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
.InvocationTargetException
;
21 import java
.lang
.reflect
.Method
;
22 import java
.lang
.reflect
.Proxy
;
23 import java
.util
.ArrayList
;
24 import java
.util
.Collections
;
25 import java
.util
.HashMap
;
26 import java
.util
.Iterator
;
27 import java
.util
.List
;
30 import javax
.jcr
.LoginException
;
31 import javax
.jcr
.Repository
;
32 import javax
.jcr
.RepositoryException
;
33 import javax
.jcr
.Session
;
34 import javax
.jcr
.SimpleCredentials
;
36 import org
.apache
.commons
.logging
.Log
;
37 import org
.apache
.commons
.logging
.LogFactory
;
38 import org
.argeo
.ArgeoException
;
40 /** Proxy JCR sessions and attach them to calling threads. */
41 public abstract class ThreadBoundJcrSessionFactory
{
42 private final static Log log
= LogFactory
43 .getLog(ThreadBoundJcrSessionFactory
.class);
45 private Repository repository
;
46 /** can be injected as list, only used if repository is null */
47 private List
<Repository
> repositories
;
49 private ThreadLocal
<Session
> session
= new ThreadLocal
<Session
>();
50 private final Session proxiedSession
;
51 /** If workspace is null, default will be used. */
52 private String workspace
= null;
54 private String defaultUsername
= "demo";
55 private String defaultPassword
= "demo";
56 private Boolean forceDefaultCredentials
= false;
58 private boolean active
= true;
61 private final List
<Thread
> threads
= Collections
62 .synchronizedList(new ArrayList
<Thread
>());
63 private final Map
<Long
, Session
> activeSessions
= Collections
64 .synchronizedMap(new HashMap
<Long
, Session
>());
65 private MonitoringThread monitoringThread
;
67 public ThreadBoundJcrSessionFactory() {
68 Class
<?
>[] interfaces
= { Session
.class };
69 proxiedSession
= (Session
) Proxy
.newProxyInstance(getClass()
70 .getClassLoader(), interfaces
,
71 new JcrSessionInvocationHandler());
74 /** Logs in to the repository using various strategies. */
75 protected synchronized Session
login() {
77 throw new ArgeoException("Thread bound session factory inactive");
79 // discard session previously attached to this thread
80 Thread thread
= Thread
.currentThread();
81 if (activeSessions
.containsKey(thread
.getId())) {
82 Session oldSession
= activeSessions
.remove(thread
.getId());
87 Session newSession
= null;
88 // first try to login without credentials, assuming the underlying login
89 // module will have dealt with authentication (typically using Spring
91 if (!forceDefaultCredentials
)
93 newSession
= repository().login(workspace
);
94 } catch (LoginException e1
) {
95 log
.warn("Cannot login without credentials: " + e1
.getMessage());
96 // invalid credentials, go to the next step
97 } catch (RepositoryException e1
) {
98 // other kind of exception, fail
99 throw new ArgeoException("Cannot log in to repository", e1
);
102 // log using default username / password (useful for testing purposes)
103 if (newSession
== null)
105 SimpleCredentials sc
= new SimpleCredentials(defaultUsername
,
106 defaultPassword
.toCharArray());
107 newSession
= repository().login(sc
, workspace
);
108 } catch (RepositoryException e
) {
109 throw new ArgeoException("Cannot log in to repository", e
);
112 session
.set(newSession
);
113 // Log and monitor new session
114 if (log
.isTraceEnabled())
115 log
.trace("Logged in to JCR session " + newSession
+ "; userId="
116 + newSession
.getUserID());
119 activeSessions
.put(thread
.getId(), newSession
);
124 public Object
getObject() {
125 return proxiedSession
;
128 public void init() throws Exception
{
129 monitoringThread
= new MonitoringThread();
130 monitoringThread
.start();
133 public synchronized void dispose() throws Exception
{
134 if (activeSessions
.size() == 0)
137 if (log
.isDebugEnabled())
138 log
.debug("Cleaning up " + activeSessions
.size()
139 + " active JCR sessions...");
142 for (Session sess
: activeSessions
.values()) {
145 activeSessions
.clear();
148 protected Boolean
isActive() {
152 protected synchronized void deactivate() {
157 protected synchronized void removeSession(Thread thread
) {
160 activeSessions
.remove(thread
.getId());
161 threads
.remove(thread
);
164 protected synchronized void cleanDeadThreads() {
167 Iterator
<Thread
> it
= threads
.iterator();
168 while (it
.hasNext()) {
169 Thread thread
= it
.next();
170 if (!thread
.isAlive() && isActive()) {
171 if (activeSessions
.containsKey(thread
.getId())) {
172 Session session
= activeSessions
.get(thread
.getId());
173 activeSessions
.remove(thread
.getId());
175 if (log
.isDebugEnabled())
176 log
.debug("Cleaned up JCR session (userID="
177 + session
.getUserID() + ") from dead thread "
185 } catch (InterruptedException e
) {
190 public Class
<?
extends Session
> getObjectType() {
191 return Session
.class;
194 public boolean isSingleton() {
199 * Called before a method is actually called, allowing to check the session
200 * or re-login it (e.g. if authentication has changed). The default
201 * implementation returns the session.
203 protected Session
preCall(Session session
) {
207 protected Repository
repository() {
208 if (repository
!= null)
210 if (repositories
!= null) {
211 // hardened for OSGi dynamic services
212 Iterator
<Repository
> it
= repositories
.iterator();
216 throw new ArgeoException("No repository injected");
219 // /** Useful for declarative registration of OSGi services (blueprint) */
220 // public void register(Repository repository, Map<?, ?> params) {
221 // this.repository = repository;
224 // /** Useful for declarative registration of OSGi services (blueprint) */
225 // public void unregister(Repository repository, Map<?, ?> params) {
226 // this.repository = null;
229 public void setRepository(Repository repository
) {
230 this.repository
= repository
;
233 public void setRepositories(List
<Repository
> repositories
) {
234 this.repositories
= repositories
;
237 public void setDefaultUsername(String defaultUsername
) {
238 this.defaultUsername
= defaultUsername
;
241 public void setDefaultPassword(String defaultPassword
) {
242 this.defaultPassword
= defaultPassword
;
245 public void setForceDefaultCredentials(Boolean forceDefaultCredentials
) {
246 this.forceDefaultCredentials
= forceDefaultCredentials
;
249 public void setWorkspace(String workspace
) {
250 this.workspace
= workspace
;
253 protected class JcrSessionInvocationHandler
implements InvocationHandler
{
255 public Object
invoke(Object proxy
, Method method
, Object
[] args
)
256 throws Throwable
, RepositoryException
{
257 Session threadSession
= session
.get();
258 if (threadSession
== null) {
259 if ("logout".equals(method
.getName()))// no need to login
261 else if ("toString".equals(method
.getName()))// maybe logging
262 return "Uninitialized Argeo thread bound JCR session";
263 threadSession
= login();
266 preCall(threadSession
);
269 ret
= method
.invoke(threadSession
, args
);
270 } catch (InvocationTargetException e
) {
271 Throwable cause
= e
.getCause();
272 if (cause
instanceof RepositoryException
)
273 throw (RepositoryException
) cause
;
277 if ("logout".equals(method
.getName())) {
279 Thread thread
= Thread
.currentThread();
280 removeSession(thread
);
281 if (log
.isTraceEnabled())
282 log
.trace("Logged out JCR session (userId="
283 + threadSession
.getUserID() + ") on thread "
290 /** Monitors registered thread in order to clean up dead ones. */
291 private class MonitoringThread
extends Thread
{
293 public MonitoringThread() {
294 super("ThreadBound JCR Session Monitor");