Java Code Examples for java.security.PrivilegedExceptionAction

The following examples show how to use java.security.PrivilegedExceptionAction. 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: netbeans   Source File: BaseFileObj.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String readSymbolicLinkPath() throws IOException {
    final Path path = getNativePath();
    try {
        return AccessController.doPrivileged(
                new PrivilegedExceptionAction<String>() {

                    @Override
                    public String run() throws Exception {
                        Path target = Files.readSymbolicLink(path);
                        return target.toString();
                    }
                });
    } catch (PrivilegedActionException ex) {
        throw new IOException(ex);
    }
}
 
Example 2
Source Project: jdk8u60   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 3
Source Project: big-c   Source File: TestWebDelegationToken.java    License: Apache License 2.0 6 votes vote down vote up
public static <T> T doAsKerberosUser(String principal, String keytab,
    final Callable<T> callable) throws Exception {
  LoginContext loginContext = null;
  try {
    Set<Principal> principals = new HashSet<Principal>();
    principals.add(new KerberosPrincipal(principal));
    Subject subject = new Subject(false, principals, new HashSet<Object>(),
        new HashSet<Object>());
    loginContext = new LoginContext("", subject, null,
        new KerberosConfiguration(principal, keytab));
    loginContext.login();
    subject = loginContext.getSubject();
    return Subject.doAs(subject, new PrivilegedExceptionAction<T>() {
      @Override
      public T run() throws Exception {
        return callable.call();
      }
    });
  } catch (PrivilegedActionException ex) {
    throw ex.getException();
  } finally {
    if (loginContext != null) {
      loginContext.logout();
    }
  }
}
 
Example 4
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 5
Source Project: lams   Source File: SecurityActions.java    License: GNU General Public License v2.0 6 votes vote down vote up
static Class<?> loadClass(final String name) throws PrivilegedActionException 
{
   return AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>()
   {
      public Class<?> run() throws PrivilegedActionException
      {
         try
         {
            return getClass().getClassLoader().loadClass(name);
         }
         catch (Exception ignore)
         {
            try
            {
               return getContextClassLoader().loadClass(name);
            }
            catch (Exception e)
            {
               throw new PrivilegedActionException(e);
            }
         }
      }
   });
}
 
Example 6
/**
 * 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 7
Source Project: jdk8u_jdk   Source File: ActivationID.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Activate the object for this id.
 *
 * @param force if true, forces the activator to contact the group
 * when activating the object (instead of returning a cached reference);
 * if false, returning a cached value is acceptable.
 * @return the reference to the active remote object
 * @exception ActivationException if activation fails
 * @exception UnknownObjectException if the object is unknown
 * @exception RemoteException if remote call fails
 * @since 1.2
 */
public Remote activate(boolean force)
    throws ActivationException, UnknownObjectException, RemoteException
{
    try {
        MarshalledObject<? extends Remote> mobj =
            activator.activate(this, force);
        return AccessController.doPrivileged(
            new PrivilegedExceptionAction<Remote>() {
                public Remote run() throws IOException, ClassNotFoundException {
                    return mobj.get();
                }
            }, NOPERMS_ACC);
    } catch (PrivilegedActionException pae) {
        Exception ex = pae.getException();
        if (ex instanceof RemoteException) {
            throw (RemoteException) ex;
        } else {
            throw new UnmarshalException("activation failed", ex);
        }
    }

}
 
Example 8
/**
 * A submitted privileged exception action runs to completion
 */
public void testSubmitPrivilegedExceptionAction() throws Exception {
    final Callable callable =
        Executors.callable(new PrivilegedExceptionAction() {
            public Object run() { return TEST_STRING; }});
    Runnable r = new CheckedRunnable() {
    public void realRun() throws Exception {
        ExecutorService e = new ForkJoinPool(1);
        try (PoolCleaner cleaner = cleaner(e)) {
            Future future = e.submit(callable);
            assertSame(TEST_STRING, future.get());
        }
    }};

    runWithPermissions(r, new RuntimePermission("modifyThread"));
}
 
