Java Code Examples for java.security.PrivilegedExceptionAction

The following are top voted examples for showing how to use java.security.PrivilegedExceptionAction. 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: openjdk-jdk10   File: KrbCredSubKey.java   View source code 9 votes vote down vote up
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 2
Project: openjdk-jdk10   File: SocksSocketImpl.java   View source code 6 votes vote down vote up
private synchronized void privilegedConnect(final String host,
                                          final int port,
                                          final int timeout)
     throws IOException
{
    try {
        AccessController.doPrivileged(
            new java.security.PrivilegedExceptionAction<>() {
                public Void run() throws IOException {
                          superConnectServer(host, port, timeout);
                          cmdIn = getInputStream();
                          cmdOut = getOutputStream();
                          return null;
                      }
                  });
    } catch (java.security.PrivilegedActionException pae) {
        throw (IOException) pae.getException();
    }
}
 
Example 3
Project: hadoop   File: GenerateDistCacheData.java   View source code 6 votes vote down vote up
@Override
public Job call() throws IOException, InterruptedException,
                         ClassNotFoundException {
  UserGroupInformation ugi = UserGroupInformation.getLoginUser();
  ugi.doAs( new PrivilegedExceptionAction <Job>() {
     public Job run() throws IOException, ClassNotFoundException,
                             InterruptedException {
      job.setMapperClass(GenDCDataMapper.class);
      job.setNumReduceTasks(0);
      job.setMapOutputKeyClass(NullWritable.class);
      job.setMapOutputValueClass(BytesWritable.class);
      job.setInputFormatClass(GenDCDataFormat.class);
      job.setOutputFormatClass(NullOutputFormat.class);
      job.setJarByClass(GenerateDistCacheData.class);
      try {
        FileInputFormat.addInputPath(job, new Path("ignored"));
      } catch (IOException e) {
        LOG.error("Error while adding input path ", e);
      }
      job.submit();
      return job;
    }
  });
  return job;
}
 
Example 4
Project: incubator-netbeans   File: BaseFileObj.java   View source code 6 votes vote down vote up
@Override
public FileObject getCanonicalFileObject() throws IOException {
    final Path path = getNativePath();
    try {
        return AccessController.doPrivileged(
                new PrivilegedExceptionAction<FileObject>() {

                    @Override
                    public FileObject run() throws Exception {
                        Path realPath = path.toRealPath();
                        File realFile = realPath.toFile();
                        return FileBasedFileSystem.getFileObject(realFile);
                    }
                });
    } catch (PrivilegedActionException ex) {
        throw new IOException(ex);
    }
}
 
Example 5
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 6
Project: hadoop   File: TestContainerManagerRecovery.java   View source code 6 votes vote down vote up
private StartContainersResponse startContainer(Context context,
    final ContainerManagerImpl cm, ContainerId cid,
    ContainerLaunchContext clc, LogAggregationContext logAggregationContext)
        throws Exception {
  UserGroupInformation user = UserGroupInformation.createRemoteUser(
      cid.getApplicationAttemptId().toString());
  StartContainerRequest scReq = StartContainerRequest.newInstance(
      clc, TestContainerManager.createContainerToken(cid, 0,
          context.getNodeId(), user.getShortUserName(),
          context.getContainerTokenSecretManager(), logAggregationContext));
  final List<StartContainerRequest> scReqList =
      new ArrayList<StartContainerRequest>();
  scReqList.add(scReq);
  NMTokenIdentifier nmToken = new NMTokenIdentifier(
      cid.getApplicationAttemptId(), context.getNodeId(),
      user.getShortUserName(),
      context.getNMTokenSecretManager().getCurrentKey().getKeyId());
  user.addTokenIdentifier(nmToken);
  return user.doAs(new PrivilegedExceptionAction<StartContainersResponse>() {
    @Override
    public StartContainersResponse run() throws Exception {
      return cm.startContainers(
          StartContainersRequest.newInstance(scReqList));
    }
  });
}
 
