Java Code Examples for java.security.PrivilegedActionException

The following examples show how to use java.security.PrivilegedActionException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: hottub   Source File: Context.java    License: GNU General Public License v2.0 6 votes vote down vote up
public Context impersonate(final String someone) throws Exception {
    try {
        GSSCredential creds = Subject.doAs(s, new PrivilegedExceptionAction<GSSCredential>() {
            @Override
            public GSSCredential run() throws Exception {
                GSSManager m = GSSManager.getInstance();
                GSSName other = m.createName(someone, GSSName.NT_USER_NAME);
                if (Context.this.cred == null) {
                    Context.this.cred = m.createCredential(GSSCredential.INITIATE_ONLY);
                }
                return ((ExtendedGSSCredential)Context.this.cred).impersonate(other);
            }
        });
        Context out = new Context();
        out.s = s;
        out.cred = creds;
        out.name = name + " as " + out.cred.getName().toString();
        return out;
    } catch (PrivilegedActionException pae) {
        throw pae.getException();
    }
}
 
Example 2
Source Project: jdk8u60   Source File: HttpURLConnection.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected void plainConnect()  throws IOException {
    synchronized (this) {
        if (connected) {
            return;
        }
    }
    SocketPermission p = URLtoSocketPermission(this.url);
    if (p != null) {
        try {
            AccessController.doPrivilegedWithCombiner(
                new PrivilegedExceptionAction<Void>() {
                    public Void run() throws IOException {
                        plainConnect0();
                        return null;
                    }
                }, null, p
            );
        } catch (PrivilegedActionException e) {
                throw (IOException) e.getException();
        }
    } else {
        // run without additional permission
        plainConnect0();
    }
}
 
Example 3
Source Project: gemfirexd-oss   Source File: ErrorStreamTest.java    License: Apache License 2.0 6 votes vote down vote up
private static void assertNotEmpty(final File f) throws IOException {
    try {
        AccessController.doPrivileged (new PrivilegedExceptionAction() {
            public Object run() throws IOException {
                assertTrue("assertNotEmpty failed: " + f.getCanonicalPath()
                      + " does not exist.", f.exists());
                FileInputStream fis = new FileInputStream(f);
                int result = fis.read();
                fis.close();
                assertTrue("assertNotEmpty failed: " + f.getCanonicalPath()
                      + " is empty.", -1 != result);
                return null;
            }
        });
    } catch (PrivilegedActionException e) {
        // e.getException() should be an instance of IOException.
        throw (IOException) e.getException();
    }
}
 
Example 4
@Override
public synchronized InputStream getInputStream() throws IOException {
    connecting = true;
    SocketPermission p = URLtoSocketPermission(this.url);

    if (p != null) {
        try {
            return AccessController.doPrivilegedWithCombiner(
                new PrivilegedExceptionAction<>() {
                    public InputStream run() throws IOException {
                        return getInputStream0();
                    }
                }, null, p
            );
        } catch (PrivilegedActionException e) {
            throw (IOException) e.getException();
        }
    } else {
        return getInputStream0();
    }
}
 
Example 5
Source Project: gemfirexd-oss   Source File: StreamFileContainer.java    License: Apache License 2.0 6 votes vote down vote up
private synchronized OutputStream privGetOutputStream(StorageFile file)
    throws FileNotFoundException
{
    actionCode = STORAGE_FILE_GET_OUTPUT_STREAM_ACTION;
    actionStorageFile = file;

    try
    {
        return (OutputStream) AccessController.doPrivileged( this);
    }catch( PrivilegedActionException pae) 
    { 
        throw (FileNotFoundException)pae.getException();
    } 
    finally
    {
        actionStorageFile = null;
    }
}
 
Example 6
public boolean isRegistered(ObjectName name,
                            Subject delegationSubject) throws IOException {
    try {
        final Object params[] = new Object[] { name };
        return ((Boolean)
            doPrivilegedOperation(
              IS_REGISTERED,
              params,
              delegationSubject)).booleanValue();
    } catch (PrivilegedActionException pe) {
        Exception e = extractException(pe);
        if (e instanceof IOException)
            throw (IOException) e;
        throw newIOException("Got unexpected server exception: " + e, e);
    }
}
 
Example 7
Source Project: gemfirexd-oss   Source File: RawStore.java    License: Apache License 2.0 6 votes vote down vote up
private synchronized boolean privExists( File file)
{
    actionCode = REGULAR_FILE_EXISTS_ACTION;
    actionRegularFile = file;

    try
    {
        Object ret = AccessController.doPrivileged( this);
        return ((Boolean) ret).booleanValue();
    }
    catch( PrivilegedActionException pae) { return false;} // does not throw an exception
    finally
    {
        actionRegularFile = null;
    }
}
 
