java.security.PrivilegedActionException#getCause ( )源码实例Demo

下面列出了java.security.PrivilegedActionException#getCause ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

protected Class<?> loadClassMaybePrivileged(final String className,
        final ClassLoader classLoader) throws ClassNotFoundException {
    Class<?> clazz;
    if (SecurityUtil.isPackageProtectionEnabled()) {
        try {
            clazz = AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() {

                @Override
                public Class<?> run() throws Exception {
                    return loadClass(className, classLoader);
                }
            });
        } catch (PrivilegedActionException e) {
            Throwable t = e.getCause();
            if (t instanceof ClassNotFoundException) {
                throw (ClassNotFoundException) t;
            }
            throw new RuntimeException(t);
        }
    } else {
        clazz = loadClass(className, classLoader);
    }
    checkAccess(clazz);
    return clazz;
}
 
private static HttpClient createHttpClient(Settings settings, Path configPath) throws Exception {
    try {
        final SecurityManager sm = System.getSecurityManager();

        if (sm != null) {
            sm.checkPermission(new SpecialPermission());
        }

        return AccessController.doPrivileged(new PrivilegedExceptionAction<HttpClient>() {
            @Override
            public HttpClient run() throws Exception {
                return createHttpClient0(settings, configPath);
            }
        });
    } catch (PrivilegedActionException e) {
        if (e.getCause() instanceof Exception) {
            throw (Exception) e.getCause();
        } else {
            throw new RuntimeException(e);
        }
    }
}
 
源代码3 项目: openjdk-jdk8u   文件: SecuritySupport.java
private static <U> U doPrivilegedIOWithReturn(Callable<U> function) throws IOException {
    try {
        return AccessController.doPrivileged(new PrivilegedExceptionAction<U>() {
            @Override
            public U run() throws Exception {
                return function.call();
            }
        }, null);
    } catch (PrivilegedActionException e) {
        Throwable t = e.getCause();
        if (t instanceof IOException) {
            throw (IOException) t;
        }
        throw new IOException("Unexpected error during I/O operation. " + t.getMessage(), t);
    }
}
 
/**
 * Creates class instance by calling the default constructor.
 */
public static <T> T instantiate(final Class<T> clazz) {
    try {
        return AccessController.doPrivileged(new PrivilegedExceptionAction<T>() {
            @Override
            public T run() throws Exception {
                Constructor<T> constructor = clazz.getDeclaredConstructor();
                constructor.setAccessible(true);
                return constructor.newInstance();
            }
        });
    } catch (PrivilegedActionException e) {
        if (e.getCause() instanceof NoSuchMethodException) {
            throw new RuntimeException(clazz + " must have a default constructor");
        }
        throw new RuntimeException(e);
    }
}
 
源代码5 项目: quarkus-http   文件: RequestDispatcherImpl.java
@Override
public void include(final ServletRequest request, final ServletResponse response) throws ServletException, IOException {
    if(System.getSecurityManager() != null) {
        try {
            AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                @Override
                public Object run() throws Exception {
                    setupIncludeImpl(request, response);
                    return null;
                }
            });
        } catch (PrivilegedActionException e) {
            if(e.getCause() instanceof ServletException) {
                throw (ServletException)e.getCause();
            } else if(e.getCause() instanceof IOException) {
                throw (IOException)e.getCause();
            } else if(e.getCause() instanceof RuntimeException) {
                throw (RuntimeException)e.getCause();
            } else {
                throw new RuntimeException(e.getCause());
            }
        }
    } else {
        setupIncludeImpl(request, response);
    }
}
 