Example 7
Project: hadoop-oss   File: FileContext.java   View source code 6 votes vote down vote up
private static AbstractFileSystem getAbstractFileSystem(
    UserGroupInformation user, final URI uri, final Configuration conf)
    throws UnsupportedFileSystemException, IOException {
  try {
    return user.doAs(new PrivilegedExceptionAction<AbstractFileSystem>() {
      @Override
      public AbstractFileSystem run() throws UnsupportedFileSystemException {
        return AbstractFileSystem.get(uri, conf);
      }
    });
  } catch (InterruptedException ex) {
    LOG.error(ex);
    throw new IOException("Failed to get the AbstractFileSystem for path: "
        + uri, ex);
  }
}
 
Example 8
Project: hadoop   File: TestClientToAMTokens.java   View source code 6 votes vote down vote up
private void verifyValidToken(final Configuration conf, final CustomAM am,
    Token<ClientToAMTokenIdentifier> token) throws IOException,
    InterruptedException {
  UserGroupInformation ugi;
  ugi = UserGroupInformation.createRemoteUser("me");
  ugi.addToken(token);

  ugi.doAs(new PrivilegedExceptionAction<Void>() {
    @Override
    public Void run() throws Exception {
      CustomProtocol client =
          (CustomProtocol) RPC.getProxy(CustomProtocol.class, 1L, am.address,
            conf);
      client.ping();
      Assert.assertTrue(am.pinged);
      return null;
    }
  });
}
 
Example 9
Project: ditb   File: TestVisibilityLabelsWithDefaultVisLabelService.java   View source code 6 votes vote down vote up
@Test
public void testListLabelsWithRegEx() throws Throwable {
  PrivilegedExceptionAction<ListLabelsResponse> action =
      new PrivilegedExceptionAction<ListLabelsResponse>() {
    public ListLabelsResponse run() throws Exception {
      ListLabelsResponse response = null;
      try (Connection conn = ConnectionFactory.createConnection(conf)) {
        response = VisibilityClient.listLabels(conn, ".*secret");
      } catch (Throwable e) {
        fail("Should not have thrown exception");
      }
      // Only return the labels that end with 'secret'
      List<ByteString> labels = response.getLabelList();
      assertEquals(2, labels.size());
      assertTrue(labels.contains(ByteString.copyFrom(SECRET.getBytes())));
      assertTrue(labels.contains(ByteString.copyFrom(TOPSECRET.getBytes())));
      return null;
    }
  };
  SUPERUSER.runAs(action);
}
 
Example 10
Project: ditb   File: TestVisibilityLabelsWithDeletes.java   View source code 6 votes vote down vote up
public static void addLabels() throws Exception {
  PrivilegedExceptionAction<VisibilityLabelsResponse> action =
      new PrivilegedExceptionAction<VisibilityLabelsResponse>() {
    @Override
    public VisibilityLabelsResponse run() throws Exception {
      String[] labels = { SECRET, TOPSECRET, CONFIDENTIAL, PUBLIC, PRIVATE };
      try (Connection conn = ConnectionFactory.createConnection(conf)) {
        VisibilityClient.addLabels(conn, labels);
      } catch (Throwable t) {
        throw new IOException(t);
      }
      return null;
    }
  };
  SUPERUSER.runAs(action);
}
 
Example 11
Project: openjdk-jdk10   File: HttpURLConnection.java   View source code 6 votes vote down vote up
@Override
public synchronized OutputStream getOutputStream() throws IOException {
    connecting = true;
    SocketPermission p = URLtoSocketPermission(this.url);

    if (p != null) {
        try {
            return AccessController.doPrivilegedWithCombiner(
                new PrivilegedExceptionAction<>() {
                    public OutputStream run() throws IOException {
                        return getOutputStream0();
                    }
                }, null, p
            );
        } catch (PrivilegedActionException e) {
            throw (IOException) e.getException();
        }
    } else {
        return getOutputStream0();
    }
}
 
