001/** 002 * Copyright 2014 DuraSpace, Inc. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.fcrepo.http.commons.session; 017 018import static org.fcrepo.kernel.impl.services.TransactionServiceImpl.isInTransaction; 019import static org.modeshape.jcr.SessionUtils.unregisterObservationManager; 020import static org.slf4j.LoggerFactory.getLogger; 021 022import javax.inject.Inject; 023import javax.jcr.Session; 024import javax.servlet.http.HttpServletRequest; 025import javax.ws.rs.ext.Provider; 026 027import org.glassfish.hk2.api.Factory; 028import org.glassfish.jersey.process.internal.RequestScoped; 029import org.slf4j.Logger; 030 031/** 032 * Provide a JCR session within the current request context 033 * 034 * @author awoods 035 */ 036@Provider 037@RequestScoped 038public class SessionProvider implements Factory<Session> { 039 040 @Inject 041 SessionFactory sessionFactory; 042 043 private HttpServletRequest request; 044 045 /** 046 * Create a new session provider for a request 047 * @param request 048 */ 049 @Inject 050 public SessionProvider(final HttpServletRequest request) { 051 this.request = request; 052 } 053 054 private static final Logger LOGGER = getLogger(SessionProvider.class); 055 056 @Override 057 public Session provide() { 058 final Session session = sessionFactory.getSession(request); 059 LOGGER.trace("Providing new session {}", session); 060 return session; 061 } 062 063 @Override 064 public void dispose(final Session session) { 065 LOGGER.trace("Disposing session {}", session); 066 067 if (session.isLive() && !isInTransaction(session)) { 068 unregisterObservationManager(session); 069 session.logout(); 070 } 071 } 072}