源代码6 项目: TencentKona-8   文件: ShutdownHook.java
private WriteableUserPath makeDumpOnExitPath(PlatformRecording recording) {
    try {
        String name = Utils.makeFilename(recording.getRecording());
        AccessControlContext acc = recording.getNoDestinationDumpOnExitAccessControlContext();
        return AccessController.doPrivileged(new PrivilegedExceptionAction<WriteableUserPath>() {
            @Override
            public WriteableUserPath run() throws Exception {
                return new WriteableUserPath(recording.getDumpOnExitDirectory().toPath().resolve(name));
            }
        }, acc);
    } catch (PrivilegedActionException e) {
        Throwable t = e.getCause();
        if (t instanceof SecurityException) {
            Logger.log(LogTag.JFR, LogLevel.WARN, "Not allowed to create dump path for recording " + recording.getId() + " on exit.");
        }
        if (t instanceof IOException) {
            Logger.log(LogTag.JFR, LogLevel.WARN, "Could not dump " + recording.getId() + " on exit.");
        }
        return null;
    }
}
 
源代码7 项目: ignite   文件: ConcurrentLinkedDeque8.java
/**
 * @return Instance of Unsafe class.
 */
static Unsafe unsafe() {
    try {
        return Unsafe.getUnsafe();
    }
    catch (SecurityException ignored) {
        try {
            return AccessController.doPrivileged
                (new PrivilegedExceptionAction<Unsafe>() {
                    @Override public Unsafe run() throws Exception {
                        Field f = Unsafe.class.getDeclaredField("theUnsafe");

                        f.setAccessible(true);

                        return (Unsafe) f.get(null);
                    }
                });
        }
        catch (PrivilegedActionException e) {
            throw new RuntimeException("Could not initialize intrinsics.", e.getCause());
        }
    }
}
 
源代码8 项目: dragonwell8_jdk   文件: RMIIIOPServerImpl.java
@Override
RMIConnection doNewClient(final Object credentials) throws IOException {
    if (callerACC == null) {
        throw new SecurityException("AccessControlContext cannot be null");
    }
    try {
        return AccessController.doPrivileged(
            new PrivilegedExceptionAction<RMIConnection>() {
                public RMIConnection run() throws IOException {
                    return superDoNewClient(credentials);
                }
        }, callerACC);
    } catch (PrivilegedActionException pae) {
        throw (IOException) pae.getCause();
    }
}
 
源代码9 项目: hottub   文件: RMIIIOPServerImpl.java
@Override
RMIConnection doNewClient(final Object credentials) throws IOException {
    if (callerACC == null) {
        throw new SecurityException("AccessControlContext cannot be null");
    }
    try {
        return AccessController.doPrivileged(
            new PrivilegedExceptionAction<RMIConnection>() {
                public RMIConnection run() throws IOException {
                    return superDoNewClient(credentials);
                }
        }, callerACC);
    } catch (PrivilegedActionException pae) {
        throw (IOException) pae.getCause();
    }
}
 
源代码10 项目: HotswapAgent   文件: SecurityActions.java
static TheUnsafe getSunMiscUnsafeAnonymously() throws ClassNotFoundException
{
    try {
        return AccessController.doPrivileged(
            new PrivilegedExceptionAction<TheUnsafe>() { public TheUnsafe run() throws
                    ClassNotFoundException, NoSuchFieldException, SecurityException,
                    IllegalArgumentException, IllegalAccessException {
                Class<?> unsafe = Class.forName("sun.misc.Unsafe");
                Field theUnsafe = unsafe.getDeclaredField("theUnsafe");
                theUnsafe.setAccessible(true);
                TheUnsafe usf = stack.new TheUnsafe(unsafe, theUnsafe.get(null));
                theUnsafe.setAccessible(false);
                disableWarning(usf);
                return usf;
            }
        });
    }
    catch (PrivilegedActionException e) {
        if (e.getCause() instanceof ClassNotFoundException)
            throw (ClassNotFoundException) e.getCause();
        if (e.getCause() instanceof NoSuchFieldException)
            throw new ClassNotFoundException("No such instance.", e.getCause());
        if (e.getCause() instanceof IllegalAccessException
                || e.getCause() instanceof IllegalAccessException
                || e.getCause() instanceof SecurityException)
            throw new ClassNotFoundException("Security denied access.", e.getCause());
        throw new RuntimeException(e.getCause());
    }
}
 