Example 12
Project: jdk8u-jdk   File: ArrayNotificationBuffer.java   View source code 6 votes vote down vote up
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 13
Project: openjdk-jdk10   File: SocketAdaptor.java   View source code 6 votes vote down vote up
public InputStream getInputStream() throws IOException {
    if (!sc.isOpen())
        throw new SocketException("Socket is closed");
    if (!sc.isConnected())
        throw new SocketException("Socket is not connected");
    if (!sc.isInputOpen())
        throw new SocketException("Socket input is shutdown");
    if (socketInputStream == null) {
        try {
            socketInputStream = AccessController.doPrivileged(
                new PrivilegedExceptionAction<InputStream>() {
                    public InputStream run() throws IOException {
                        return new SocketInputStream();
                    }
                });
        } catch (java.security.PrivilegedActionException e) {
            throw (IOException)e.getException();
        }
    }
    return socketInputStream;
}
 
Example 14
Project: ditb   File: TestCellACLWithMultipleVersions.java   View source code 6 votes vote down vote up
private void verifyUserDeniedForIncrementMultipleVersions(final User user, final byte[] row,
    final byte[] q1) throws IOException, InterruptedException {
  user.runAs(new PrivilegedExceptionAction<Void>() {
    @Override
    public Void run() throws Exception {
      try (Connection connection = ConnectionFactory.createConnection(conf)) {
        try (Table t = connection.getTable(TEST_TABLE.getTableName())) {
          Increment inc = new Increment(row);
          inc.setTimeRange(0, 127);
          inc.addColumn(TEST_FAMILY1, q1, 2L);
          t.increment(inc);
          fail(user.getShortName() + " cannot do the increment.");
        } catch (Exception e) {

        }
      }
      return null;
    }
  });
}
 
Example 15
Project: hadoop   File: TestDFSPermission.java   View source code 6 votes vote down vote up
@Test
public void testAccessGroupMember() throws IOException, InterruptedException {
  FileSystem rootFs = FileSystem.get(conf);
  Path p2 = new Path("/p2");
  rootFs.mkdirs(p2);
  rootFs.setOwner(p2, UserGroupInformation.getCurrentUser().getShortUserName(), GROUP1_NAME);
  rootFs.setPermission(p2, new FsPermission((short) 0740));
  fs = USER1.doAs(new PrivilegedExceptionAction<FileSystem>() {
    @Override
    public FileSystem run() throws Exception {
      return FileSystem.get(conf);
    }
  });
  fs.access(p2, FsAction.READ);
  try {
    fs.access(p2, FsAction.EXECUTE);
    fail("The access call should have failed.");
  } catch (AccessControlException e) {
    assertTrue("Permission denied messages must carry the username",
            e.getMessage().contains(USER1_NAME));
    assertTrue("Permission denied messages must carry the path parent",
            e.getMessage().contains(
                p2.getParent().toUri().getPath()));
  }
}
 
Example 16
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 17
Project: scheduling-connector-for-hadoop   File: FSDownload.java   View source code 6 votes vote down vote up
@Override
public Path call() throws Exception {
  final Path sCopy = resource.getResource();
  createDir(destDirPath, cachePerms);
  final Path dst_work = destDirPath;
  createDir(dst_work, cachePerms);
  Path dFinal = files.makeQualified(new Path(dst_work, resource
      .getTargetName()));
  try {
    Path dTmp = null == userUgi ? files.makeQualified(copy(sCopy, dst_work))
        : userUgi.doAs(new PrivilegedExceptionAction<Path>() {
          public Path run() throws Exception {
            return files.makeQualified(copy(sCopy, dst_work));
          };
        });
    unpack(new File(dTmp.toUri()), new File(dFinal.toUri()));
    changePermissions(dFinal.getFileSystem(conf), dFinal);
  } catch (Exception e) {
    throw e;
  } finally {
    conf = null;
    resource = null;
  }
  return files.makeQualified(new Path(destDirPath, sCopy.getName()));
}
 
