2 * Copyright (C) 2010 Mathieu Baudier <mbaudier@argeo.org>
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package org
.argeo
.jcr
;
19 import java
.lang
.reflect
.InvocationHandler
;
20 import java
.lang
.reflect
.Method
;
21 import java
.lang
.reflect
.Proxy
;
22 import java
.util
.ArrayList
;
23 import java
.util
.Collections
;
24 import java
.util
.HashMap
;
25 import java
.util
.Iterator
;
26 import java
.util
.List
;
29 import javax
.jcr
.LoginException
;
30 import javax
.jcr
.Repository
;
31 import javax
.jcr
.RepositoryException
;
32 import javax
.jcr
.Session
;
33 import javax
.jcr
.SimpleCredentials
;
35 import org
.apache
.commons
.logging
.Log
;
36 import org
.apache
.commons
.logging
.LogFactory
;
37 import org
.argeo
.ArgeoException
;
38 import org
.springframework
.beans
.factory
.DisposableBean
;
39 import org
.springframework
.beans
.factory
.FactoryBean
;
40 import org
.springframework
.beans
.factory
.InitializingBean
;
42 /** Proxy JCR sessions and attach them to calling threads. */
43 public class ThreadBoundJcrSessionFactory
implements FactoryBean
,
44 InitializingBean
, DisposableBean
{
45 private final static Log log
= LogFactory
46 .getLog(ThreadBoundJcrSessionFactory
.class);
48 private Repository repository
;
50 private ThreadLocal
<Session
> session
= new ThreadLocal
<Session
>();
51 private final Session proxiedSession
;
52 /** If workspace is null, default will be used. */
53 private String workspace
= null;
55 private String defaultUsername
= "demo";
56 private String defaultPassword
= "demo";
57 private Boolean forceDefaultCredentials
= false;
59 private boolean active
= true;
62 private final List
<Thread
> threads
= Collections
63 .synchronizedList(new ArrayList
<Thread
>());
64 private final Map
<Long
, Session
> activeSessions
= Collections
65 .synchronizedMap(new HashMap
<Long
, Session
>());
66 private MonitoringThread monitoringThread
;
68 public ThreadBoundJcrSessionFactory() {
69 Class
<?
>[] interfaces
= { Session
.class };
70 proxiedSession
= (Session
) Proxy
.newProxyInstance(getClass()
71 .getClassLoader(), interfaces
,
72 new JcrSessionInvocationHandler());
75 /** Logs in to the repository using various strategies. */
76 protected Session
login() {
78 throw new ArgeoException("Thread bound session factory inactive");
80 // discard session previously attached to this thread
81 Thread thread
= Thread
.currentThread();
82 if (activeSessions
.containsKey(thread
.getId())) {
83 Session oldSession
= activeSessions
.remove(thread
.getId());
88 Session newSession
= null;
89 // first try to login without credentials, assuming the underlying login
90 // module will have dealt with authentication (typically using Spring
92 if (!forceDefaultCredentials
)
94 newSession
= repository
.login(workspace
);
95 } catch (LoginException e1
) {
96 log
.warn("Cannot login without credentials: " + e1
.getMessage());
97 // invalid credentials, go to the next step
98 } catch (RepositoryException e1
) {
99 // other kind of exception, fail
100 throw new ArgeoException("Cannot log in to repository", e1
);
103 // log using default username / password (useful for testing purposes)
104 if (newSession
== null)
106 SimpleCredentials sc
= new SimpleCredentials(defaultUsername
,
107 defaultPassword
.toCharArray());
108 newSession
= repository
.login(sc
, workspace
);
109 } catch (RepositoryException e
) {
110 throw new ArgeoException("Cannot log in to repository", e
);
113 session
.set(newSession
);
114 // Log and monitor new session
115 if (log
.isTraceEnabled())
116 log
.trace("Logged in to JCR session " + newSession
+ "; userId="
117 + newSession
.getUserID());
120 activeSessions
.put(thread
.getId(), newSession
);
125 public Object
getObject() {
126 return proxiedSession
;
129 public void afterPropertiesSet() throws Exception
{
130 monitoringThread
= new MonitoringThread();
131 monitoringThread
.start();
134 public synchronized void destroy() throws Exception
{
135 if (activeSessions
.size() == 0)
138 if (log
.isDebugEnabled())
139 log
.debug("Cleaning up " + activeSessions
.size()
140 + " active JCR sessions...");
143 for (Session sess
: activeSessions
.values()) {
146 activeSessions
.clear();
149 protected Boolean
isActive() {
153 protected synchronized void deactivate() {
158 protected synchronized void removeSession(Thread thread
) {
161 activeSessions
.remove(thread
.getId());
162 threads
.remove(thread
);
165 protected synchronized void cleanDeadThreads() {
168 Iterator
<Thread
> it
= threads
.iterator();
169 while (it
.hasNext()) {
170 Thread thread
= it
.next();
171 if (!thread
.isAlive() && isActive()) {
172 if (activeSessions
.containsKey(thread
.getId())) {
173 Session session
= activeSessions
.get(thread
.getId());
174 activeSessions
.remove(thread
.getId());
176 if (log
.isDebugEnabled())
177 log
.debug("Cleaned up JCR session (userID="
178 + session
.getUserID() + ") from dead thread "
186 } catch (InterruptedException e
) {
191 public Class
<?
extends Session
> getObjectType() {
192 return Session
.class;
195 public boolean isSingleton() {
200 * Called before a method is actually called, allowing to check the session
201 * or re-login it (e.g. if authentication has changed). The default
202 * implementation returns the session.
204 protected Session
preCall(Session session
) {
208 public void setRepository(Repository repository
) {
209 this.repository
= repository
;
212 public void setDefaultUsername(String defaultUsername
) {
213 this.defaultUsername
= defaultUsername
;
216 public void setDefaultPassword(String defaultPassword
) {
217 this.defaultPassword
= defaultPassword
;
220 public void setForceDefaultCredentials(Boolean forceDefaultCredentials
) {
221 this.forceDefaultCredentials
= forceDefaultCredentials
;
224 public void setWorkspace(String workspace
) {
225 this.workspace
= workspace
;
228 protected class JcrSessionInvocationHandler
implements InvocationHandler
{
230 public Object
invoke(Object proxy
, Method method
, Object
[] args
)
232 Session threadSession
= session
.get();
233 if (threadSession
== null) {
234 if ("logout".equals(method
.getName()))// no need to login
236 else if ("toString".equals(method
.getName()))// maybe logging
237 return "Uninitialized Argeo thread bound JCR session";
238 threadSession
= login();
241 Object ret
= method
.invoke(threadSession
, args
);
242 if ("logout".equals(method
.getName())) {
244 Thread thread
= Thread
.currentThread();
245 removeSession(thread
);
246 if (log
.isTraceEnabled())
247 log
.trace("Logged out JCR session (userId="
248 + threadSession
.getUserID() + ") on thread "
255 /** Monitors registered thread in order to clean up dead ones. */
256 private class MonitoringThread
extends Thread
{