源代码11 项目: keycloak   文件: SecurityActions.java
/**
 * Set a single Field value
 *
 * @param target The object to set it on
 * @param fieldName The field name
 * @param value The new value
 */
public static void setFieldValue(final Class<?> source, final Object target, final String fieldName,
        final Object value) throws NoSuchFieldException {
    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws Exception {
                Field field = source.getDeclaredField(fieldName);
                if (!field.isAccessible()) {
                    field.setAccessible(true);
                }
                field.set(target, value);
                return null;
            }
        });
    } // Unwrap
    catch (final PrivilegedActionException pae) {
        final Throwable t = pae.getCause();
        // Rethrow
        if (t instanceof NoSuchFieldException) {
            throw (NoSuchFieldException) t;
        } else {
            // No other checked Exception thrown by Class.getConstructor
            try {
                throw (RuntimeException) t;
            } // Just in case we've really messed up
            catch (final ClassCastException cce) {
                throw new RuntimeException("Obtained unchecked Exception; this code should never be reached", t);
            }
        }
    }
}
 
源代码12 项目: jdk8u-jdk   文件: CalendarSystem.java
/**
 * Returns a {@link Properties} loaded from lib/calendars.properties.
 *
 * @return a {@link Properties} loaded from lib/calendars.properties
 * @throws IOException if an error occurred when reading from the input stream
 * @throws IllegalArgumentException if the input stream contains any malformed
 *                                  Unicode escape sequences
 */
public static Properties getCalendarProperties() throws IOException {
    Properties calendarProps = null;
    try {
        String homeDir = AccessController.doPrivileged(
            new sun.security.action.GetPropertyAction("java.home"));
        final String fname = homeDir + File.separator + "lib" + File.separator
                             + "calendars.properties";
        calendarProps = AccessController.doPrivileged(new PrivilegedExceptionAction<Properties>() {
            @Override
            public Properties run() throws IOException {
                Properties props = new Properties();
                try (FileInputStream fis = new FileInputStream(fname)) {
                    props.load(fis);
                }
                return props;
            }
        });
    } catch (PrivilegedActionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof IOException) {
            throw (IOException) cause;
        } else if (cause instanceof IllegalArgumentException) {
            throw (IllegalArgumentException) cause;
        }
        // Should not happen
        throw new InternalError(cause);
    }
    return calendarProps;
}
 
源代码13 项目: knox   文件: AbstractJWTFilter.java
protected void continueWithEstablishedSecurityContext(Subject subject, final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws IOException, ServletException {
  Principal principal = (Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0];
  AuditContext context = auditService.getContext();
  if (context != null) {
    context.setUsername( principal.getName() );
    String sourceUri = (String)request.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME );
    if (sourceUri != null) {
      auditor.audit( Action.AUTHENTICATION , sourceUri, ResourceType.URI, ActionOutcome.SUCCESS );
    }
  }

  try {
    Subject.doAs(
      subject,
      new PrivilegedExceptionAction<Object>() {
        @Override
        public Object run() throws Exception {
          chain.doFilter(request, response);
          return null;
        }
      }
      );
  }
  catch (PrivilegedActionException e) {
    Throwable t = e.getCause();
    if (t instanceof IOException) {
      throw (IOException) t;
    }
    else if (t instanceof ServletException) {
      throw (ServletException) t;
    }
    else {
      throw new ServletException(t);
    }
  }
}
 
源代码14 项目: netty-4.1.22   文件: SocketUtils.java
public static boolean connect(final SocketChannel socketChannel, final SocketAddress remoteAddress)
        throws IOException {
    try {
        return AccessController.doPrivileged(new PrivilegedExceptionAction<Boolean>() {
            @Override
            public Boolean run() throws IOException {
                return socketChannel.connect(remoteAddress);
            }
        });
    } catch (PrivilegedActionException e) {
        throw (IOException) e.getCause();
    }
}
 
