2009-06-29 13:56:41 -04:00
|
|
|
|
2014-04-19 02:30:29 -04:00
|
|
|
package net.filebot.format;
|
2009-06-29 13:56:41 -04:00
|
|
|
|
|
|
|
|
|
|
|
import java.lang.reflect.InvocationHandler;
|
|
|
|
import java.lang.reflect.InvocationTargetException;
|
|
|
|
import java.lang.reflect.Method;
|
|
|
|
import java.lang.reflect.Proxy;
|
|
|
|
import java.security.AccessControlContext;
|
|
|
|
import java.security.AccessController;
|
|
|
|
import java.security.PrivilegedActionException;
|
|
|
|
import java.security.PrivilegedExceptionAction;
|
|
|
|
|
|
|
|
|
2009-07-05 15:39:51 -04:00
|
|
|
public final class PrivilegedInvocation implements InvocationHandler {
|
2015-07-25 18:47:19 -04:00
|
|
|
|
2009-06-29 13:56:41 -04:00
|
|
|
private final Object object;
|
|
|
|
private final AccessControlContext context;
|
2015-07-25 18:47:19 -04:00
|
|
|
|
2009-06-29 13:56:41 -04:00
|
|
|
|
|
|
|
private PrivilegedInvocation(Object object, AccessControlContext context) {
|
|
|
|
this.object = object;
|
|
|
|
this.context = context;
|
|
|
|
}
|
2015-07-25 18:47:19 -04:00
|
|
|
|
2009-06-29 13:56:41 -04:00
|
|
|
|
|
|
|
@Override
|
|
|
|
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
|
|
|
|
try {
|
|
|
|
return AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
|
2015-07-25 18:47:19 -04:00
|
|
|
|
2009-06-29 13:56:41 -04:00
|
|
|
@Override
|
|
|
|
public Object run() throws Exception {
|
|
|
|
return method.invoke(object, args);
|
|
|
|
}
|
|
|
|
}, context);
|
|
|
|
} catch (PrivilegedActionException e) {
|
|
|
|
Throwable cause = e.getException();
|
2015-07-25 18:47:19 -04:00
|
|
|
|
2009-06-29 13:56:41 -04:00
|
|
|
// the underlying method may have throw an exception
|
|
|
|
if (cause instanceof InvocationTargetException) {
|
|
|
|
// get actual cause
|
|
|
|
cause = cause.getCause();
|
|
|
|
}
|
2015-07-25 18:47:19 -04:00
|
|
|
|
2009-06-29 13:56:41 -04:00
|
|
|
// forward cause
|
|
|
|
throw cause;
|
|
|
|
}
|
|
|
|
}
|
2015-07-25 18:47:19 -04:00
|
|
|
|
2009-06-29 13:56:41 -04:00
|
|
|
|
2009-07-05 15:39:51 -04:00
|
|
|
public static <I> I newProxy(Class<I> interfaceClass, I object, AccessControlContext context) {
|
2009-06-29 13:56:41 -04:00
|
|
|
InvocationHandler invocationHandler = new PrivilegedInvocation(object, context);
|
|
|
|
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
|
2015-07-25 18:47:19 -04:00
|
|
|
|
2009-06-29 13:56:41 -04:00
|
|
|
// create dynamic invocation proxy
|
2009-07-05 15:39:51 -04:00
|
|
|
return interfaceClass.cast(Proxy.newProxyInstance(classLoader, new Class[] { interfaceClass }, invocationHandler));
|
2009-06-29 13:56:41 -04:00
|
|
|
}
|
|
|
|
}
|