Example 9
Source Project: jdk8u_nashorn   Source File: CodeStore.java    License: GNU General Public License v2.0 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 10
private ArrayList<String> castToFiles(final List files,
                                      final ProtectionDomain userProtectionDomain) throws IOException
{
    final ArrayList<String> fileList = new ArrayList<String>();
    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws IOException {
                for (Object fileObject : files)
                {
                    File file = castToFile(fileObject);
                    if (file != null &&
                        (null == System.getSecurityManager() ||
                        !(isFileInWebstartedCache(file) ||
                        isForbiddenToRead(file, userProtectionDomain))))
                    {
                        fileList.add(file.getCanonicalPath());
                    }
                }
                return null;
            }
        });
    } catch (PrivilegedActionException pae) {
        throw new IOException(pae.getMessage());
    }
    return fileList;
}
 
Example 11
@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 12
public static void unbindAndCloseSilently(final Connection connection) {
    if (connection == null) {
        return;
    }

    final SecurityManager sm = System.getSecurityManager();

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

    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                connection.close();
                return null;
            }
        });
    } catch (PrivilegedActionException e) {
        // ignore
    }
}
 
Example 13
Source Project: hottub   Source File: Socket.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns an output stream for this socket.
 *
 * <p> If this socket has an associated channel then the resulting output
 * stream delegates all of its operations to the channel.  If the channel
 * is in non-blocking mode then the output stream's {@code write}
 * operations will throw an {@link
 * java.nio.channels.IllegalBlockingModeException}.
 *
 * <p> Closing the returned {@link java.io.OutputStream OutputStream}
 * will close the associated socket.
 *
 * @return     an output stream for writing bytes to this socket.
 * @exception  IOException  if an I/O error occurs when creating the
 *               output stream or if the socket is not connected.
 * @revised 1.4
 * @spec JSR-51
 */
public OutputStream getOutputStream() throws IOException {
    if (isClosed())
        throw new SocketException("Socket is closed");
    if (!isConnected())
        throw new SocketException("Socket is not connected");
    if (isOutputShutdown())
        throw new SocketException("Socket output is shutdown");
    final Socket s = this;
    OutputStream os = null;
    try {
        os = AccessController.doPrivileged(
            new PrivilegedExceptionAction<OutputStream>() {
                public OutputStream run() throws IOException {
                    return impl.getOutputStream();
                }
            });
    } catch (java.security.PrivilegedActionException e) {
        throw (IOException) e.getException();
    }
    return os;
}
 
Example 14
private static boolean isInstanceOf(final MBeanServer mbs,
                                    final ObjectName name,
                                    final String className) {
    PrivilegedExceptionAction<Boolean> act =
        new PrivilegedExceptionAction<Boolean>() {
            public Boolean run() throws InstanceNotFoundException {
                return mbs.isInstanceOf(name, className);
            }
        };
    try {
        return AccessController.doPrivileged(act);
    } catch (Exception e) {
        logger.fine("isInstanceOf", "failed: " + e);
        logger.debug("isInstanceOf", e);
        return false;
    }
}
 
Example 15
public static byte[] jsonMapToByteArray(Map<String, Object> jsonAsMap) throws IOException {

        final SecurityManager sm = System.getSecurityManager();

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

        try {
            return AccessController.doPrivileged(new PrivilegedExceptionAction<byte[]>() {
                @Override
                public byte[] run() throws Exception {
                    return internalMapper.writeValueAsBytes(jsonAsMap);
                }
            });
        } catch (final PrivilegedActionException e) {
            if (e.getCause() instanceof JsonProcessingException) {
                throw (JsonProcessingException) e.getCause();
            } else if (e.getCause() instanceof RuntimeException) {
                throw (RuntimeException) e.getCause();
            } else {
                throw new RuntimeException(e.getCause());
            }
        }
    }
 