Example 18
Project: apache-tomcat-7.0.73-with-comment   File: PageContextImpl.java   View source code 6 votes vote down vote up
@Override
public void include(final String relativeUrlPath, final boolean flush)
        throws ServletException, IOException {
    if (SecurityUtil.isPackageProtectionEnabled()) {
        try {
            AccessController.doPrivileged(
                    new PrivilegedExceptionAction<Void>() {
                @Override
                public Void run() throws Exception {
                    doInclude(relativeUrlPath, flush);
                    return null;
                }
            });
        } catch (PrivilegedActionException e) {
            Exception ex = e.getException();
            if (ex instanceof IOException) {
                throw (IOException) ex;
            } else {
                throw (ServletException) ex;
            }
        }
    } else {
        doInclude(relativeUrlPath, flush);
    }
}
 
Example 19
Project: hadoop   File: GridmixJob.java   View source code 6 votes vote down vote up
protected GridmixJob(final Configuration conf, long submissionMillis, 
                     final String name) throws IOException {
  submissionTimeNanos = TimeUnit.NANOSECONDS.convert(
      submissionMillis, TimeUnit.MILLISECONDS);
  jobdesc = null;
  outdir = null;
  seq = -1;
  ugi = UserGroupInformation.getCurrentUser();

  try {
    job = this.ugi.doAs(new PrivilegedExceptionAction<Job>() {
      public Job run() throws IOException {
        Job ret = Job.getInstance(conf, name);
        ret.getConfiguration().setInt(GRIDMIX_JOB_SEQ, seq);
        setJobQueue(ret, conf.get(GRIDMIX_DEFAULT_QUEUE));
        return ret;
      }
    });
  } catch (InterruptedException e) {
    throw new IOException(e);
  }
}
 
Example 20
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 21
Project: OpenJSharp   File: ServerSocket.java   View source code 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 22
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 23
Project: hadoop   File: HttpFSFileSystem.java   View source code 6 votes vote down vote up
/**
 * Convenience method that creates a <code>HttpURLConnection</code> for the
 * HttpFSServer file system operations.
 * <p/>
 * This methods performs and injects any needed authentication credentials
 * via the {@link #getConnection(URL, String)} method
 *
 * @param method the HTTP method.
 * @param params the query string parameters.
 * @param multiValuedParams multi valued parameters of the query string
 * @param path the file path
 * @param makeQualified if the path should be 'makeQualified'
 *
 * @return HttpURLConnection a <code>HttpURLConnection</code> for the
 *         HttpFSServer server, authenticated and ready to use for the
 *         specified path and file system operation.
 *
 * @throws IOException thrown if an IO error occurrs.
 */
private HttpURLConnection getConnection(final String method,
    Map<String, String> params, Map<String, List<String>> multiValuedParams,
    Path path, boolean makeQualified) throws IOException {
  if (makeQualified) {
    path = makeQualified(path);
  }
  final URL url = HttpFSUtils.createURL(path, params, multiValuedParams);
  try {
    return UserGroupInformation.getCurrentUser().doAs(
        new PrivilegedExceptionAction<HttpURLConnection>() {
          @Override
          public HttpURLConnection run() throws Exception {
            return getConnection(url, method);
          }
        }
    );
  } catch (Exception ex) {
    if (ex instanceof IOException) {
      throw (IOException) ex;
    } else {
      throw new IOException(ex);
    }
  }
}
 