源代码15 项目: crate   文件: URLBlobContainer.java
@SuppressForbidden(reason = "We call connect in doPrivileged and provide SocketPermission")
private static InputStream getInputStream(URL url) throws IOException {
    try {
        return AccessController.doPrivileged((PrivilegedExceptionAction<InputStream>) url::openStream);
    } catch (PrivilegedActionException e) {
        throw (IOException) e.getCause();
    }
}
 
源代码16 项目: jdk8u-jdk   文件: CalendarSystem.java
/**
 * Returns a {@link Properties} loaded from lib/calendars.properties.
 *
 * @return a {@link Properties} loaded from lib/calendars.properties
 * @throws IOException if an error occurred when reading from the input stream
 * @throws IllegalArgumentException if the input stream contains any malformed
 *                                  Unicode escape sequences
 */
public static Properties getCalendarProperties() throws IOException {
    Properties calendarProps = null;
    try {
        String homeDir = AccessController.doPrivileged(
            new sun.security.action.GetPropertyAction("java.home"));
        final String fname = homeDir + File.separator + "lib" + File.separator
                             + "calendars.properties";
        calendarProps = AccessController.doPrivileged(new PrivilegedExceptionAction<Properties>() {
            @Override
            public Properties run() throws IOException {
                Properties props = new Properties();
                try (FileInputStream fis = new FileInputStream(fname)) {
                    props.load(fis);
                }
                return props;
            }
        });
    } catch (PrivilegedActionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof IOException) {
            throw (IOException) cause;
        } else if (cause instanceof IllegalArgumentException) {
            throw (IllegalArgumentException) cause;
        }
        // Should not happen
        throw new InternalError(cause);
    }
    return calendarProps;
}
 
源代码17 项目: TencentKona-8   文件: ClassLoader.java
private static synchronized void initSystemClassLoader() {
    if (!sclSet) {
        if (scl != null)
            throw new IllegalStateException("recursive invocation");
        sun.misc.Launcher l = sun.misc.Launcher.getLauncher();
        if (l != null) {
            Throwable oops = null;
            scl = l.getClassLoader();
            try {
                scl = AccessController.doPrivileged(
                    new SystemClassLoaderAction(scl));
            } catch (PrivilegedActionException pae) {
                oops = pae.getCause();
                if (oops instanceof InvocationTargetException) {
                    oops = oops.getCause();
                }
            }
            if (oops != null) {
                if (oops instanceof Error) {
                    throw (Error) oops;
                } else {
                    // wrap the exception
                    throw new Error(oops);
                }
            }
        }
        sclSet = true;
    }
}
 
源代码18 项目: netty-4.1.22   文件: SocketUtils.java
public static InetAddress addressByName(final String hostname) throws UnknownHostException {
    try {
        return AccessController.doPrivileged(new PrivilegedExceptionAction<InetAddress>() {
            @Override
            public InetAddress run() throws UnknownHostException {
                return InetAddress.getByName(hostname);
            }
        });
    } catch (PrivilegedActionException e) {
        throw (UnknownHostException) e.getCause();
    }
}
 
源代码19 项目: astor   文件: SecureCaller.java
/**
 * Call the specified callable using a protection domain belonging to the
 * specified code source.
 */
