]> git.argeo.org Git - lgpl/argeo-commons.git/blob - jcr/acr/JcrSessionAdapter.java
Prepare next development cycle
[lgpl/argeo-commons.git] / jcr / acr / JcrSessionAdapter.java
1 package org.argeo.cms.jcr.acr;
2
3 import java.security.PrivilegedAction;
4 import java.util.Collections;
5 import java.util.HashMap;
6 import java.util.Map;
7
8 import javax.jcr.Repository;
9 import javax.jcr.RepositoryException;
10 import javax.jcr.Session;
11 import javax.security.auth.Subject;
12
13 import org.argeo.jcr.JcrException;
14 import org.argeo.jcr.JcrUtils;
15
16 /** Manages JCR {@link Session} in an ACR context. */
17 class JcrSessionAdapter {
18 private Repository repository;
19 private Subject subject;
20
21 private Map<Thread, Map<String, Session>> threadSessions = Collections.synchronizedMap(new HashMap<>());
22
23 private boolean closed = false;
24
25 private Thread lastRetrievingThread = null;
26
27 public JcrSessionAdapter(Repository repository, Subject subject) {
28 this.repository = repository;
29 this.subject = subject;
30 }
31
32 public synchronized void close() {
33 for (Map<String, Session> sessions : threadSessions.values()) {
34 for (Session session : sessions.values()) {
35 JcrUtils.logoutQuietly(session);
36 }
37 sessions.clear();
38 }
39 threadSessions.clear();
40 closed = true;
41 }
42
43 public synchronized Session getSession(String workspace) {
44 if (closed)
45 throw new IllegalStateException("JCR session adapter is closed.");
46
47 Thread currentThread = Thread.currentThread();
48 if (lastRetrievingThread == null)
49 lastRetrievingThread = currentThread;
50
51 Map<String, Session> threadSession = threadSessions.get(currentThread);
52 if (threadSession == null) {
53 threadSession = new HashMap<>();
54 threadSessions.put(currentThread, threadSession);
55 }
56
57 Session session = threadSession.get(workspace);
58 if (session == null) {
59 session = Subject.doAs(subject, (PrivilegedAction<Session>) () -> {
60 try {
61 Session sess = repository.login(workspace);
62 return sess;
63 } catch (RepositoryException e) {
64 throw new IllegalStateException("Cannot log in to " + workspace, e);
65 }
66 });
67 threadSession.put(workspace, session);
68 }
69
70 if (lastRetrievingThread != currentThread) {
71 try {
72 session.refresh(true);
73 } catch (RepositoryException e) {
74 throw new JcrException("Cannot refresh JCR session " + session, e);
75 }
76 }
77 lastRetrievingThread = currentThread;
78 return session;
79 }
80
81 }