Java Code Examples for java.security.PrivilegedActionException

The following are top voted examples for showing how to use java.security.PrivilegedActionException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: OpenJSharp   File: ManagedObjectManagerFactory.java   View source code 7 votes vote down vote up
/** Convenience method for getting access to a method through reflection.
 * Same as Class.getDeclaredMethod, but only throws RuntimeExceptions.
 * @param cls The class to search for a method.
 * @param name The method name.
 * @param types The array of argument types.
 * @return The Method if found.
 * @throws GmbalException if no such method is found.
 */
public static Method getMethod( final Class<?> cls, final String name,
    final Class<?>... types ) {

    try {
        return AccessController.doPrivileged(
            new PrivilegedExceptionAction<Method>() {
                public Method run() throws Exception {
                    return cls.getDeclaredMethod(name, types);
                }
            });
    } catch (PrivilegedActionException ex) {
        throw new GmbalException( "Unexpected exception", ex ) ;
    } catch (SecurityException exc) {
        throw new GmbalException( "Unexpected exception", exc ) ;
    }
}
 
Example 2
Project: monarch   File: KerberosTicketOperations.java   View source code 7 votes vote down vote up
public static String validateServiceTicket(Subject subject, final byte[] serviceTicket)
    throws GSSException, IllegalAccessException, NoSuchFieldException, ClassNotFoundException,
    PrivilegedActionException {
  // Kerberos version 5 OID
  Oid krb5Oid = KerberosUtils.getOidInstance("GSS_KRB5_MECH_OID");


  // Accept the context and return the client principal name.
  return Subject.doAs(subject, new PrivilegedExceptionAction<String>() {

    @Override
    public String run() throws Exception {
      String clientName = null;
      // Identify the server that communications are being made to.
      GSSManager manager = GSSManager.getInstance();
      GSSContext context = manager.createContext((GSSCredential) null);
      context.acceptSecContext(serviceTicket, 0, serviceTicket.length);
      clientName = context.getSrcName().toString();
      return clientName;
    }
  });
}
 
Example 3
Project: jdk8u-jdk   File: RMIConnectionImpl.java   View source code 6 votes vote down vote up
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 4
Project: elasticsearch_my   File: SocketAccess.java   View source code 6 votes vote down vote up
public static <T> T doPrivilegedIOException(PrivilegedExceptionAction<T> operation) throws IOException {
    SpecialPermission.check();
    try {
        return AccessController.doPrivileged(operation);
    } catch (PrivilegedActionException e) {
        throw (IOException) e.getCause();
    }
}
 
Example 5
Project: elasticsearch_my   File: SocketAccess.java   View source code 6 votes vote down vote up
public static void doPrivilegedVoidException(StorageRunnable action) throws StorageException, URISyntaxException {
    SpecialPermission.check();
    try {
        AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
            action.executeCouldThrow();
            return null;
        });
    } catch (PrivilegedActionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof StorageException) {
            throw (StorageException) cause;
        } else {
            throw (URISyntaxException) cause;
        }
    }
}
 
Example 6
Project: OpenJSharp   File: CodeStore.java   View source code 6 votes vote down vote up
private static File checkDirectory(final String path, final ScriptEnvironment env, final boolean readOnly) throws IOException {
    try {
        return AccessController.doPrivileged(new PrivilegedExceptionAction<File>() {
            @Override
            public File run() throws IOException {
                final File dir = new File(path, getVersionDir(env)).getAbsoluteFile();
                if (readOnly) {
                    if (!dir.exists() || !dir.isDirectory()) {
                        throw new IOException("Not a directory: " + dir.getPath());
                    } else if (!dir.canRead()) {
                        throw new IOException("Directory not readable: " + dir.getPath());
                    }
                } else if (!dir.exists() && !dir.mkdirs()) {
                    throw new IOException("Could not create directory: " + dir.getPath());
                } else if (!dir.isDirectory()) {
                    throw new IOException("Not a directory: " + dir.getPath());
                } else if (!dir.canRead() || !dir.canWrite()) {
                    throw new IOException("Directory not readable or writable: " + dir.getPath());
                }
                return dir;
            }
        });
    } catch (final PrivilegedActionException e) {
        throw (IOException) e.getException();
    }
}
 
