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
.apache
.jackrabbit
.core
.SessionImpl
;
14 import org
.argeo
.api
.acr
.spi
.ProvidedSession
;
15 import org
.argeo
.jcr
.JcrException
;
16 import org
.argeo
.jcr
.JcrUtils
;
18 /** Manages JCR {@link Session} in an ACR context. */
19 class JcrSessionAdapter
{
20 private Repository repository
;
21 private Subject subject
;
23 private ProvidedSession contentSession
;
25 private Map
<Thread
, Map
<String
, Session
>> threadSessions
= Collections
.synchronizedMap(new HashMap
<>());
27 private boolean closed
= false;
29 private Thread lastRetrievingThread
= null;
31 public JcrSessionAdapter(Repository repository
, ProvidedSession contentSession
, Subject subject
) {
32 this.repository
= repository
;
33 this.contentSession
= contentSession
;
34 this.subject
= subject
;
37 public synchronized void close() {
38 for (Map
<String
, Session
> sessions
: threadSessions
.values()) {
39 for (Session session
: sessions
.values()) {
40 JcrUtils
.logoutQuietly(session
);
44 threadSessions
.clear();
48 public synchronized Session
getSession(String workspace
) {
50 throw new IllegalStateException("JCR session adapter is closed.");
52 Thread currentThread
= Thread
.currentThread();
53 if (lastRetrievingThread
== null)
54 lastRetrievingThread
= currentThread
;
56 Map
<String
, Session
> threadSession
= threadSessions
.get(currentThread
);
57 if (threadSession
== null) {
58 threadSession
= new HashMap
<>();
59 threadSessions
.put(currentThread
, threadSession
);
62 Session session
= threadSession
.get(workspace
);
63 if (session
== null) {
64 session
= Subject
.doAs(subject
, (PrivilegedAction
<Session
>) () -> {
66 // String username = CurrentUser.getUsername(subject);
67 // SimpleCredentials credentials = new SimpleCredentials(username, new char[0]);
68 // credentials.setAttribute(ProvidedSession.class.getName(), contentSession);
69 Session sess
= repository
.login(workspace
);
70 // Jackrabbit specific:
71 ((SessionImpl
)sess
).setAttribute(ProvidedSession
.class.getName(), contentSession
);
73 } catch (RepositoryException e
) {
74 throw new IllegalStateException("Cannot log in to " + workspace
, e
);
77 threadSession
.put(workspace
, session
);
80 if (lastRetrievingThread
!= currentThread
) {
82 session
.refresh(true);
83 } catch (RepositoryException e
) {
84 throw new JcrException("Cannot refresh JCR session " + session
, e
);
87 lastRetrievingThread
= currentThread
;