X-Git-Url: http://git.argeo.org/?a=blobdiff_plain;f=server%2Fruntime%2Forg.argeo.server.jcr%2Fsrc%2Fmain%2Fjava%2Forg%2Fargeo%2Fjcr%2FThreadBoundJcrSessionFactory.java;h=d05d8450a4608f94c5f6e54f228aec1e3d0e2b63;hb=019e0f2af17286be08ab17c1c9e1d8ba871ec9b2;hp=ed2857ad5cf3112085dbb51e57b1b93627c49dad;hpb=833d3535cdc4b3c1d9dca4743a346acc232ba67d;p=lgpl%2Fargeo-commons.git diff --git a/server/runtime/org.argeo.server.jcr/src/main/java/org/argeo/jcr/ThreadBoundJcrSessionFactory.java b/server/runtime/org.argeo.server.jcr/src/main/java/org/argeo/jcr/ThreadBoundJcrSessionFactory.java index ed2857ad5..d05d8450a 100644 --- a/server/runtime/org.argeo.server.jcr/src/main/java/org/argeo/jcr/ThreadBoundJcrSessionFactory.java +++ b/server/runtime/org.argeo.server.jcr/src/main/java/org/argeo/jcr/ThreadBoundJcrSessionFactory.java @@ -21,8 +21,12 @@ import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; import java.util.List; +import java.util.Map; +import javax.jcr.LoginException; import javax.jcr.Repository; import javax.jcr.RepositoryException; import javax.jcr.Session; @@ -33,86 +37,157 @@ import org.apache.commons.logging.LogFactory; import org.argeo.ArgeoException; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.InitializingBean; /** Proxy JCR sessions and attach them to calling threads. */ public class ThreadBoundJcrSessionFactory implements FactoryBean, - DisposableBean { + InitializingBean, DisposableBean { private final static Log log = LogFactory .getLog(ThreadBoundJcrSessionFactory.class); private Repository repository; - private List activeSessions = Collections - .synchronizedList(new ArrayList()); private ThreadLocal session = new ThreadLocal(); - private boolean destroying = false; private final Session proxiedSession; + /** If workspace is null, default will be used. */ + private String workspace = null; private String defaultUsername = "demo"; private String defaultPassword = "demo"; + private Boolean forceDefaultCredentials = false; + + private boolean active = true; + + // monitoring + private final List threads = Collections + .synchronizedList(new ArrayList()); + private final Map activeSessions = Collections + .synchronizedMap(new HashMap()); + private MonitoringThread monitoringThread; public ThreadBoundJcrSessionFactory() { Class[] interfaces = { Session.class }; proxiedSession = (Session) Proxy.newProxyInstance(getClass() - .getClassLoader(), interfaces, new InvocationHandler() { - - public Object invoke(Object proxy, Method method, Object[] args) - throws Throwable { - Session threadSession = session.get(); - if (threadSession == null) { - if ("logout".equals(method.getName()))// no need to login - return Void.TYPE; - threadSession = login(); - session.set(threadSession); - } - - Object ret = method.invoke(threadSession, args); - if ("logout".equals(method.getName())) { - session.remove(); - if (!destroying) - activeSessions.remove(threadSession); - if (log.isTraceEnabled()) - log.trace("Logged out from JCR session " - + threadSession + "; userId=" - + threadSession.getUserID()); - } - return ret; - } - }); + .getClassLoader(), interfaces, + new JcrSessionInvocationHandler()); } + /** Logs in to the repository using various strategies. */ protected Session login() { - try { - SimpleCredentials sc = new SimpleCredentials(defaultUsername, - defaultPassword.toCharArray()); - Session sess = repository.login(sc); - if (log.isTraceEnabled()) - log.trace("Log in to JCR session " + sess + "; userId=" - + sess.getUserID()); - // Thread.dumpStack(); - activeSessions.add(sess); - return sess; - } catch (RepositoryException e) { - throw new ArgeoException("Cannot log in to repository", e); + if (!isActive()) + throw new ArgeoException("Thread bound session factory inactive"); + + // discard session previously attached to this thread + Thread thread = Thread.currentThread(); + if (activeSessions.containsKey(thread.getId())) { + Session oldSession = activeSessions.remove(thread.getId()); + oldSession.logout(); + session.remove(); } + + Session newSession = null; + // first try to login without credentials, assuming the underlying login + // module will have dealt with authentication (typically using Spring + // Security) + if (!forceDefaultCredentials) + try { + newSession = repository.login(workspace); + } catch (LoginException e1) { + log.warn("Cannot login without credentials: " + e1.getMessage()); + // invalid credentials, go to the next step + } catch (RepositoryException e1) { + // other kind of exception, fail + throw new ArgeoException("Cannot log in to repository", e1); + } + + // log using default username / password (useful for testing purposes) + if (newSession == null) + try { + SimpleCredentials sc = new SimpleCredentials(defaultUsername, + defaultPassword.toCharArray()); + newSession = repository.login(sc, workspace); + } catch (RepositoryException e) { + throw new ArgeoException("Cannot log in to repository", e); + } + + session.set(newSession); + // Log and monitor new session + if (log.isTraceEnabled()) + log.trace("Logged in to JCR session " + newSession + "; userId=" + + newSession.getUserID()); + + // monitoring + activeSessions.put(thread.getId(), newSession); + threads.add(thread); + return newSession; } public Object getObject() { return proxiedSession; } - public void destroy() throws Exception { + public void afterPropertiesSet() throws Exception { + monitoringThread = new MonitoringThread(); + monitoringThread.start(); + } + + public synchronized void destroy() throws Exception { + if (activeSessions.size() == 0) + return; + if (log.isDebugEnabled()) log.debug("Cleaning up " + activeSessions.size() + " active JCR sessions..."); - destroying = true; - for (Session sess : activeSessions) { + deactivate(); + for (Session sess : activeSessions.values()) { sess.logout(); } activeSessions.clear(); } + protected Boolean isActive() { + return active; + } + + protected synchronized void deactivate() { + active = false; + notifyAll(); + } + + protected synchronized void removeSession(Thread thread) { + if (!isActive()) + return; + activeSessions.remove(thread.getId()); + threads.remove(thread); + } + + protected synchronized void cleanDeadThreads() { + if (!isActive()) + return; + Iterator it = threads.iterator(); + while (it.hasNext()) { + Thread thread = it.next(); + if (!thread.isAlive() && isActive()) { + if (activeSessions.containsKey(thread.getId())) { + Session session = activeSessions.get(thread.getId()); + activeSessions.remove(thread.getId()); + session.logout(); + if (log.isDebugEnabled()) + log.debug("Cleaned up JCR session (userID=" + + session.getUserID() + ") from dead thread " + + thread.getId()); + } + it.remove(); + } + } + try { + wait(1000); + } catch (InterruptedException e) { + // silent + } + } + public Class getObjectType() { return Session.class; } @@ -121,6 +196,15 @@ public class ThreadBoundJcrSessionFactory implements FactoryBean, return true; } + /** + * Called before a method is actually called, allowing to check the session + * or re-login it (e.g. if authentication has changed). The default + * implementation returns the session. + */ + protected Session preCall(Session session) { + return session; + } + public void setRepository(Repository repository) { this.repository = repository; } @@ -133,4 +217,50 @@ public class ThreadBoundJcrSessionFactory implements FactoryBean, this.defaultPassword = defaultPassword; } + public void setForceDefaultCredentials(Boolean forceDefaultCredentials) { + this.forceDefaultCredentials = forceDefaultCredentials; + } + + public void setWorkspace(String workspace) { + this.workspace = workspace; + } + + protected class JcrSessionInvocationHandler implements InvocationHandler { + + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable { + Session threadSession = session.get(); + if (threadSession == null) { + if ("logout".equals(method.getName()))// no need to login + return Void.TYPE; + else if ("toString".equals(method.getName()))// maybe logging + return "Uninitialized Argeo thread bound JCR session"; + threadSession = login(); + } + + Object ret = method.invoke(threadSession, args); + if ("logout".equals(method.getName())) { + session.remove(); + Thread thread = Thread.currentThread(); + removeSession(thread); + if (log.isTraceEnabled()) + log.trace("Logged out JCR session (userId=" + + threadSession.getUserID() + ") on thread " + + thread.getId()); + } + return ret; + } + } + + /** Monitors registered thread in order to clean up dead ones. */ + private class MonitoringThread extends Thread { + + @Override + public void run() { + while (isActive()) { + cleanDeadThreads(); + } + } + + } }