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