001/** 002 * Copyright 2015 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.slf4j.LoggerFactory.getLogger; 020 021import javax.inject.Inject; 022import javax.jcr.Session; 023import javax.servlet.http.HttpServletRequest; 024import javax.ws.rs.ext.Provider; 025 026import org.glassfish.hk2.api.Factory; 027import org.glassfish.jersey.process.internal.RequestScoped; 028import org.slf4j.Logger; 029 030/** 031 * Provide a JCR session within the current request context 032 * 033 * @author awoods 034 */ 035@Provider 036@RequestScoped 037public class SessionProvider implements Factory<Session> { 038 039 @Inject 040 SessionFactory sessionFactory; 041 042 private HttpServletRequest request; 043 044 /** 045 * Create a new session provider for a request 046 * @param request the request 047 */ 048 @Inject 049 public SessionProvider(final HttpServletRequest request) { 050 this.request = request; 051 } 052 053 private static final Logger LOGGER = getLogger(SessionProvider.class); 054 055 @Override 056 public Session provide() { 057 final Session session = sessionFactory.getSession(request); 058 LOGGER.trace("Providing new session {}", session); 059 return session; 060 } 061 062 @Override 063 public void dispose(final Session session) { 064 LOGGER.trace("Disposing session {}", session); 065 066 if (session.isLive() && !isInTransaction(session)) { 067 session.logout(); 068 } 069 } 070}