]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.util/src/org/argeo/util/CurrentSubject.java
Improve ACR, introduce migration from JCR.
[lgpl/argeo-commons.git] / org.argeo.util / src / org / argeo / util / CurrentSubject.java
1 package org.argeo.util;
2
3 import java.security.AccessController;
4 import java.security.PrivilegedActionException;
5 import java.security.PrivilegedExceptionAction;
6 import java.util.concurrent.Callable;
7 import java.util.concurrent.CompletionException;
8
9 import javax.security.auth.Subject;
10
11 /**
12 * Prepare evolution of Java APIs introduced in JDK 18, as these static methods
13 * will be added to {@link Subject}.
14 */
15 @SuppressWarnings("removal")
16 public class CurrentSubject {
17
18 private final static boolean useThreadLocal = Boolean
19 .parseBoolean(System.getProperty("jdk.security.auth.subject.useTL"));
20
21 private final static InheritableThreadLocal<Subject> current = new InheritableThreadLocal<>();
22
23 public static Subject current() {
24 if (useThreadLocal) {
25 return current.get();
26 } else {// legacy
27 Subject subject = Subject.getSubject(AccessController.getContext());
28 return subject;
29 }
30 }
31
32 public static <T> T callAs(Subject subject, Callable<T> action) {
33 if (useThreadLocal) {
34 Subject previous = current();
35 current.set(subject);
36 try {
37 return action.call();
38 } catch (Exception e) {
39 throw new CompletionException("Failed to execute action for " + subject, e);
40 } finally {
41 current.set(previous);
42 }
43 } else {// legacy
44 try {
45 return Subject.doAs(subject, new PrivilegedExceptionAction<T>() {
46
47 @Override
48 public T run() throws Exception {
49 return action.call();
50 }
51
52 });
53 } catch (PrivilegedActionException e) {
54 throw new CompletionException("Failed to execute action for " + subject, e.getCause());
55 } catch (Exception e) {
56 throw new CompletionException("Failed to execute action for " + subject, e);
57 }
58 }
59 }
60
61 /** Singleton. */
62 private CurrentSubject() {
63 }
64
65 }