2 * Copyright (C) 2007-2012 Argeo GmbH
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.
16 package org
.argeo
.jcr
;
18 import java
.lang
.reflect
.InvocationHandler
;
19 import java
.lang
.reflect
.InvocationTargetException
;
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
;
38 /** 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
;
45 /** can be injected as list, only used if repository is null */
46 private List
<Repository
> repositories
;
48 private ThreadLocal
<Session
> session
= new ThreadLocal
<Session
>();
49 private final Session proxiedSession
;
50 /** If workspace is null, default will be used. */
51 private String workspace
= null;
53 private String defaultUsername
= "demo";
54 private String defaultPassword
= "demo";
55 private Boolean forceDefaultCredentials
= false;
57 private boolean active
= true;
60 private final List
<Thread
> threads
= Collections
61 .synchronizedList(new ArrayList
<Thread
>());
62 private final Map
<Long
, Session
> activeSessions
= Collections
63 .synchronizedMap(new HashMap
<Long
, Session
>());
64 private MonitoringThread monitoringThread
;
66 public ThreadBoundJcrSessionFactory() {
67 Class
<?
>[] interfaces
= { Session
.class };
68 proxiedSession
= (Session
) Proxy
.newProxyInstance(
69 ThreadBoundJcrSessionFactory
.class.getClassLoader(),
70 interfaces
, new JcrSessionInvocationHandler());
73 /** Logs in to the repository using various strategies. */
74 protected synchronized Session
login() {
76 throw new ArgeoJcrException("Thread bound session factory inactive");
78 // discard session previously attached to this thread
79 Thread thread
= Thread
.currentThread();
80 if (activeSessions
.containsKey(thread
.getId())) {
81 Session oldSession
= activeSessions
.remove(thread
.getId());
86 Session newSession
= null;
87 // first try to login without credentials, assuming the underlying login
88 // module will have dealt with authentication (typically using Spring
90 if (!forceDefaultCredentials
)
92 newSession
= repository().login(workspace
);
93 } catch (LoginException e1
) {
94 log
.warn("Cannot login without credentials: " + e1
.getMessage());
95 // invalid credentials, go to the next step
96 } catch (RepositoryException e1
) {
97 // other kind of exception, fail
98 throw new ArgeoJcrException("Cannot log in to repository", e1
);
101 // log using default username / password (useful for testing purposes)
102 if (newSession
== null)
104 SimpleCredentials sc
= new SimpleCredentials(defaultUsername
,
105 defaultPassword
.toCharArray());
106 newSession
= repository().login(sc
, workspace
);
107 } catch (RepositoryException e
) {
108 throw new ArgeoJcrException("Cannot log in to repository", e
);
111 session
.set(newSession
);
112 // Log and monitor new session
113 if (log
.isTraceEnabled())
114 log
.trace("Logged in to JCR session " + newSession
+ "; userId="
115 + newSession
.getUserID());
118 activeSessions
.put(thread
.getId(), newSession
);
123 public Object
getObject() {
124 return proxiedSession
;
127 public void init() throws Exception
{
128 log
.error("SHOULD NOT BE USED ANYMORE");
129 monitoringThread
= new MonitoringThread();
130 monitoringThread
.start();
133 public void dispose() throws Exception
{
134 // if (activeSessions.size() == 0)
137 if (log
.isTraceEnabled())
138 log
.trace("Cleaning up " + activeSessions
.size()
139 + " active JCR sessions...");
142 for (Session sess
: activeSessions
.values()) {
143 JcrUtils
.logoutQuietly(sess
);
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
.isTraceEnabled())
176 log
.trace("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 ArgeoJcrException("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");