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