Example 8
Source Project: openjdk-jdk9   Source File: Executors.java    License: GNU General Public License v2.0 6 votes vote down vote up
public T call() throws Exception {
    try {
        return AccessController.doPrivileged(
            new PrivilegedExceptionAction<T>() {
                public T run() throws Exception {
                    Thread t = Thread.currentThread();
                    ClassLoader cl = t.getContextClassLoader();
                    if (ccl == cl) {
                        return task.call();
                    } else {
                        t.setContextClassLoader(ccl);
                        try {
                            return task.call();
                        } finally {
                            t.setContextClassLoader(cl);
                        }
                    }
                }
            }, acc);
    } catch (PrivilegedActionException e) {
        throw e.getException();
    }
}
 
Example 9
Source Project: gemfirexd-oss   Source File: StreamFileContainer.java    License: Apache License 2.0 6 votes vote down vote up
private synchronized boolean privMkdirs(StorageFile file)
{
    actionCode = STORAGE_FILE_MKDIRS_ACTION;
    actionStorageFile = file;

    try
    {
        Object ret = AccessController.doPrivileged( this);
        return ((Boolean) ret).booleanValue();
    }catch( PrivilegedActionException pae) 
    {
        // method executed under this priveleged block 
        // does not throw an exception
        return false;
    } 
    finally
    {
        actionStorageFile = null;
    }
}
 
Example 10
Source Project: birt   Source File: FileSecurity.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 
 * @param path
 * @param type
 * @return
 * @throws FileNotFoundException
 * @throws DataException
 */
public static RandomAccessFile createRandomAccessFile( final String path,
		final String type ) throws FileNotFoundException, DataException
{
	try
	{
		return AccessController.doPrivileged( new PrivilegedExceptionAction<RandomAccessFile>( ) {

			public RandomAccessFile run( ) throws FileNotFoundException
			{
				return new RandomAccessFile( path, type );
			}
		} );
	}
	catch ( PrivilegedActionException e )
	{
		Exception typedException = e.getException( );
		if ( typedException instanceof FileNotFoundException )
		{
			throw (FileNotFoundException) typedException;
		}
		throw new DataException( e.getLocalizedMessage( ) );
	}
}
 
Example 11
Source Project: smart-testing   Source File: SecurityUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Obtains the Constructor specified from the given Class and argument types
 */
private static <T> Constructor<T> getConstructor(final Class<T> clazz, final Class<?>... argumentTypes)
    throws NoSuchMethodException {
    try {
        return AccessController.doPrivileged(
            (PrivilegedExceptionAction<Constructor<T>>) () -> clazz.getDeclaredConstructor(argumentTypes));
    }
    // Unwrap
    catch (final PrivilegedActionException pae) {
        final Throwable t = pae.getCause();
        // Rethrow
        if (t instanceof NoSuchMethodException) {
            throw (NoSuchMethodException) 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);
            }
        }
    }
}
 
Example 12
Source Project: gemfirexd-oss   Source File: JarUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Copy the jar from the externally obtained 
 * input stream into the database
 * @param jarExternalName Name of jar with database structure.
 * @param contents Contents of jar file.
 * @param add true to add, false to replace
 * @param currentGenerationId generation id of existing version, ignored when adding.
 */
 private long setJar(final String jarExternalName,
      final InputStream contents,
        final boolean add,
        final long currentGenerationId)
        throws StandardException {
    try {
        return ((Long) AccessController
                .doPrivileged(new java.security.PrivilegedExceptionAction() {

                    public Object run() throws StandardException {
                        long generationId;
                        
                        if (add)
                            generationId = fr.add(jarExternalName, contents, lcc);
                        else
                            generationId =  fr.replace(jarExternalName,
                                    currentGenerationId, contents, lcc);
                        return Long.valueOf(generationId);
                    }
                })).longValue();
    } catch (PrivilegedActionException e) {
        throw (StandardException) e.getException();
    }
}
 
Example 13
Source Project: AndroidPNClient   Source File: LoginContext.java    License: Apache License 2.0 6 votes vote down vote up
public void handle(final Callback[] callbacks) throws IOException,
        UnsupportedCallbackException {
    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
            public Void run() throws IOException, UnsupportedCallbackException {
                hiddenHandlerRef.handle(callbacks);
                return null;
            }
        }, userContext);
    } catch (PrivilegedActionException ex) {
        if (ex.getCause() instanceof UnsupportedCallbackException) {
            throw (UnsupportedCallbackException) ex.getCause();
        }
        throw (IOException) ex.getCause();
    }
}
 
Example 14
Source Project: JDKSourceCode1.8   Source File: RMIIIOPServerImpl.java    License: MIT License 6 votes vote down vote up
@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();
    }
}
 