static Object callSecurely(final CodeSource codeSource, Callable callable,
        Context cx, Scriptable scope, Scriptable thisObj, Object[] args)
{
    final Thread thread = Thread.currentThread();
    // Run in doPrivileged as we might be checked for "getClassLoader"
    // runtime permission
    final ClassLoader classLoader = (ClassLoader)AccessController.doPrivileged(
        new PrivilegedAction<Object>() {
            public Object run() {
                return thread.getContextClassLoader();
            }
        });
    Map<ClassLoader,SoftReference<SecureCaller>> classLoaderMap;
    synchronized(callers)
    {
        classLoaderMap = callers.get(codeSource);
        if(classLoaderMap == null)
        {
            classLoaderMap = new WeakHashMap<ClassLoader,SoftReference<SecureCaller>>();
            callers.put(codeSource, classLoaderMap);
        }
    }
    SecureCaller caller;
    synchronized(classLoaderMap)
    {
        SoftReference<SecureCaller> ref = classLoaderMap.get(classLoader);
        if (ref != null) {
            caller = ref.get();
        } else {
            caller = null;
        }
        if (caller == null) {
            try
            {
                // Run in doPrivileged as we'll be checked for
                // "createClassLoader" runtime permission
                caller = (SecureCaller)AccessController.doPrivileged(
                        new PrivilegedExceptionAction<Object>()
                {
                    public Object run() throws Exception
                    {
                        ClassLoader effectiveClassLoader;
                        Class<?> thisClass = getClass();
                        if(classLoader.loadClass(thisClass.getName()) != thisClass) {
                            effectiveClassLoader = thisClass.getClassLoader();
                        } else {
                            effectiveClassLoader = classLoader;
                        }
                        SecureClassLoaderImpl secCl =
                            new SecureClassLoaderImpl(effectiveClassLoader);
                        Class<?> c = secCl.defineAndLinkClass(
                                SecureCaller.class.getName() + "Impl",
                                secureCallerImplBytecode, codeSource);
                        return c.newInstance();
                    }
                });
                classLoaderMap.put(classLoader, new SoftReference<SecureCaller>(caller));
            }
            catch(PrivilegedActionException ex)
            {
                throw new UndeclaredThrowableException(ex.getCause());
            }
        }
    }
    return caller.call(callable, cx, scope, thisObj, args);
}
 
源代码20 项目: pulsar   文件: PulsarSaslClient.java
public PulsarSaslClient(String serverHostname, String serverType, Subject subject) throws SaslException {
    checkArgument(subject != null, "Cannot create SASL client with NULL JAAS subject");
    checkArgument(!Strings.isNullOrEmpty(serverHostname), "Cannot create SASL client with NUll server name");
    if (!serverType.equals(SaslConstants.SASL_BROKER_PROTOCOL) && !serverType
                                                                       .equals(SaslConstants.SASL_PROXY_PROTOCOL)) {
        log.warn("The server type {} is not recommended", serverType);
    }

    String serverPrincipal = serverType.toLowerCase() + "/" + serverHostname;
    this.clientSubject = subject;
    if (clientSubject.getPrincipals().isEmpty()) {
        throw new SaslException("Cannot create SASL client with empty JAAS subject principal");
    }
    // GSSAPI/Kerberos
    final Object[] principals = clientSubject.getPrincipals().toArray();
    final Principal clientPrincipal = (Principal) principals[0];

    final KerberosName clientKerberosName = new KerberosName(clientPrincipal.getName());
    KerberosName serviceKerberosName = new KerberosName(serverPrincipal + "@" + clientKerberosName.getRealm());
    final String serviceName = serviceKerberosName.getServiceName();
    final String serviceHostname = serviceKerberosName.getHostName();
    final String clientPrincipalName = clientKerberosName.toString();
    log.info("Using JAAS/SASL/GSSAPI auth to connect to server Principal {},",
        serverPrincipal);

    try {
        this.saslClient = Subject.doAs(clientSubject, new PrivilegedExceptionAction<SaslClient>() {
            @Override
            public SaslClient run() throws SaslException {
                String[] mechs = {"GSSAPI"};
                return Sasl.createSaslClient(mechs, clientPrincipalName, serviceName, serviceHostname, null,
                    new ClientCallbackHandler());
            }
        });
    } catch (PrivilegedActionException err) {
        log.error("GSSAPI client error", err.getCause());
        throw new SaslException("error while booting GSSAPI client", err.getCause());
    }

    if (saslClient == null) {
        throw new SaslException("Cannot create JVM SASL Client");
    }

}