Example 24
Project: hadoop   File: TestSecureLogins.java   View source code 6 votes vote down vote up
@Test
public void testUGILogin() throws Throwable {

  UserGroupInformation ugi = loginUGI(ZOOKEEPER, keytab_zk);
  RegistrySecurity.UgiInfo ugiInfo =
      new RegistrySecurity.UgiInfo(ugi);
  LOG.info("logged in as: {}", ugiInfo);
  assertTrue("security is not enabled: " + ugiInfo,
      UserGroupInformation.isSecurityEnabled());
  assertTrue("login is keytab based: " + ugiInfo,
      ugi.isFromKeytab());

  // now we are here, build a SASL ACL
  ACL acl = ugi.doAs(new PrivilegedExceptionAction<ACL>() {
    @Override
    public ACL run() throws Exception {
      return registrySecurity.createSaslACLFromCurrentUser(0);
    }
  });
  assertEquals(ZOOKEEPER_REALM, acl.getId().getId());
  assertEquals(ZookeeperConfigOptions.SCHEME_SASL, acl.getId().getScheme());
  registrySecurity.addSystemACL(acl);

}
 
Example 25
Project: OpenJSharp   File: URLClassPath.java   View source code 6 votes vote down vote up
private Loader getLoader(final URL url) throws IOException {
    try {
        return java.security.AccessController.doPrivileged(
            new java.security.PrivilegedExceptionAction<Loader>() {
            public Loader run() throws IOException {
                String file = url.getFile();
                if (file != null && file.endsWith("/")) {
                    if ("file".equals(url.getProtocol())) {
                        return new FileLoader(url);
                    } else {
                        return new Loader(url);
                    }
                } else {
                    return new JarLoader(url, jarHandler, lmap);
                }
            }
        });
    } catch (java.security.PrivilegedActionException pae) {
        throw (IOException)pae.getException();
    }
}
 
Example 26
Project: lams   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(){
            public Object run() throws IllegalAccessException, InvocationTargetException{
                return method.invoke(context,  params);
            }
        });
    } else {
        return method.invoke(context, params);
    }        
}
 
Example 27
Project: openjdk-jdk10   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<>() {
                    public Void run() throws IOException {
                        plainConnect0();
                        return null;
                    }
                }, null, p
            );
        } catch (PrivilegedActionException e) {
                throw (IOException) e.getException();
        }
    } else {
        // run without additional permission
        plainConnect0();
    }
}
 
Example 28
Project: elasticsearch_my   File: TikaImpl.java   View source code 6 votes vote down vote up
/**
 * parses with tika, throwing any exception hit while parsing the document
 */
// only package private for testing!
static String parse(final byte content[], final Metadata metadata, final int limit) throws TikaException, IOException {
    // check that its not unprivileged code like a script
    SpecialPermission.check();

    try {
        return AccessController.doPrivileged((PrivilegedExceptionAction<String>)
            () -> TIKA_INSTANCE.parseToString(new ByteArrayInputStream(content), metadata, limit), RESTRICTED_CONTEXT);
    } catch (PrivilegedActionException e) {
        // checked exception from tika: unbox it
        Throwable cause = e.getCause();
        if (cause instanceof TikaException) {
            throw (TikaException) cause;
        } else if (cause instanceof IOException) {
            throw (IOException) cause;
        } else {
            throw new AssertionError(cause);
        }
    }
}
 
Example 29
Project: OpenJSharp   File: DataTransferer.java   View source code 6 votes vote down vote up
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 30
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 31
Project: hadoop   File: HttpFSFileSystem.java   View source code 6 votes vote down vote up
public long renewDelegationToken(final Token<?> token) throws IOException {
  try {
    return UserGroupInformation.getCurrentUser().doAs(
        new PrivilegedExceptionAction<Long>() {
          @Override
          public Long run() throws Exception {
            return authURL.renewDelegationToken(uri.toURL(), authToken);
          }
        }
    );
  } catch (Exception ex) {
    if (ex instanceof IOException) {
      throw (IOException) ex;
    } else {
      throw new IOException(ex);
    }
  }
}
 
