1 package org
.argeo
.cms
.jcr
.acr
;
3 import java
.security
.PrivilegedAction
;
4 import java
.util
.Collections
;
5 import java
.util
.HashMap
;
8 import javax
.jcr
.Repository
;
9 import javax
.jcr
.RepositoryException
;
10 import javax
.jcr
.Session
;
11 import javax
.security
.auth
.Subject
;
13 import org
.argeo
.jcr
.JcrException
;
14 import org
.argeo
.jcr
.JcrUtils
;
16 /** Manages JCR {@link Session} in an ACR context. */
17 class JcrSessionAdapter
{
18 private Repository repository
;
19 private Subject subject
;
21 private Map
<Thread
, Map
<String
, Session
>> threadSessions
= Collections
.synchronizedMap(new HashMap
<>());
23 private boolean closed
= false;
25 private Thread lastRetrievingThread
= null;
27 public JcrSessionAdapter(Repository repository
, Subject subject
) {
28 this.repository
= repository
;
29 this.subject
= subject
;
32 public synchronized void close() {
33 for (Map
<String
, Session
> sessions
: threadSessions
.values()) {
34 for (Session session
: sessions
.values()) {
35 JcrUtils
.logoutQuietly(session
);
39 threadSessions
.clear();
43 public synchronized Session
getSession(String workspace
) {
45 throw new IllegalStateException("JCR session adapter is closed.");
47 Thread currentThread
= Thread
.currentThread();
48 if (lastRetrievingThread
== null)
49 lastRetrievingThread
= currentThread
;
51 Map
<String
, Session
> threadSession
= threadSessions
.get(currentThread
);
52 if (threadSession
== null) {
53 threadSession
= new HashMap
<>();
54 threadSessions
.put(currentThread
, threadSession
);
57 Session session
= threadSession
.get(workspace
);
58 if (session
== null) {
59 session
= Subject
.doAs(subject
, (PrivilegedAction
<Session
>) () -> {
61 Session sess
= repository
.login(workspace
);
63 } catch (RepositoryException e
) {
64 throw new IllegalStateException("Cannot log in to " + workspace
, e
);
67 threadSession
.put(workspace
, session
);
70 if (lastRetrievingThread
!= currentThread
) {
72 session
.refresh(true);
73 } catch (RepositoryException e
) {
74 throw new JcrException("Cannot refresh JCR session " + session
, e
);
77 lastRetrievingThread
= currentThread
;