001/*
002 * (C) Copyright 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
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 *
016 * Contributors:
017 *     bstefanescu
018 */
019package org.nuxeo.ecm.webengine.jaxrs.session;
020
021import java.util.HashMap;
022import java.util.Map;
023
024import javax.servlet.http.HttpServletRequest;
025
026import org.nuxeo.ecm.core.api.CloseableCoreSession;
027import org.nuxeo.ecm.core.api.CoreInstance;
028import org.nuxeo.ecm.core.api.CoreSession;
029
030/**
031 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
032 */
033public abstract class CoreSessionProvider<REF extends SessionRef> {
034
035    protected Map<String, REF> sessions;
036
037    protected CoreSessionProvider() {
038        this.sessions = new HashMap<String, REF>();
039    }
040
041    /**
042     * The HTTP request was consumed. Do any request level cleanup now.
043     */
044    protected abstract void onRequestDone(HttpServletRequest request);
045
046    protected abstract REF createSessionRef(CloseableCoreSession session);
047
048    public SessionRef[] getSessions() {
049        return sessions.values().toArray(new SessionRef[sessions.size()]);
050    }
051
052    public SessionRef getSessionRef(HttpServletRequest request, String repoName) {
053        REF ref = sessions.get(repoName);
054        if (ref == null) {
055            ref = createSessionRef(createSession(request, repoName));
056            sessions.put(repoName, ref);
057        }
058        return ref;
059    }
060
061    public CoreSession getSession(HttpServletRequest request, String repoName) {
062        return getSessionRef(request, repoName).get();
063    }
064
065    protected CloseableCoreSession createSession(HttpServletRequest request, String repoName) {
066        if (request.getUserPrincipal() == null) {
067            throw new java.lang.IllegalStateException("Not authenticated user is trying to get a core session");
068        }
069        return CoreInstance.openCoreSession(repoName);
070    }
071
072    public boolean hasSessions() {
073        return !sessions.isEmpty();
074    }
075
076    protected void destroy() {
077        for (SessionRef ref : getSessions()) {
078            ref.destroy();
079        }
080        sessions = null;
081    }
082
083}