Example 7
Project: lazycat   File: StandardManager.java   View source code 6 votes vote down vote up
@Override
public void unload() throws IOException {
	if (SecurityUtil.isPackageProtectionEnabled()) {
		try {
			AccessController.doPrivileged(new PrivilegedDoUnload());
		} catch (PrivilegedActionException ex) {
			Exception exception = ex.getException();
			if (exception instanceof IOException) {
				throw (IOException) exception;
			}
			if (log.isDebugEnabled()) {
				log.debug("Unreported exception in unLoad()", exception);
			}
		}
	} else {
		doUnload();
	}
}
 
Example 8
Project: aries-jpa   File: TempBundleDelegatingClassLoader.java   View source code 6 votes vote down vote up
private Enumeration<URL> findResourcesInBundle(final String resName, final Bundle inBundle) throws IOException {
    Enumeration<URL> resources = null;
    try {
        // Bundle.getResources requires privileges that the client may not
        // have but we need
        // use a doPriv so that only this bundle needs the privileges
        resources = AccessController.doPrivileged(new PrivilegedExceptionAction<Enumeration<URL>>() {
            @Override
            public Enumeration<URL> run() throws IOException {
                return inBundle.getResources(resName);
            }
        });
    } catch (PrivilegedActionException pae) {
        // thrownException can never be a RuntimeException, as that would escape the doPriv normally
        Exception thrownException = pae.getException();
        if (thrownException instanceof IOException) {
            throw (IOException)thrownException;
        } else {
            LOG.warn("Exception during findResourcesInBundle", pae);
        }
    }
    return resources;
}
 
Example 9
Project: hadoop   File: MRApps.java   View source code 6 votes vote down vote up
private static ClassLoader createJobClassLoader(final String appClasspath,
    final String[] systemClasses) throws IOException {
  try {
    return AccessController.doPrivileged(
      new PrivilegedExceptionAction<ClassLoader>() {
        @Override
        public ClassLoader run() throws MalformedURLException {
          return new ApplicationClassLoader(appClasspath,
              MRApps.class.getClassLoader(), Arrays.asList(systemClasses));
        }
    });
  } catch (PrivilegedActionException e) {
    Throwable t = e.getCause();
    if (t instanceof MalformedURLException) {
      throw (MalformedURLException) t;
    }
    throw new IOException(e);
  }
}
 
Example 10
Project: OpenJSharp   File: RMIConnectionImpl.java   View source code 6 votes vote down vote up
private ClassLoader getClassLoaderFor(final ObjectName name)
    throws InstanceNotFoundException {
    try {
        return (ClassLoader)
            AccessController.doPrivileged(
                new PrivilegedExceptionAction<Object>() {
                    public Object run() throws InstanceNotFoundException {
                        return mbeanServer.getClassLoaderFor(name);
                    }
                },
                withPermissions(new MBeanPermission("*", "getClassLoaderFor"))
        );
    } catch (PrivilegedActionException pe) {
        throw (InstanceNotFoundException) extractException(pe);
    }
}
 
Example 11
Project: tomcat7   File: ApplicationDispatcher.java   View source code 6 votes vote down vote up
/**
 * Forward this request and response to another resource for processing.
 * Any runtime exception, IOException, or ServletException thrown by the
 * called servlet will be propagated to the caller.
 *
 * @param request The servlet request to be forwarded
 * @param response The servlet response to be forwarded
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet exception occurs
 */
@Override
public void forward(ServletRequest request, ServletResponse response)
    throws ServletException, IOException
{
    if (Globals.IS_SECURITY_ENABLED) {
        try {
            PrivilegedForward dp = new PrivilegedForward(request,response);
            AccessController.doPrivileged(dp);
        } catch (PrivilegedActionException pe) {
            Exception e = pe.getException();
            if (e instanceof ServletException)
                throw (ServletException) e;
            throw (IOException) e;
        }
    } else {
        doForward(request,response);
    }
}
 
