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