Example 15
@Override
public synchronized OutputStream getOutputStream() throws IOException {
    connecting = true;
    SocketPermission p = URLtoSocketPermission(this.url);

    if (p != null) {
        try {
            return AccessController.doPrivilegedWithCombiner(
                new PrivilegedExceptionAction<OutputStream>() {
                    public OutputStream run() throws IOException {
                        return getOutputStream0();
                    }
                }, null, p
            );
        } catch (PrivilegedActionException e) {
            throw (IOException) e.getException();
        }
    } else {
        return getOutputStream0();
    }
}
 
Example 16
public static Map<String, Object> byteArrayToMutableJsonMap(byte[] jsonBytes) throws IOException {

        final SecurityManager sm = System.getSecurityManager();

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

        try {
            return AccessController.doPrivileged(new PrivilegedExceptionAction<Map<String, Object>>() {
                @Override
                public Map<String, Object> run() throws Exception {
                    return internalMapper.readValue(jsonBytes, new TypeReference<Map<String, Object>>() {});
                }
            });
        } catch (final PrivilegedActionException e) {
            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());
            }
        }
    }
 
Example 17
Source Project: knox   Source File: SpnegoAuthInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
private static <T> T doAs(Subject subject, GssSupplier<T> action) throws GSSException {
  try {
    return Subject.doAs(subject, (PrivilegedExceptionAction<T>) action::get);
  } catch (PrivilegedActionException e) {
    Throwable t = e.getCause();
    if (t instanceof GSSException) {
      throw (GSSException)t;
    } else if (t instanceof Error) {
      throw (Error)t;
    } else if (t instanceof RuntimeException) {
      throw (RuntimeException)t;
    } else {
      throw new RuntimeException(t);
    }
  }
}
 
Example 18
Source Project: hottub   Source File: HijrahChronology.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return the configuration properties from the resource.
 * <p>
 * The default location of the variant configuration resource is:
 * <pre>
 *   "$java.home/lib/" + resource-name
 * </pre>
 *
 * @param resource the name of the calendar property resource
 * @return a Properties containing the properties read from the resource.
 * @throws Exception if access to the property resource fails
 */
private static Properties readConfigProperties(final String resource) throws Exception {
    try {
        return AccessController
                .doPrivileged((java.security.PrivilegedExceptionAction<Properties>)
                    () -> {
                    String libDir = System.getProperty("java.home") + File.separator + "lib";
                    File file = new File(libDir, resource);
                    Properties props = new Properties();
                    try (InputStream is = new FileInputStream(file)) {
                        props.load(is);
                    }
                    return props;
                });
    } catch (PrivilegedActionException pax) {
        throw pax.getException();
    }
}
 
Example 19
public boolean isRegistered(ObjectName name,
                            Subject delegationSubject) throws IOException {
    try {
        final Object params[] = new Object[] { name };
        return ((Boolean)
            doPrivilegedOperation(
              IS_REGISTERED,
              params,
              delegationSubject)).booleanValue();
    } catch (PrivilegedActionException pe) {
        Exception e = extractException(pe);
        if (e instanceof IOException)
            throw (IOException) e;
        throw newIOException("Got unexpected server exception: " + e, e);
    }
}
 
Example 20
private ClassLoader getClassLoader(final ObjectName name)
    throws InstanceNotFoundException {
    try {
        return
            AccessController.doPrivileged(
                new PrivilegedExceptionAction<ClassLoader>() {
                    public ClassLoader run() throws InstanceNotFoundException {
                        return mbeanServer.getClassLoader(name);
                    }
                },
                withPermissions(new MBeanPermission("*", "getClassLoader"))
        );
    } catch (PrivilegedActionException pe) {
        throw (InstanceNotFoundException) extractException(pe);
    }
}
 
Example 21
Source Project: openjdk-8   Source File: RMIIIOPServerImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
@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();
    }
}
 
Example 22
/**
 * Called with file lock held (in addition to node locks).
 */
protected void removeNodeSpi() throws BackingStoreException {
    try {
        AccessController.doPrivileged(
            new PrivilegedExceptionAction<Void>() {
            public Void run() throws BackingStoreException {
                if (changeLog.contains(nodeCreate)) {
                    changeLog.remove(nodeCreate);
                    nodeCreate = null;
                    return null;
                }
                if (!dir.exists())
                    return null;
                prefsFile.delete();
                tmpFile.delete();
                // dir should be empty now.  If it's not, empty it
                File[] junk = dir.listFiles();
                if (junk.length != 0) {
                    getLogger().warning(
                       "Found extraneous files when removing node: "
                        + Arrays.asList(junk));
                    for (int i=0; i<junk.length; i++)
                        junk[i].delete();
                }
                if (!dir.delete())
                    throw new BackingStoreException("Couldn't delete dir: "
                                                                     + dir);
                return null;
            }
        });
    } catch (PrivilegedActionException e) {
        throw (BackingStoreException) e.getException();
    }
}
 
