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
;
39 /** Proxy JCR sessions and attach them to calling threads. */
40 public abstract class ThreadBoundJcrSessionFactory
{
41 private final static Log log
= LogFactory
42 .getLog(ThreadBoundJcrSessionFactory
.class);
44 private Repository repository
;
46 private ThreadLocal
<Session
> session
= new ThreadLocal
<Session
>();
47 private final Session proxiedSession
;
48 /** If workspace is null, default will be used. */
49 private String workspace
= null;
51 private String defaultUsername
= "demo";
52 private String defaultPassword
= "demo";
53 private Boolean forceDefaultCredentials
= false;
55 private boolean active
= true;
58 private final List
<Thread
> threads
= Collections
59 .synchronizedList(new ArrayList
<Thread
>());
60 private final Map
<Long
, Session
> activeSessions
= Collections
61 .synchronizedMap(new HashMap
<Long
, Session
>());
62 private MonitoringThread monitoringThread
;
64 public ThreadBoundJcrSessionFactory() {
65 Class
<?
>[] interfaces
= { Session
.class };
66 proxiedSession
= (Session
) Proxy
.newProxyInstance(getClass()
67 .getClassLoader(), interfaces
,
68 new JcrSessionInvocationHandler());
71 /** Logs in to the repository using various strategies. */
72 protected Session
login() {
74 throw new ArgeoException("Thread bound session factory inactive");
76 // discard session previously attached to this thread
77 Thread thread
= Thread
.currentThread();
78 if (activeSessions
.containsKey(thread
.getId())) {
79 Session oldSession
= activeSessions
.remove(thread
.getId());
84 Session newSession
= null;
85 // first try to login without credentials, assuming the underlying login
86 // module will have dealt with authentication (typically using Spring
88 if (!forceDefaultCredentials
)
90 newSession
= repository
.login(workspace
);
91 } catch (LoginException e1
) {
92 log
.warn("Cannot login without credentials: " + e1
.getMessage());
93 // invalid credentials, go to the next step
94 } catch (RepositoryException e1
) {
95 // other kind of exception, fail
96 throw new ArgeoException("Cannot log in to repository", e1
);
99 // log using default username / password (useful for testing purposes)
100 if (newSession
== null)
102 SimpleCredentials sc
= new SimpleCredentials(defaultUsername
,
103 defaultPassword
.toCharArray());
104 newSession
= repository
.login(sc
, workspace
);
105 } catch (RepositoryException e
) {
106 throw new ArgeoException("Cannot log in to repository", e
);
109 session
.set(newSession
);
110 // Log and monitor new session
111 if (log
.isTraceEnabled())
112 log
.trace("Logged in to JCR session " + newSession
+ "; userId="
113 + newSession
.getUserID());
116 activeSessions
.put(thread
.getId(), newSession
);
121 public Object
getObject() {
122 return proxiedSession
;
125 public void init() throws Exception
{
126 monitoringThread
= new MonitoringThread();
127 monitoringThread
.start();
130 public synchronized void dispose() throws Exception
{
131 if (activeSessions
.size() == 0)
134 if (log
.isDebugEnabled())
135 log
.debug("Cleaning up " + activeSessions
.size()
136 + " active JCR sessions...");
139 for (Session sess
: activeSessions
.values()) {
142 activeSessions
.clear();
145 protected Boolean
isActive() {
149 protected synchronized void deactivate() {
154 protected synchronized void removeSession(Thread thread
) {
157 activeSessions
.remove(thread
.getId());
158 threads
.remove(thread
);
161 protected synchronized void cleanDeadThreads() {
164 Iterator
<Thread
> it
= threads
.iterator();
165 while (it
.hasNext()) {
166 Thread thread
= it
.next();
167 if (!thread
.isAlive() && isActive()) {
168 if (activeSessions
.containsKey(thread
.getId())) {
169 Session session
= activeSessions
.get(thread
.getId());
170 activeSessions
.remove(thread
.getId());
172 if (log
.isDebugEnabled())
173 log
.debug("Cleaned up JCR session (userID="
174 + session
.getUserID() + ") from dead thread "
182 } catch (InterruptedException e
) {
187 public Class
<?
extends Session
> getObjectType() {
188 return Session
.class;
191 public boolean isSingleton() {
196 * Called before a method is actually called, allowing to check the session
197 * or re-login it (e.g. if authentication has changed). The default
198 * implementation returns the session.
200 protected Session
preCall(Session session
) {
204 public void setRepository(Repository repository
) {
205 this.repository
= repository
;
208 public void setDefaultUsername(String defaultUsername
) {
209 this.defaultUsername
= defaultUsername
;
212 public void setDefaultPassword(String defaultPassword
) {
213 this.defaultPassword
= defaultPassword
;
216 public void setForceDefaultCredentials(Boolean forceDefaultCredentials
) {
217 this.forceDefaultCredentials
= forceDefaultCredentials
;
220 public void setWorkspace(String workspace
) {
221 this.workspace
= workspace
;
224 protected class JcrSessionInvocationHandler
implements InvocationHandler
{
226 public Object
invoke(Object proxy
, Method method
, Object
[] args
)
228 Session threadSession
= session
.get();
229 if (threadSession
== null) {
230 if ("logout".equals(method
.getName()))// no need to login
232 else if ("toString".equals(method
.getName()))// maybe logging
233 return "Uninitialized Argeo thread bound JCR session";
234 threadSession
= login();
237 preCall(threadSession
);
238 Object ret
= method
.invoke(threadSession
, args
);
239 if ("logout".equals(method
.getName())) {
241 Thread thread
= Thread
.currentThread();
242 removeSession(thread
);
243 if (log
.isTraceEnabled())
244 log
.trace("Logged out JCR session (userId="
245 + threadSession
.getUserID() + ") on thread "
252 /** Monitors registered thread in order to clean up dead ones. */
253 private class MonitoringThread
extends Thread
{