下面列出了怎么用java.security.PrivilegedAction的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Constructor for AppContext. This method is <i>not</i> public,
* nor should it ever be used as such. The proper way to construct
* an AppContext is through the use of SunToolkit.createNewAppContext.
* A ThreadGroup is created for the new AppContext, a Thread is
* created within that ThreadGroup, and that Thread calls
* SunToolkit.createNewAppContext before calling anything else.
* That creates both the new AppContext and its EventQueue.
*
* @param threadGroup The ThreadGroup for the new AppContext
* @see sun.awt.SunToolkit
* @since 1.2
*/
AppContext(ThreadGroup threadGroup) {
numAppContexts.incrementAndGet();
this.threadGroup = threadGroup;
threadGroup2appContext.put(threadGroup, this);
this.contextClassLoader =
AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
public ClassLoader run() {
return Thread.currentThread().getContextClassLoader();
}
});
// Initialize push/pop lock and its condition to be used by all the
// EventQueues within this AppContext
Lock eventQueuePushPopLock = new ReentrantLock();
put(EVENT_QUEUE_LOCK_KEY, eventQueuePushPopLock);
Condition eventQueuePushPopCond = eventQueuePushPopLock.newCondition();
put(EVENT_QUEUE_COND_KEY, eventQueuePushPopCond);
}
private static void forkSecondaryFinalizer(final Runnable proc) {
AccessController.doPrivileged(
new PrivilegedAction<Void>() {
public Void run() {
ThreadGroup tg = Thread.currentThread().getThreadGroup();
for (ThreadGroup tgn = tg;
tgn != null;
tg = tgn, tgn = tg.getParent());
Thread sft = new Thread(tg, proc, "Secondary finalizer");
if (TenantGlobals.isDataIsolationEnabled() && TenantContainer.current() != null) {
SharedSecrets.getTenantAccess()
.registerServiceThread(TenantContainer.current(), sft);
}
sft.start();
try {
sft.join();
} catch (InterruptedException x) {
Thread.currentThread().interrupt();
}
return null;
}});
}
/** Looks up a named character set. A character set is a 256-entry
* array of characters, mapping unsigned byte values to their Unicode
* equivalents. The character set is loaded if necessary.
*
* @returns the character set
*/
public static Object
getCharacterSet(final String name)
throws IOException
{
char[] set = characterSets.get(name);
if (set == null) {
InputStream charsetStream = AccessController.doPrivileged(
new PrivilegedAction<InputStream>() {
public InputStream run() {
return RTFReader.class.getResourceAsStream("charsets/" + name + ".txt");
}
});
set = readCharset(charsetStream);
defineCharacterSet(name, set);
}
return set;
}
public static void main(String[]args) throws Exception {
final DomainCombiner dc = new DomainCombiner() {
@Override
public ProtectionDomain[] combine(ProtectionDomain[] currentDomains, ProtectionDomain[] assignedDomains) {
return currentDomains; // basically a no-op
}
};
// Get an instance of the saved ACC
AccessControlContext saved = AccessController.getContext();
// Simulate the stack ACC with a DomainCombiner attached
AccessControlContext stack = new AccessControlContext(AccessController.getContext(), dc);
// Now try to run JavaSecurityAccess.doIntersectionPrivilege() and assert
// whether the DomainCombiner from the stack ACC is preserved
boolean ret = SharedSecrets.getJavaSecurityAccess().doIntersectionPrivilege(new PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
return dc == AccessController.getContext().getDomainCombiner();
}
}, stack, saved);
if (!ret) {
System.exit(1);
}
}
static void stopEventDispatchThreads() {
for (AppContext appContext: getAppContexts()) {
if (appContext.isDisposed()) {
continue;
}
Runnable r = new PostShutdownEventRunnable(appContext);
// For security reasons EventQueue.postEvent should only be called
// on a thread that belongs to the corresponding thread group.
if (appContext != AppContext.getAppContext()) {
// Create a thread that belongs to the thread group associated
// with the AppContext and invokes EventQueue.postEvent.
PrivilegedAction<Thread> action = new CreateThreadAction(appContext, r);
Thread thread = AccessController.doPrivileged(action);
thread.start();
} else {
r.run();
}
}
}
@Override
public Object findAttribute(final String name) {
if (SecurityUtil.isPackageProtectionEnabled()) {
return AccessController.doPrivileged(
new PrivilegedAction<Object>() {
@Override
public Object run() {
if (name == null) {
throw new NullPointerException(Localizer
.getMessage("jsp.error.attribute.null_name"));
}
return doFindAttribute(name);
}
});
} else {
if (name == null) {
throw new NullPointerException(Localizer
.getMessage("jsp.error.attribute.null_name"));
}
return doFindAttribute(name);
}
}
@Override
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
AccessControlContext acc = null;
if (System.getSecurityManager() != null &&
(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {
acc = this.applicationContext.getBeanFactory().getAccessControlContext();
}
if (acc != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
invokeAwareInterfaces(bean);
return null;
}
}, acc);
}
else {
invokeAwareInterfaces(bean);
}
return bean;
}
private String combineSafe(Set<String> values) {
if (context == null) {
// VM events requires no access control context
return combine(values);
}
return AccessController.doPrivileged(new PrivilegedAction<String>() {
@Override
public String run() {
try {
combine(Collections.unmodifiableSet(values));
} catch (Throwable t) {
// Prevent malicious user to propagate exception callback in the wrong context
Logger.log(LogTag.JFR_SETTING, LogLevel.WARN, "Exception occured when combining " + values + " for " + getClass());
}
return null;
}
}, context);
}
private void checkPackageAccess(Class<?> cls, ProtectionDomain pd) {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
if (ReflectUtil.isNonPublicProxyClass(cls)) {
for (Class<?> intf: cls.getInterfaces()) {
checkPackageAccess(intf, pd);
}
return;
}
final String name = cls.getName();
final int i = name.lastIndexOf('.');
if (i != -1) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
sm.checkPackageAccess(name.substring(0, i));
return null;
}
}, new AccessControlContext(new ProtectionDomain[] {pd}));
}
}
domains.add(pd);
}
/**
* Open a file for writing. If {@code append} is {@code true} then the file
* is opened for atomic append directly and a FileOutputStream constructed
* with the resulting handle. This is because a FileOutputStream created
* to append to a file does not open the file in a manner that guarantees
* that writes by the child process will be atomic.
*/
private static FileOutputStream newFileOutputStream(File f, boolean append)
throws IOException
{
if (append) {
String path = f.getPath();
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkWrite(path);
long handle = openForAtomicAppend(path);
final FileDescriptor fd = new FileDescriptor();
fdAccess.setHandle(fd, handle);
return AccessController.doPrivileged(
new PrivilegedAction<FileOutputStream>() {
public FileOutputStream run() {
return new FileOutputStream(fd);
}
}
);
} else {
return new FileOutputStream(f);
}
}
/**
* Getter methods for java.util.spi.* providers
*/
@Override
public CurrencyNameProvider getCurrencyNameProvider() {
if (currencyNameProvider == null) {
CurrencyNameProvider provider = AccessController.doPrivileged(
(PrivilegedAction<CurrencyNameProvider>) () ->
new CurrencyNameProviderImpl(
getAdapterType(),
getLanguageTagSet("CurrencyNames")));
synchronized (this) {
if (currencyNameProvider == null) {
currencyNameProvider = provider;
}
}
}
return currencyNameProvider;
}
/**
* Returns the value contained by this EntryFuture, blocking if
* necessary until a value is set.
*/
synchronized Object get() {
boolean interrupted = false;
while (entry == unset) {
try {
wait();
} catch (InterruptedException ex) {
interrupted = true;
}
}
if (interrupted) {
AccessController.doPrivileged(
new PrivilegedAction<Void>() {
public Void run() {
Thread.currentThread().interrupt();
return null;
}
}
);
}
return entry;
}
private static void checkMBeanTrustPermission(final Class<?> theClass)
throws SecurityException {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
Permission perm = new MBeanTrustPermission("register");
PrivilegedAction<ProtectionDomain> act =
new PrivilegedAction<ProtectionDomain>() {
public ProtectionDomain run() {
return theClass.getProtectionDomain();
}
};
ProtectionDomain pd = AccessController.doPrivileged(act);
AccessControlContext acc =
new AccessControlContext(new ProtectionDomain[] { pd });
sm.checkPermission(perm, acc);
}
}
public static void main(String args[]) {
//parent thread without any permission
AccessController.doPrivileged(
(PrivilegedAction) () -> {
Thread ct = new Thread(
new ChildThread(PROPERTYPERM, FILEPERM));
ct.start();
try {
ct.join();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
ie.printStackTrace();
throw new RuntimeException("Unexpected InterruptedException");
}
return null;
}, ACC);
}
@Override
public TimeZoneNameProvider getTimeZoneNameProvider() {
if (timeZoneNameProvider == null) {
TimeZoneNameProvider provider = AccessController.doPrivileged(
(PrivilegedAction<TimeZoneNameProvider>) () ->
new CLDRTimeZoneNameProviderImpl(
getAdapterType(),
getLanguageTagSet("TimeZoneNames")));
synchronized (this) {
if (timeZoneNameProvider == null) {
timeZoneNameProvider = provider;
}
}
}
return timeZoneNameProvider;
}
private MRClientProtocol getMRClientProtocol(Token token,
final InetSocketAddress hsAddress, String user, final Configuration conf) {
UserGroupInformation ugi = UserGroupInformation.createRemoteUser(user);
ugi.addToken(ConverterUtils.convertFromYarn(token, hsAddress));
final YarnRPC rpc = YarnRPC.create(conf);
MRClientProtocol hsWithDT = ugi
.doAs(new PrivilegedAction<MRClientProtocol>() {
@Override
public MRClientProtocol run() {
return (MRClientProtocol) rpc.getProxy(HSClientProtocol.class,
hsAddress, conf);
}
});
return hsWithDT;
}
/**
* Creates a new <code>MarshalledObjectInputStream</code> that
* reads its objects from <code>objIn</code> and annotations
* from <code>locIn</code>. If <code>locIn</code> is
* <code>null</code>, then all annotations will be
* <code>null</code>.
*/
MarshalledObjectInputStream(InputStream objIn, InputStream locIn,
ObjectInputFilter filter)
throws IOException
{
super(objIn);
this.locIn = (locIn == null ? null : new ObjectInputStream(locIn));
if (filter != null) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
ObjectInputFilter.Config.setObjectInputFilter(MarshalledObjectInputStream.this, filter);
if (MarshalledObjectInputStream.this.locIn != null) {
ObjectInputFilter.Config.setObjectInputFilter(MarshalledObjectInputStream.this.locIn, filter);
}
return null;
}
});
}
}
@Override
public void run() {
// Don't need to synchronize, as it only runs in one thread.
for (Map.Entry<HandshakeCompletedListener,AccessControlContext>
entry : targets) {
final HandshakeCompletedListener l = entry.getKey();
AccessControlContext acc = entry.getValue();
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
l.handshakeCompleted(event);
return null;
}
}, acc);
}
}
private static void checkMBeanTrustPermission(final Class<?> theClass)
throws SecurityException {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
Permission perm = new MBeanTrustPermission("register");
PrivilegedAction<ProtectionDomain> act =
new PrivilegedAction<ProtectionDomain>() {
public ProtectionDomain run() {
return theClass.getProtectionDomain();
}
};
ProtectionDomain pd = AccessController.doPrivileged(act);
AccessControlContext acc =
new AccessControlContext(new ProtectionDomain[] { pd });
sm.checkPermission(perm, acc);
}
}
final void initDispatchThread() {
pushPopLock.lock();
try {
if (dispatchThread == null && !threadGroup.isDestroyed() && !appContext.isDisposed()) {
dispatchThread = AccessController.doPrivileged(
new PrivilegedAction<EventDispatchThread>() {
public EventDispatchThread run() {
EventDispatchThread t =
new EventDispatchThread(threadGroup,
name,
EventQueue.this);
t.setContextClassLoader(classLoader);
t.setPriority(Thread.NORM_PRIORITY + 1);
t.setDaemon(false);
AWTAutoShutdown.getInstance().notifyThreadBusy(t);
return t;
}
}
);
dispatchThread.start();
}
} finally {
pushPopLock.unlock();
}
}
/**
* Validate all of the components that have been marked invalid.
* @see #addInvalidComponent
*/
public void validateInvalidComponents() {
final java.util.List<Component> ic;
synchronized(this) {
if (invalidComponents == null) {
return;
}
ic = invalidComponents;
invalidComponents = null;
}
int n = ic.size();
for(int i = 0; i < n; i++) {
final Component c = ic.get(i);
AccessControlContext stack = AccessController.getContext();
AccessControlContext acc =
AWTAccessor.getComponentAccessor().getAccessControlContext(c);
javaSecurityAccess.doIntersectionPrivilege(
new PrivilegedAction<Void>() {
public Void run() {
c.validate();
return null;
}
}, stack, acc);
}
}
DefaultResourceLeakDetectorFactory() {
String customLeakDetector;
try {
customLeakDetector = AccessController.doPrivileged(new PrivilegedAction<String>() {
@Override
public String run() {
return SystemPropertyUtil.get("io.netty.customResourceLeakDetector");
}
});
} catch (Throwable cause) {
logger.error("Could not access System property: io.netty.customResourceLeakDetector", cause);
customLeakDetector = null;
}
if (customLeakDetector == null) {
obsoleteCustomClassConstructor = customClassConstructor = null;
} else {
obsoleteCustomClassConstructor = obsoleteCustomClassConstructor(customLeakDetector);
customClassConstructor = customClassConstructor(customLeakDetector);
}
}
public void runTest(AccessControlContext acc, Permission perm,
boolean expectACE, int id) {
AccessController.doPrivileged(
(PrivilegedAction) () -> {
try {
AccessController.getContext().checkPermission(P1);
} catch (AccessControlException ace) {
catchACE = true;
}
if (catchACE ^ expectACE) {
throw new RuntimeException("test" + id + " failed");
}
return null;
}, acc, perm);
}
void nativeQueueSurfaceDataRunnable(AppContext appContext,
final Component c, final Runnable r)
{
synchronized(this) {
if (runnableList == null) {
runnableList = new LinkedList<Runnable>();
}
runnableList.add(new Runnable() {
public void run() {
AccessControlContext stack = AccessController.getContext();
AccessControlContext acc =
AWTAccessor.getComponentAccessor().getAccessControlContext(c);
javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<Void>() {
public Void run() {
r.run();
return null;
}
}, stack, acc);
}
});
}
scheduleProcessingRunnable(appContext);
}
static ServletRequestContext requireCurrentServletRequestContext() {
if (System.getSecurityManager() == null) {
return ServletRequestContext.requireCurrent();
} else {
return AccessController.doPrivileged(new PrivilegedAction<ServletRequestContext>() {
@Override
public ServletRequestContext run() {
return ServletRequestContext.requireCurrent();
}
});
}
}
/**
* Retrieves a system property within a privileged block. Use it only when
* the property is used from within Rhino code and is not passed out of it.
* @param name the name of the system property
* @return the value of the system property
*/
public static String getSystemProperty(final String name)
{
return AccessController.doPrivileged(
new PrivilegedAction<String>()
{
public String run()
{
return System.getProperty(name);
}
});
}
@Override
protected String[] getDefaultPlatformFont() {
String[] info = new String[2];
info[0] = "Arial";
info[1] = "c:\\windows\\fonts";
final String[] dirs = getPlatformFontDirs(true);
if (dirs.length > 1) {
String dir = (String)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
for (int i=0; i<dirs.length; i++) {
String path =
dirs[i] + File.separator + "arial.ttf";
File file = new File(path);
if (file.exists()) {
return dirs[i];
}
}
return null;
}
});
if (dir != null) {
info[1] = dir;
}
} else {
info[1] = dirs[0];
}
info[1] = info[1] + File.separator + "arial.ttf";
return info;
}
private static ClassLoader wrap(final ClassLoader parent) {
return parent != null ? AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
@Override
public ClassLoader run() {
return new ClassLoader(parent) {
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
ReflectUtil.checkPackageAccess(name);
return super.loadClass(name, resolve);
}
};
}
}) : null;
}
public String generateCookieString(final Cookie cookie) {
// Web application code can receive a IllegalArgumentException
// from the generateHeader() invocation
if (SecurityUtil.isPackageProtectionEnabled()) {
return AccessController.doPrivileged(new PrivilegedAction<String>() {
@Override
public String run(){
return getContext().getCookieProcessor().generateHeader(cookie);
}
});
} else {
return getContext().getCookieProcessor().generateHeader(cookie);
}
}
static long getLastModified(final File f) {
return ((Long) AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
return new Long(f.lastModified());
}
})).longValue();
}