Example 23
Source Project: JDKSourceCode1.8   Source File: ServerNotifForwarder.java    License: MIT License 5 votes vote down vote up
static void checkMBeanPermission(
        final MBeanServer mbs, final ObjectName name, final String actions)
        throws InstanceNotFoundException, SecurityException {

    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        AccessControlContext acc = AccessController.getContext();
        ObjectInstance oi;
        try {
            oi = AccessController.doPrivileged(
                new PrivilegedExceptionAction<ObjectInstance>() {
                    public ObjectInstance run()
                    throws InstanceNotFoundException {
                        return mbs.getObjectInstance(name);
                    }
            });
        } catch (PrivilegedActionException e) {
            throw (InstanceNotFoundException) extractException(e);
        }
        String classname = oi.getClassName();
        MBeanPermission perm = new MBeanPermission(
            classname,
            null,
            name,
            actions);
        sm.checkPermission(perm, acc);
    }
}
 
Example 24
Source Project: es6draft   Source File: Compiler.java    License: MIT License 5 votes vote down vote up
private static sun.misc.Unsafe initializeUnsafe() {
    try {
        return AccessController.doPrivileged((PrivilegedExceptionAction<sun.misc.Unsafe>) () -> {
            Field f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
            f.setAccessible(true);
            return (sun.misc.Unsafe) f.get(null);
        });
    } catch (PrivilegedActionException e) {
        throw new ExceptionInInitializerError(e.getException());
    }
}
 
Example 25
Source Project: jdk8u-jdk   Source File: ClassLoader.java    License: GNU General Public License v2.0 5 votes vote down vote up
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;
    }
}
 
Example 26
Source Project: smallrye-fault-tolerance   Source File: GenericConfig.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <U> U getConfigFromAnnotation(String key) {
    try {
        return (U) SecurityActions.getAnnotationMethod(annotationType, key).invoke(annotation);
    } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException | IllegalArgumentException
            | PrivilegedActionException e) {
        throw new FaultToleranceDefinitionException(
                "Member " + key + " on annotation " + annotation.getClass().toString()
                        + " doesn't exist or is not accessible");
    }
}
 
Example 27
Source Project: openjdk-jdk9   Source File: SecuritySupport.java    License: GNU General Public License v2.0 5 votes vote down vote up
static FileInputStream getFileInputStream(final File file)
throws FileNotFoundException
{
    try {
        return AccessController.doPrivileged(
                (PrivilegedExceptionAction<FileInputStream>)() ->
                new FileInputStream(file));
    } catch (PrivilegedActionException e) {
        throw (FileNotFoundException)e.getException();
    }
}
 
Example 28
Source Project: jdk8u-jdk   Source File: RMIConnectionImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")  // MarshalledObject
public Set<ObjectInstance>
    queryMBeans(ObjectName name,
                MarshalledObject query,
                Subject delegationSubject)
    throws IOException {
    final QueryExp queryValue;
    final boolean debug=logger.debugOn();

    if (debug) logger.debug("queryMBeans",
             "connectionId=" + connectionId
             +" unwrapping query with defaultClassLoader.");

    queryValue = unwrap(query, defaultContextClassLoader, QueryExp.class);

    try {
        final Object params[] = new Object[] { name, queryValue };

        if (debug) logger.debug("queryMBeans",
             "connectionId=" + connectionId
             +", name="+name +", query="+query);

        return cast(
            doPrivilegedOperation(
              QUERY_MBEANS,
              params,
              delegationSubject));
    } catch (PrivilegedActionException pe) {
        Exception e = extractException(pe);
        if (e instanceof IOException)
            throw (IOException) e;
        throw newIOException("Got unexpected server exception: " + e, e);
    }
}
 
Example 29
static void checkMBeanPermission(
        final MBeanServer mbs, final ObjectName name, final String actions)
        throws InstanceNotFoundException, SecurityException {

    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        AccessControlContext acc = AccessController.getContext();
        ObjectInstance oi;
        try {
            oi = AccessController.doPrivileged(
                new PrivilegedExceptionAction<ObjectInstance>() {
                    public ObjectInstance run()
                    throws InstanceNotFoundException {
                        return mbs.getObjectInstance(name);
                    }
            });
        } catch (PrivilegedActionException e) {
            throw (InstanceNotFoundException) extractException(e);
        }
        String classname = oi.getClassName();
        MBeanPermission perm = new MBeanPermission(
            classname,
            null,
            name,
            actions);
        sm.checkPermission(perm, acc);
    }
}
 
Example 30
public void testInsertData() throws SQLException, Exception {
    try {

        AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws SQLException, FileNotFoundException,
                    IOException {
                insertData();
                return null;
            }
        });
    } catch (PrivilegedActionException e) {
        throw e.getException();
    }
}