Example 12
Project: OpenJSharp   File: RMIConnectionImpl.java   View source code 6 votes vote down vote up
public Integer getMBeanCount(Subject delegationSubject)
    throws IOException {
    try {
        final Object params[] = new Object[] { };

        if (logger.debugOn()) logger.debug("getMBeanCount",
             "connectionId=" + connectionId);

        return (Integer)
            doPrivilegedOperation(
              GET_MBEAN_COUNT,
              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 13
Project: OpenJSharp   File: UNIXProcess.java   View source code 6 votes vote down vote up
UNIXProcess(final byte[] prog,
            final byte[] argBlock, final int argc,
            final byte[] envBlock, final int envc,
            final byte[] dir,
            final int[] fds,
            final boolean redirectErrorStream)
        throws IOException {

    pid = forkAndExec(launchMechanism.ordinal() + 1,
                      helperpath,
                      prog,
                      argBlock, argc,
                      envBlock, envc,
                      dir,
                      fds,
                      redirectErrorStream);

    try {
        doPrivileged((PrivilegedExceptionAction<Void>) () -> {
            initStreams(fds);
            return null;
        });
    } catch (PrivilegedActionException ex) {
        throw (IOException) ex.getException();
    }
}
 
Example 14
Project: tomcat7   File: PageContextImpl.java   View source code 6 votes vote down vote up
@Override
public void forward(final String relativeUrlPath) throws ServletException,
        IOException {
    if (SecurityUtil.isPackageProtectionEnabled()) {
        try {
            AccessController.doPrivileged(
                    new PrivilegedExceptionAction<Void>() {
                @Override
                public Void run() throws Exception {
                    doForward(relativeUrlPath);
                    return null;
                }
            });
        } catch (PrivilegedActionException e) {
            Exception ex = e.getException();
            if (ex instanceof IOException) {
                throw (IOException) ex;
            } else {
                throw (ServletException) ex;
            }
        }
    } else {
        doForward(relativeUrlPath);
    }
}
 
Example 15
Project: myfaces-trinidad   File: ClassLoaderUtils.java   View source code 6 votes vote down vote up
/**
 * Dynamically accesses the current context class loader. 
 * Includes a check for priviledges against java2 security 
 * to ensure no security related exceptions are encountered. 
 * Returns null if there is no per-thread context class loader.
 */
public static ClassLoader getContextClassLoader()
{
    if (System.getSecurityManager() != null) 
    {
        try 
        {
            ClassLoader cl = AccessController.doPrivileged(new PrivilegedExceptionAction<ClassLoader>()
                    {
                        public ClassLoader run() throws PrivilegedActionException
                        {
                            return Thread.currentThread().getContextClassLoader();
                        }
                    });
            return cl;
        }
        catch (PrivilegedActionException pae)
        {
            throw new FacesException(pae);
        }
    }
    else
    {
        return Thread.currentThread().getContextClassLoader();
    }
}
 
Example 16
Project: jdk8u-jdk   File: IIOPProxyImpl.java   View source code 6 votes vote down vote up
@Override
public Remote toStub(final Remote obj) throws NoSuchObjectException {
    if (System.getSecurityManager() == null) {
        return PortableRemoteObject.toStub(obj);
    } else {
        try {
            return AccessController.doPrivileged(new PrivilegedExceptionAction<Remote>() {

                @Override
                public Remote run() throws Exception {
                    return PortableRemoteObject.toStub(obj);
                }
            }, STUB_ACC);
        } catch (PrivilegedActionException e) {
            if (e.getException() instanceof NoSuchObjectException) {
                throw (NoSuchObjectException)e.getException();
            }
            throw new RuntimeException("Unexpected exception type", e.getException());
        }
    }
}
 
Example 17
Project: jdk8u-jdk   File: HttpURLConnection.java   View source code 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 18
Project: lams   File: PersistentManagerBase.java   View source code 6 votes vote down vote up
/**
 * Clear all sessions from the Store.
 */
public void clearStore() {

    if (store == null)
        return;

    try {     
        if (SecurityUtil.isPackageProtectionEnabled()){
            try{
                AccessController.doPrivileged(new PrivilegedStoreClear());
            }catch(PrivilegedActionException ex){
                Exception exception = ex.getException();
                log.error("Exception clearing the Store: " + exception);
                exception.printStackTrace();                        
            }
        } else {
            store.clear();
        }
    } catch (IOException e) {
        log.error("Exception clearing the Store: " + e);
        e.printStackTrace();
    }

}
 
Example 19
Project: jdk8u-jdk   File: RMIIIOPServerImpl.java   View source code 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 20
Project: OpenJSharp   File: HttpURLConnection.java   View source code 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.doPrivileged(
                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 21
Project: openjdk-jdk10   File: HttpURLConnection.java   View source code 6 votes vote down vote up
@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 22
Project: jdk8u-jdk   File: SerializedLambda.java   View source code 6 votes vote down vote up
private Object readResolve() throws ReflectiveOperationException {
    try {
        Method deserialize = AccessController.doPrivileged(new PrivilegedExceptionAction<Method>() {
            @Override
            public Method run() throws Exception {
                Method m = capturingClass.getDeclaredMethod("$deserializeLambda$", SerializedLambda.class);
                m.setAccessible(true);
                return m;
            }
        });

        return deserialize.invoke(null, this);
    }
    catch (PrivilegedActionException e) {
        Exception cause = e.getException();
        if (cause instanceof ReflectiveOperationException)
            throw (ReflectiveOperationException) cause;
        else if (cause instanceof RuntimeException)
            throw (RuntimeException) cause;
        else
            throw new RuntimeException("Exception in SerializedLambda.readResolve", e);
    }
}
 
Example 23
Project: openjdk-jdk10   File: DataTransferer.java   View source code 6 votes vote down vote up
private ArrayList<String> castToFiles(final List<?> files,
                                      final ProtectionDomain userProtectionDomain) throws IOException {
    try {
        return AccessController.doPrivileged((PrivilegedExceptionAction<ArrayList<String>>) () -> {
            ArrayList<String> fileList = new ArrayList<>();
            for (Object fileObject : files)
            {
                File file = castToFile(fileObject);
                if (file != null &&
                    (null == System.getSecurityManager() ||
                    !(isFileInWebstartedCache(file) ||
                    isForbiddenToRead(file, userProtectionDomain))))
                {
                    fileList.add(file.getCanonicalPath());
                }
            }
            return fileList;
        });
    } catch (PrivilegedActionException pae) {
        throw new IOException(pae.getMessage());
    }
}
 
Example 24
Project: hadoop   File: UserGroupInformation.java   View source code 6 votes vote down vote up
/**
 * Run the given action as the user, potentially throwing an exception.
 * @param <T> the return type of the run method
 * @param action the method to execute
 * @return the value from the run method
 * @throws IOException if the action throws an IOException
 * @throws Error if the action throws an Error
 * @throws RuntimeException if the action throws a RuntimeException
 * @throws InterruptedException if the action throws an InterruptedException
 * @throws UndeclaredThrowableException if the action throws something else
 */
@InterfaceAudience.Public
@InterfaceStability.Evolving
public <T> T doAs(PrivilegedExceptionAction<T> action
                  ) throws IOException, InterruptedException {
  try {
    logPrivilegedAction(subject, action);
    return Subject.doAs(subject, action);
  } catch (PrivilegedActionException pae) {
    Throwable cause = pae.getCause();
    if (LOG.isDebugEnabled()) {
      LOG.debug("PrivilegedActionException as:" + this + " cause:" + cause);
    }
    if (cause instanceof IOException) {
      throw (IOException) cause;
    } else if (cause instanceof Error) {
      throw (Error) cause;
    } else if (cause instanceof RuntimeException) {
      throw (RuntimeException) cause;
    } else if (cause instanceof InterruptedException) {
      throw (InterruptedException) cause;
    } else {
      throw new UndeclaredThrowableException(cause);
    }
  }
}
 
Example 25
Project: apache-tomcat-7.0.73-with-comment   File: ApplicationDispatcher.java   View source code 6 votes vote down vote up
/**
 * Include the response from another resource in the current response.
 * Any runtime exception, IOException, or ServletException thrown by the
 * called servlet will be propagated to the caller.
 *
 * @param request The servlet request that is including this one
 * @param response The servlet response to be appended to
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet exception occurs
 */
@Override
public void include(ServletRequest request, ServletResponse response)
    throws ServletException, IOException
{
    if (Globals.IS_SECURITY_ENABLED) {
        try {
            PrivilegedInclude dp = new PrivilegedInclude(request,response);
            AccessController.doPrivileged(dp);
        } catch (PrivilegedActionException pe) {
            Exception e = pe.getException();

            if (e instanceof ServletException)
                throw (ServletException) e;
            throw (IOException) e;
        }
    } else {
        doInclude(request, response);
    }
}
 
Example 26
Project: OpenJSharp   File: SerializedLambda.java   View source code 6 votes vote down vote up
private Object readResolve() throws ReflectiveOperationException {
    try {
        Method deserialize = AccessController.doPrivileged(new PrivilegedExceptionAction<Method>() {
            @Override
            public Method run() throws Exception {
                Method m = capturingClass.getDeclaredMethod("$deserializeLambda$", SerializedLambda.class);
                m.setAccessible(true);
                return m;
            }
        });

        return deserialize.invoke(null, this);
    }
    catch (PrivilegedActionException e) {
        Exception cause = e.getException();
        if (cause instanceof ReflectiveOperationException)
            throw (ReflectiveOperationException) cause;
        else if (cause instanceof RuntimeException)
            throw (RuntimeException) cause;
        else
            throw new RuntimeException("Exception in SerializedLambda.readResolve", e);
    }
}
 
Example 27
Project: OpenJSharp   File: ManagementFactory.java   View source code 6 votes vote down vote up
/**
 * Registers a DynamicMBean.
 */
private static void addDynamicMBean(final MBeanServer mbs,
                                    final DynamicMBean dmbean,
                                    final ObjectName on) {
    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws InstanceAlreadyExistsException,
                                     MBeanRegistrationException,
                                     NotCompliantMBeanException {
                mbs.registerMBean(dmbean, on);
                return null;
            }
        });
    } catch (PrivilegedActionException e) {
        throw new RuntimeException(e.getException());
    }
}
 
Example 28
Project: apache-tomcat-7.0.73-with-comment   File: ApplicationContextFacade.java   View source code 6 votes vote down vote up
/**
 * Executes the method of the specified <code>ApplicationContext</code>
 * @param method The method object to be invoked.
 * @param context The AppliationContext object on which the method
 *                   will be invoked
 * @param params The arguments passed to the called method.
 */
private Object executeMethod(final Method method, 
                             final ApplicationContext context,
                             final Object[] params) 
        throws PrivilegedActionException, 
               IllegalAccessException,
               InvocationTargetException {
                                 
    if (SecurityUtil.isPackageProtectionEnabled()){
       return AccessController.doPrivileged(new PrivilegedExceptionAction<Object>(){
            @Override
            public Object run() throws IllegalAccessException, InvocationTargetException{
                return method.invoke(context,  params);
            }
        });
    } else {
        return method.invoke(context, params);
    }        
}
 
Example 29
Project: OpenJSharp   File: ArrayNotificationBuffer.java   View source code 5 votes vote down vote up
/**
 * Iterate until we extract the real exception
 * from a stack of PrivilegedActionExceptions.
 */
private static Exception extractException(Exception e) {
    while (e instanceof PrivilegedActionException) {
        e = ((PrivilegedActionException)e).getException();
    }
    return e;
}
 
Example 30
Project: lazycat   File: CoyoteInputStream.java   View source code 5 votes vote down vote up
@Override
public int read() throws IOException {
	if (SecurityUtil.isPackageProtectionEnabled()) {

		try {
			Integer result = AccessController.doPrivileged(new PrivilegedExceptionAction<Integer>() {

				@Override
				public Integer run() throws IOException {
					Integer integer = Integer.valueOf(ib.readByte());
					return integer;
				}

			});
			return result.intValue();
		} catch (PrivilegedActionException pae) {
			Exception e = pae.getException();
			if (e instanceof IOException) {
				throw (IOException) e;
			} else {
				throw new RuntimeException(e.getMessage(), e);
			}
		}
	} else {
		return ib.readByte();
	}
}
 
Example 31
Project: rapidminer   File: ManageDatabaseDriversDialog.java   View source code 5 votes vote down vote up
private List<String> findDrivers(final File file) {
    final LinkedList driverNames = new LinkedList();
    (new ProgressThread("manage_database_drivers.scan_jar", true) {
        public void run() {
            try {
                ClassLoader e = (ClassLoader)AccessController.doPrivileged(new PrivilegedExceptionAction() {
                    public ClassLoader run() throws Exception {
                        try {
                            return new URLClassLoader(new URL[]{file.toURI().toURL()});
                        } catch (MalformedURLException var2) {
                            throw new RuntimeException("Cannot create class loader for file \'" + file + "\': " + var2.getMessage(), var2);
                        }
                    }
                });

                try {
                    JarFile e1 = new JarFile(file);
                    Tools.findImplementationsInJar(e, e1, Driver.class, driverNames);
                } catch (Exception var3) {
                    LogService.getRoot().log(Level.WARNING, I18N.getMessage(LogService.getRoot().getResourceBundle(), "com.rapidminer.gui.tools.dialogs.ManageDatabaseDriversDialog.scanning_jar_file_error", new Object[]{file, var3.getMessage()}), var3);
                }

            } catch (PrivilegedActionException var4) {
                throw new RuntimeException("Cannot create class loader for file \'" + file + "\': " + var4.getMessage(), var4);
            }
        }
    }).startAndWait();
    return driverNames;
}
 
Example 32
Project: hadoop-oss   File: UserGroupInformation.java   View source code 5 votes vote down vote up
/**
 * Run the given action as the user, potentially throwing an exception.
 * @param <T> the return type of the run method
 * @param action the method to execute
 * @return the value from the run method
 * @throws IOException if the action throws an IOException
 * @throws Error if the action throws an Error
 * @throws RuntimeException if the action throws a RuntimeException
 * @throws InterruptedException if the action throws an InterruptedException
 * @throws UndeclaredThrowableException if the action throws something else
 */
@InterfaceAudience.Public
@InterfaceStability.Evolving
public <T> T doAs(PrivilegedExceptionAction<T> action
                  ) throws IOException, InterruptedException {
  try {
    logPrivilegedAction(subject, action);
    return Subject.doAs(subject, action);
  } catch (PrivilegedActionException pae) {
    Throwable cause = pae.getCause();
    if (LOG.isDebugEnabled()) {
      LOG.debug("PrivilegedActionException as:" + this + " cause:" + cause);
    }
    if (cause == null) {
      throw new RuntimeException("PrivilegedActionException with no " +
              "underlying cause. UGI [" + this + "]" +": " + pae, pae);
    } else if (cause instanceof IOException) {
      throw (IOException) cause;
    } else if (cause instanceof Error) {
      throw (Error) cause;
    } else if (cause instanceof RuntimeException) {
      throw (RuntimeException) cause;
    } else if (cause instanceof InterruptedException) {
      throw (InterruptedException) cause;
    } else {
      throw new UndeclaredThrowableException(cause);
    }
  }
}
 
Example 33
Project: jerrydog   File: ApplicationContext.java   View source code 5 votes vote down vote up
/**
 * Return the URL to the resource that is mapped to a specified path.
 * The path must begin with a "/" and is interpreted as relative to the
 * current context root.
 *
 * @param path The path to the desired resource
 *
 * @exception MalformedURLException if the path is not given
 *  in the correct form
 */
public URL getResource(String path)
    throws MalformedURLException {

    DirContext resources = context.getResources();
    if (resources != null) {
        String fullPath = context.getName() + path;

        // this is the problem. Host must not be null
        String hostName = context.getParent().getName();

        try {
            resources.lookup(path);
            if( System.getSecurityManager() != null ) {
                try {
                    PrivilegedGetResource dp =
                        new PrivilegedGetResource
                            (hostName, fullPath, resources);
                    return (URL)AccessController.doPrivileged(dp);
                } catch( PrivilegedActionException pe) {
                    throw pe.getException();
                }
            } else {
                return new URL
                    ("jndi", null, 0, getJNDIUri(hostName, fullPath),
                     new DirContextURLStreamHandler(resources));
            }
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }
    return (null);

}
 
Example 34
Project: elasticsearch_my   File: SocketAccess.java   View source code 5 votes vote down vote up
public static <T> T doPrivilegedException(PrivilegedExceptionAction<T> operation) throws StorageException, URISyntaxException {
    SpecialPermission.check();
    try {
        return AccessController.doPrivileged(operation);
    } catch (PrivilegedActionException e) {
        throw (StorageException) e.getCause();
    }
}
 
Example 35
Project: jerrydog   File: HttpResponseBase.java   View source code 5 votes vote down vote up
/**
 * Flush the buffer and commit this response.  If this is the first output,
 * send the HTTP headers prior to the user data.
 *
 * @exception IOException if an input/output error occurs
 */
public void flushBuffer() throws IOException {

    if( System.getSecurityManager() != null ) {
        try {
            PrivilegedFlushBuffer dp = new PrivilegedFlushBuffer();
            AccessController.doPrivileged(dp);
        } catch( PrivilegedActionException pe) {
            throw (IOException)pe.getException();
        }
    } else {
        doFlushBuffer();
    }

}
 
Example 36
Project: openjdk-jdk10   File: ExecutableInputMethodManager.java   View source code 5 votes vote down vote up
private void initializeInputMethodLocatorList() {
    synchronized (javaInputMethodLocatorList) {
        javaInputMethodLocatorList.clear();
        try {
            AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                public Object run() {
                    for (InputMethodDescriptor descriptor :
                        ServiceLoader.load(InputMethodDescriptor.class,
                                           ClassLoader.getSystemClassLoader())) {
                        ClassLoader cl = descriptor.getClass().getClassLoader();
                        javaInputMethodLocatorList.add(new InputMethodLocator(descriptor, cl, null));
                    }
                    return null;
                }
            });
        }  catch (PrivilegedActionException e) {
            e.printStackTrace();
        }
        javaInputMethodCount = javaInputMethodLocatorList.size();
    }

    if (hasMultipleInputMethods()) {
        // initialize preferences
        if (userRoot == null) {
            userRoot = getUserRoot();
        }
    } else {
        // indicate to clients not to offer the menu
        triggerMenuString = null;
    }
}
 