Example 16
Source Project: openjdk-8   Source File: HttpURLConnection.java    License: GNU General Public License v2.0 6 votes vote down vote up
private String getHostAndPort(URL url) {
    String host = url.getHost();
    final String hostarg = host;
    try {
        // lookup hostname and use IP address if available
        host = AccessController.doPrivileged(
            new PrivilegedExceptionAction<String>() {
                public String run() throws IOException {
                        InetAddress addr = InetAddress.getByName(hostarg);
                        return addr.getHostAddress();
                }
            }
        );
    } catch (PrivilegedActionException e) {}
    int port = url.getPort();
    if (port == -1) {
        String scheme = url.getProtocol();
        if ("http".equals(scheme)) {
            return host + ":80";
        } else { // scheme must be https
            return host + ":443";
        }
    }
    return host + ":" + Integer.toString(port);
}
 
Example 17
Source Project: jdk8u-jdk   Source File: RMIConnectionImpl.java    License: GNU General Public License v2.0 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 18
/**
 * 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 19
Source Project: netbeans   Source File: BaseFileObj.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public FileObject readSymbolicLink() throws IOException {
    final Path path = getNativePath();
    try {
        return AccessController.doPrivileged(
                new PrivilegedExceptionAction<FileObject>() {

                    @Override
                    public FileObject run() throws Exception {
                        Path target = Files.readSymbolicLink(path);
                        Path absoluteTarget = target.isAbsolute()
                            ? target
                            : path.getParent().resolve(target);
                        File file = absoluteTarget.toFile();
                        File normFile = FileUtil.normalizeFile(file);
                        return FileBasedFileSystem.getFileObject(normFile);
                    }
                });
    } catch (PrivilegedActionException ex) {
        throw new IOException(ex);
    }
}
 
Example 20
Source Project: hadoop   Source File: JobClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets all the jobs which were added to particular Job Queue
 * 
 * @param queueName name of the Job Queue
 * @return Array of jobs present in the job queue
 * @throws IOException
 */

public JobStatus[] getJobsFromQueue(final String queueName) throws IOException {
  try {
    QueueInfo queue = clientUgi.doAs(new PrivilegedExceptionAction<QueueInfo>() {
      @Override
      public QueueInfo run() throws IOException, InterruptedException {
        return cluster.getQueue(queueName);
      }
    });
    if (queue == null) {
      return null;
    }
    org.apache.hadoop.mapreduce.JobStatus[] stats = 
      queue.getJobStatuses();
    JobStatus[] ret = new JobStatus[stats.length];
    for (int i = 0 ; i < stats.length; i++ ) {
      ret[i] = JobStatus.downgrade(stats[i]);
    }
    return ret;
  } catch (InterruptedException ie) {
    throw new IOException(ie);
  }
}
 
Example 21
Source Project: hadoop   Source File: TestPermissionSymlinks.java    License: Apache License 2.0 6 votes vote down vote up
private void doDeleteTargetParentAndTargetNotWritable() throws Exception {
  // Try a delete where the symlink parent dir is writable,
  // but the target's parent and target are not
  user.doAs(new PrivilegedExceptionAction<Object>() {
    @Override
    public Object run() throws IOException {
      FileContext myfc = FileContext.getFileContext(conf);
      myfc.delete(link, false);
      return null;
    }
  });
  // Make sure only the link was deleted
  assertTrue("Target should not have been deleted!",
      wrapper.exists(target));
  assertFalse("Link should have been deleted!",
      wrapper.exists(link));
}
 
Example 22
private void addNotificationListener(final ObjectName name,
                                     final NotificationListener listener,
                                     final NotificationFilter filter,
                                     final Object handback)
        throws Exception {
    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
            public Void run() throws InstanceNotFoundException {
                mBeanServer.addNotificationListener(name,
                                                    listener,
                                                    filter,
                                                    handback);
                return null;
            }
        });
    } catch (Exception e) {
        throw extractException(e);
    }
}
 
