001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     bstefanescu
011 */
012package org.nuxeo.ecm.webengine.jaxrs.session.impl;
013
014import javax.servlet.http.HttpServletRequest;
015
016import org.nuxeo.ecm.core.api.CoreSession;
017import org.nuxeo.ecm.webengine.jaxrs.session.CoreSessionProvider;
018import org.nuxeo.ecm.webengine.jaxrs.session.SessionRef;
019import org.nuxeo.ecm.webengine.jaxrs.session.impl.PerRequestCoreProvider.Ref;
020
021/**
022 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
023 */
024public class PerRequestCoreProvider extends CoreSessionProvider<Ref> {
025
026    public static class Ref implements SessionRef {
027        protected CoreSession session;
028
029        public Ref(CoreSession session) {
030            this.session = session;
031        }
032
033        @Override
034        public CoreSession get() {
035            return session;
036        }
037
038        @Override
039        public void unget() {
040            // do nothing
041        }
042
043        public void destroy() {
044            try {
045                session.close();
046            } finally {
047                session = null;
048            }
049        }
050    }
051
052    @Override
053    protected void onRequestDone(HttpServletRequest request) {
054        // destroy all sessions created during this request
055        if (!sessions.isEmpty()) {
056            for (SessionRef ref : getSessions()) {
057                ref.destroy();
058            }
059        }
060        sessions = null;
061    }
062
063    @Override
064    protected Ref createSessionRef(CoreSession session) {
065        return new Ref(session);
066    }
067
068}