Example 37
Project: openjdk-jdk10   File: FileSystemPreferences.java   View source code 5 votes vote down vote up
/**
 * 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 38
Project: jdk8u-jdk   File: RMIConnectionImpl.java   View source code 5 votes vote down vote up
public ObjectInstance getObjectInstance(ObjectName name,
                                        Subject delegationSubject)
    throws
    InstanceNotFoundException,
    IOException {

    checkNonNull("ObjectName", name);

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

        if (logger.debugOn()) logger.debug("getObjectInstance",
             "connectionId=" + connectionId
             +", name="+name);

        return (ObjectInstance)
            doPrivilegedOperation(
              GET_OBJECT_INSTANCE,
              params,
              delegationSubject);
    } catch (PrivilegedActionException pe) {
        Exception e = extractException(pe);
        if (e instanceof InstanceNotFoundException)
            throw (InstanceNotFoundException) e;
        if (e instanceof IOException)
            throw (IOException) e;
        throw newIOException("Got unexpected server exception: " + e, e);
    }
}
 
Example 39
Project: OpenJSharp   File: SecuritySupport.java   View source code 5 votes vote down vote up
static FileInputStream getFileInputStream(final File file)
throws FileNotFoundException
{
    try {
        return (FileInputStream)
        AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws FileNotFoundException {
                return new FileInputStream(file);
            }
        });
    } catch (PrivilegedActionException e) {
        throw (FileNotFoundException)e.getException();
    }
}
 
Example 40
Project: tomcat7   File: ResponseFacade.java   View source code 5 votes vote down vote up
@Override
public void flushBuffer()
    throws IOException {

    if (isFinished()) {
        //            throw new IllegalStateException
        //                (/*sm.getString("responseFacade.finished")*/);
        return;
    }

    if (SecurityUtil.isPackageProtectionEnabled()){
        try{
            AccessController.doPrivileged(
                    new PrivilegedExceptionAction<Void>(){

                @Override
                public Void run() throws IOException{
                    response.setAppCommitted(true);

                    response.flushBuffer();
                    return null;
                }
            });
        } catch(PrivilegedActionException e){
            Exception ex = e.getException();
            if (ex instanceof IOException){
                throw (IOException)ex;
            }
        }
    } else {
        response.setAppCommitted(true);

        response.flushBuffer();
    }

}