Java 类java.security.PrivilegedExceptionAction 实例源码

项目:openjdk-jdk10    文件:KrbCredSubKey.java   
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);
            }
        });
    }
项目:openjdk-jdk10    文件:SocksSocketImpl.java   
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();
    }
}
项目:hadoop    文件:GenerateDistCacheData.java   
@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;
}
项目:incubator-netbeans    文件:BaseFileObj.java   
@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);
    }
}
项目:openjdk-jdk10    文件:DataTransferer.java   
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());
    }
}
项目:hadoop    文件:TestContainerManagerRecovery.java   
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));
    }
  });
}
项目:hadoop-oss    文件:FileContext.java   
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);
  }
}
项目:hadoop    文件:TestClientToAMTokens.java   
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;
    }
  });
}
项目:ditb    文件:TestVisibilityLabelsWithDefaultVisLabelService.java   
@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);
}
项目:ditb    文件:TestVisibilityLabelsWithDeletes.java   
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);
}
项目:openjdk-jdk10    文件:HttpURLConnection.java   
@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();
    }
}
项目:jdk8u-jdk    文件:ArrayNotificationBuffer.java   
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);
    }
}
项目:openjdk-jdk10    文件:SocketAdaptor.java   
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;
}
项目:ditb    文件:TestCellACLWithMultipleVersions.java   
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;
    }
  });
}
项目:hadoop    文件:TestDFSPermission.java   
@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()));
  }
}
项目:openjdk-jdk10    文件:HttpURLConnection.java   
@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();
    }
}
项目:scheduling-connector-for-hadoop    文件:FSDownload.java   
@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()));
}
项目:apache-tomcat-7.0.73-with-comment    文件:PageContextImpl.java   
@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);
    }
}
项目:hadoop    文件:GridmixJob.java   
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);
  }
}
项目:jdk8u-jdk    文件:SerializedLambda.java   
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);
    }
}
项目:OpenJSharp    文件:ServerSocket.java   
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;
    }
}
项目:elasticsearch_my    文件:SocketAccess.java   
public static <T> T doPrivilegedIOException(PrivilegedExceptionAction<T> operation) throws IOException {
    SpecialPermission.check();
    try {
        return AccessController.doPrivileged(operation);
    } catch (PrivilegedActionException e) {
        throw (IOException) e.getCause();
    }
}
项目:hadoop    文件:HttpFSFileSystem.java   
/**
 * 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);
    }
  }
}
项目:hadoop    文件:TestSecureLogins.java   
@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);

}
项目:OpenJSharp    文件:URLClassPath.java   
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();
    }
}
项目:lams    文件:ApplicationContextFacade.java   
/**
 * 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);
    }        
}
项目:openjdk-jdk10    文件:HttpURLConnection.java   
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();
    }
}
项目:elasticsearch_my    文件:TikaImpl.java   
/**
 * 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);
        }
    }
}
项目:OpenJSharp    文件:DataTransferer.java   
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;
}
项目:aries-jpa    文件:TempBundleDelegatingClassLoader.java   
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;
}
项目:hadoop    文件:HttpFSFileSystem.java   
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);
    }
  }
}
项目:ditb    文件:TestVisibilityLabels.java   
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);
}
项目:hadoop    文件:TestKMS.java   
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();
  }
}
项目:hadoop    文件:TestClientRMTokens.java   
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;
}
项目:ditb    文件:Compactor.java   
/**
 * 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;
    }
  }
}
项目:hadoop    文件:JobClient.java   
/**
 * 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);
  }
}
项目:OpenJSharp    文件:AtomicLongFieldUpdater.java   
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);
}
项目:OpenJSharp    文件:SecuritySupport.java   
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();
    }
}
项目:hadoop-oss    文件:ZKFailoverController.java   
/**
 * 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);
  }
}
项目:hadoop    文件:TimelineClientImpl.java   
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;
}