]> git.argeo.org Git - lgpl/argeo-commons.git/blob - util/CurrentSubject.java
Prepare next development cycle
[lgpl/argeo-commons.git] / 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 evotion 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 /** Singleton. */
19 private CurrentSubject() {
20
21 }
22
23 public static Subject current() {
24 Subject subject = Subject.getSubject(AccessController.getContext());
25 if (subject == null)
26 throw new IllegalStateException("Cannot find related subject");
27 return subject;
28 }
29
30 public static <T> T callAs(Subject subject, Callable<T> action) {
31 try {
32 return Subject.doAs(subject, new PrivilegedExceptionAction<T>() {
33
34 @Override
35 public T run() throws Exception {
36 return action.call();
37 }
38
39 });
40 } catch (PrivilegedActionException e) {
41 throw new CompletionException("Failed to execute action for " + subject, e.getCause());
42 }
43 }
44 }