Example 32
Project: ditb   File: TestVisibilityLabels.java   View source code 6 votes vote down vote up
public static void addLabels() throws Exception {
  PrivilegedExceptionAction<VisibilityLabelsResponse> action =
      new PrivilegedExceptionAction<VisibilityLabelsResponse>() {
    public VisibilityLabelsResponse run() throws Exception {
      String[] labels = { SECRET, TOPSECRET, CONFIDENTIAL, PUBLIC, PRIVATE, COPYRIGHT, ACCENT,
          UNICODE_VIS_TAG, UC1, UC2 };
      try (Connection conn = ConnectionFactory.createConnection(conf)) {
        VisibilityClient.addLabels(conn, labels);
      } catch (Throwable t) {
        throw new IOException(t);
      }
      return null;
    }
  };
  SUPERUSER.runAs(action);
}
 
Example 33
Project: hadoop   File: TestKMS.java   View source code 6 votes vote down vote up
private <T> T doAs(String user, final PrivilegedExceptionAction<T> action)
    throws Exception {
  Set<Principal> principals = new HashSet<Principal>();
  principals.add(new KerberosPrincipal(user));

  //client login
  Subject subject = new Subject(false, principals,
      new HashSet<Object>(), new HashSet<Object>());
  LoginContext loginContext = new LoginContext("", subject, null,
      KerberosConfiguration.createClientConfig(user, keytab));
  try {
    loginContext.login();
    subject = loginContext.getSubject();
    UserGroupInformation ugi =
        UserGroupInformation.getUGIFromSubject(subject);
    return ugi.doAs(action);
  } finally {
    loginContext.logout();
  }
}
 
Example 34
Project: hadoop   File: TestClientRMTokens.java   View source code 6 votes vote down vote up
private long renewDelegationToken(final UserGroupInformation loggedInUser,
    final ApplicationClientProtocol clientRMService,
    final org.apache.hadoop.yarn.api.records.Token dToken)
    throws IOException, InterruptedException {
  long nextExpTime = loggedInUser.doAs(new PrivilegedExceptionAction<Long>() {
    @Override
    public Long run() throws YarnException, IOException {
      RenewDelegationTokenRequest request = Records
          .newRecord(RenewDelegationTokenRequest.class);
      request.setDelegationToken(dToken);
      return clientRMService.renewDelegationToken(request)
          .getNextExpirationTime();
    }
  });
  return nextExpTime;
}
 
Example 35
Project: ditb   File: Compactor.java   View source code 6 votes vote down vote up
/**
 * Calls coprocessor, if any, to create scanners - after normal scanner creation.
 *
 * @param request  Compaction request.
 * @param scanType Scan type.
 * @param scanner  The default scanner created for compaction.
 * @return Scanner scanner to use (usually the default); null if compaction should not proceed.
 */
protected InternalScanner postCreateCoprocScanner(final CompactionRequest request,
    final ScanType scanType, final InternalScanner scanner, User user) throws IOException {
  if (store.getCoprocessorHost() == null) return scanner;
  if (user == null) {
    return store.getCoprocessorHost().preCompact(store, scanner, scanType, request);
  } else {
    try {
      return user.getUGI().doAs(new PrivilegedExceptionAction<InternalScanner>() {
        @Override public InternalScanner run() throws Exception {
          return store.getCoprocessorHost().preCompact(store, scanner, scanType, request);
        }
      });
    } catch (InterruptedException ie) {
      InterruptedIOException iioe = new InterruptedIOException();
      iioe.initCause(ie);
      throw iioe;
    }
  }
}
 
Example 36
Project: hadoop   File: JobClient.java   View source code 6 votes vote down vote up
/**
 * Get status information about the Map-Reduce cluster.
 *  
 * @param  detailed if true then get a detailed status including the
 *         tracker names
 * @return the status information about the Map-Reduce cluster as an object
 *         of {@link ClusterStatus}.
 * @throws IOException
 */
