3 import java
.lang
.reflect
.InvocationHandler
;
4 import java
.lang
.reflect
.Method
;
5 import java
.lang
.reflect
.Proxy
;
6 import java
.util
.ArrayList
;
7 import java
.util
.Collections
;
10 import javax
.jcr
.Repository
;
11 import javax
.jcr
.RepositoryException
;
12 import javax
.jcr
.Session
;
14 import org
.apache
.commons
.logging
.Log
;
15 import org
.apache
.commons
.logging
.LogFactory
;
16 import org
.argeo
.ArgeoException
;
17 import org
.springframework
.beans
.factory
.DisposableBean
;
18 import org
.springframework
.beans
.factory
.FactoryBean
;
20 public class ThreadBoundJcrSessionFactory
implements FactoryBean
,
22 private final static Log log
= LogFactory
23 .getLog(ThreadBoundJcrSessionFactory
.class);
25 private Repository repository
;
26 private List
<Session
> activeSessions
= Collections
27 .synchronizedList(new ArrayList
<Session
>());
29 private ThreadLocal
<Session
> session
= new ThreadLocal
<Session
>();
30 private boolean destroying
= false;
31 private final Session proxiedSession
;
33 public ThreadBoundJcrSessionFactory() {
34 Class
<?
>[] interfaces
= { Session
.class };
35 proxiedSession
= (Session
) Proxy
.newProxyInstance(getClass()
36 .getClassLoader(), interfaces
, new InvocationHandler() {
38 public Object
invoke(Object proxy
, Method method
, Object
[] args
)
40 Session threadSession
= session
.get();
41 if (threadSession
== null) {
42 if ("logout".equals(method
.getName()))// no need to login
44 threadSession
= login();
45 session
.set(threadSession
);
48 Object ret
= method
.invoke(threadSession
, args
);
49 if ("logout".equals(method
.getName())) {
52 activeSessions
.remove(threadSession
);
53 if (log
.isTraceEnabled())
54 log
.trace("Logged out from JCR session "
55 + threadSession
+ "; userId="
56 + threadSession
.getUserID());
63 protected Session
login() {
65 Session sess
= repository
.login();
66 if (log
.isTraceEnabled())
67 log
.trace("Log in to JCR session " + sess
+ "; userId="
69 // Thread.dumpStack();
70 activeSessions
.add(sess
);
72 } catch (RepositoryException e
) {
73 throw new ArgeoException("Cannot log in to repository", e
);
77 public Object
getObject() {
78 return proxiedSession
;
81 public void destroy() throws Exception
{
82 if (log
.isDebugEnabled())
83 log
.debug("Cleaning up " + activeSessions
.size()
84 + " active JCR sessions...");
87 for (Session sess
: activeSessions
) {
90 activeSessions
.clear();
93 public Class
<?
extends Session
> getObjectType() {
97 public boolean isSingleton() {
101 public void setRepository(Repository repository
) {
102 this.repository
= repository
;