Example 23
public static void main(String[] args) throws Exception {

        // We don't care about clock difference
        new FileOutputStream("krb5.conf").write(
                "[libdefaults]\nclockskew=999999999".getBytes());
        System.setProperty("java.security.krb5.conf", "krb5.conf");
        Config.refresh();

        Subject subj = new Subject();
        KerberosPrincipal kp = new KerberosPrincipal(princ);
        KerberosKey kk = new KerberosKey(
                kp, key, EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96, 0);
        subj.getPrincipals().add(kp);
        subj.getPrivateCredentials().add(kk);

        Subject.doAs(subj, new PrivilegedExceptionAction() {
            public Object run() throws Exception {
                GSSManager man = GSSManager.getInstance();
                GSSContext ctxt = man.createContext(man.createCredential(
                        null, GSSCredential.INDEFINITE_LIFETIME,
                        GSSUtil.GSS_KRB5_MECH_OID, GSSCredential.ACCEPT_ONLY));
                return ctxt.acceptSecContext(token, 0, token.length);
            }
        });
    }
 
Example 24
Source Project: jdk8u-jdk   Source File: HttpURLConnection.java    License: GNU General Public License v2.0 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<InputStream>() {
                    public InputStream run() throws IOException {
                        return getInputStream0();
                    }
                }, null, p
            );
        } catch (PrivilegedActionException e) {
            throw (IOException) e.getException();
        }
    } else {
        return getInputStream0();
    }
}
 
Example 25
/**
 * Construct a built in implementation with priveleges.
 * Returning null indicates a non-built is specified.
 */
private IIOPOutputStream createOutputStreamBuiltIn(
    final String name
) throws Throwable {
    try {
        return AccessController.doPrivileged(
            new PrivilegedExceptionAction<IIOPOutputStream>() {
                public IIOPOutputStream run() throws IOException {
                    return createOutputStreamBuiltInNoPriv(name);
                }
            }
        );
    } catch (java.security.PrivilegedActionException exc) {
        throw exc.getCause();
    }
}
 
Example 26
Source Project: gemfirexd-oss   Source File: LOBStreamControl.java    License: Apache License 2.0 6 votes vote down vote up
static
// GemStone changes END
    private void deleteFile (StorageFile file) throws IOException {
        try {
            final StorageFile sf = file;
            AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                public Object run() throws IOException {
                    sf.delete();
                    return null;
                }
            });
        } catch (PrivilegedActionException pae) {
            Exception e = pae.getException();
            if (e instanceof IOException)
                throw (IOException) e;
            if (e instanceof RuntimeException)
                throw (RuntimeException) e;
            throw Util.newIOException(e);
        }
    }
 
Example 27
Source Project: openjdk-jdk9   Source File: ServerSocket.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void checkOldImpl() {
    if (impl == null)
        return;
    // SocketImpl.connect() is a protected method, therefore we need to use
    // getDeclaredMethod, therefore we need permission to access the member
    try {
        AccessController.doPrivileged(
            new PrivilegedExceptionAction<Void>() {
                public Void run() throws NoSuchMethodException {
                    impl.getClass().getDeclaredMethod("connect",
                                                      SocketAddress.class,
                                                      int.class);
                    return null;
                }
            });
    } catch (java.security.PrivilegedActionException e) {
        oldImpl = true;
    }
}
 
Example 28
private void addNotificationListener(final ObjectName name,
                                     final NotificationListener listener,
                                     final NotificationFilter filter,
                                     final Object handback)
        throws Exception {
    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
            public Void run() throws InstanceNotFoundException {
                mBeanServer.addNotificationListener(name,
                                                    listener,
                                                    filter,
                                                    handback);
                return null;
            }
        });
    } catch (Exception e) {
        throw extractException(e);
    }
}
 
Example 29
Source Project: jdk8u60   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 30
Source Project: jdk8u-jdk   Source File: Statement.java    License: GNU General Public License v2.0 6 votes vote down vote up
Object invoke() throws Exception {
    AccessControlContext acc = this.acc;
    if ((acc == null) && (System.getSecurityManager() != null)) {
        throw new SecurityException("AccessControlContext is not set");
    }
    try {
        return AccessController.doPrivileged(
                new PrivilegedExceptionAction<Object>() {
                    public Object run() throws Exception {
                        return invokeInternal();
                    }
                },
                acc
        );
    }
    catch (PrivilegedActionException exception) {
        throw exception.getException();
    }
}