public ClusterStatus getClusterStatus(boolean detailed) throws IOException {
  try {
    return clientUgi.doAs(new PrivilegedExceptionAction<ClusterStatus>() {
      public ClusterStatus run() throws IOException, InterruptedException {
      ClusterMetrics metrics = cluster.getClusterStatus();
      return new ClusterStatus(arrayToStringList(cluster.getActiveTaskTrackers()),
        arrayToBlackListInfo(cluster.getBlackListedTaskTrackers()),
        cluster.getTaskTrackerExpiryInterval(), metrics.getOccupiedMapSlots(),
        metrics.getOccupiedReduceSlots(), metrics.getMapSlotCapacity(),
        metrics.getReduceSlotCapacity(), 
        cluster.getJobTrackerStatus());
      }
    });
  } catch (InterruptedException ie) {
    throw new IOException(ie);
  }
}
 
Example 37
Project: OpenJSharp   File: AtomicLongFieldUpdater.java   View source code 5 votes vote down vote up
LockedUpdater(final Class<T> tclass, final String fieldName,
              final Class<?> caller) {
    Field field = null;
    int modifiers = 0;
    try {
        field = AccessController.doPrivileged(
            new PrivilegedExceptionAction<Field>() {
                public Field run() throws NoSuchFieldException {
                    return tclass.getDeclaredField(fieldName);
                }
            });
        modifiers = field.getModifiers();
        sun.reflect.misc.ReflectUtil.ensureMemberAccess(
            caller, tclass, null, modifiers);
        ClassLoader cl = tclass.getClassLoader();
        ClassLoader ccl = caller.getClassLoader();
        if ((ccl != null) && (ccl != cl) &&
            ((cl == null) || !isAncestor(cl, ccl))) {
          sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass);
        }
    } catch (PrivilegedActionException pae) {
        throw new RuntimeException(pae.getException());
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }

    Class<?> fieldt = field.getType();
    if (fieldt != long.class)
        throw new IllegalArgumentException("Must be long type");

    if (!Modifier.isVolatile(modifiers))
        throw new IllegalArgumentException("Must be volatile type");

    this.cclass = (Modifier.isProtected(modifiers) &&
                   caller != tclass) ? caller : null;
    this.tclass = tclass;
    offset = unsafe.objectFieldOffset(field);
}
 
Example 38
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 39
Project: hadoop-oss   File: ZKFailoverController.java   View source code 5 votes vote down vote up
/**
 * Coordinate a graceful failover to this node.
 * @throws ServiceFailedException if the node fails to become active
 * @throws IOException some other error occurs
 */
void gracefulFailoverToYou() throws ServiceFailedException, IOException {
  try {
    UserGroupInformation.getLoginUser().doAs(new PrivilegedExceptionAction<Void>() {
      @Override
      public Void run() throws Exception {
        doGracefulFailover();
        return null;
      }
      
    });
  } catch (InterruptedException e) {
    throw new IOException(e);
  }
}
 
Example 40
Project: hadoop   File: TimelineClientImpl.java   View source code 5 votes vote down vote up
private ClientResponse doPosting(final Object obj, final String path)
    throws IOException, YarnException {
  ClientResponse resp;
  try {
    resp = authUgi.doAs(new PrivilegedExceptionAction<ClientResponse>() {
      @Override
      public ClientResponse run() throws Exception {
        return doPostingObject(obj, path);
      }
    });
  } catch (UndeclaredThrowableException e) {
      throw new IOException(e.getCause());
  } catch (InterruptedException ie) {
    throw new IOException(ie);
  }
  if (resp == null ||
      resp.getClientResponseStatus() != ClientResponse.Status.OK) {
    String msg =
        "Failed to get the response from the timeline server.";
    LOG.error(msg);
    if (LOG.isDebugEnabled() && resp != null) {
      String output = resp.getEntity(String.class);
      LOG.debug("HTTP error code: " + resp.getStatus()
          + " Server response : \n" + output);
    }
    throw new YarnException(msg);
  }
  return resp;
}