微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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,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 {
  UserGroup@R_630_4045@ion ugi = UserGroup@R_630_404[email protected]();
  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 {
  UserGroup@R_630_4045@ion user = UserGroup@R_630_404[email protected](
      cid.getApplicationAttemptId().toString());
  StartContainerRequest scReq = StartContainerRequest.newInstance(
      clc,TestContainerManager.createContainerToken(cid,context.getNodeId(),user.getShortUserName(),context.getContainerTokenSecretManager(),logAggregationContext));
  final List<StartContainerRequest> scReqList =
      new ArrayList<StartContainerRequest>();
  scReqList.add(scReq);
  NMTokenIdentifier nmToken = new NMTokenIdentifier(
      cid.getApplicationAttemptId(),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(
    UserGroup@R_630_4045@ion 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 {
  UserGroup@R_630_4045@ion ugi;
  ugi = UserGroup@R_630_404[email protected]("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,UserGroup@R_630_404[email protected]().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();
                    }
                },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 = UserGroup@R_630_404[email protected]();

  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,List<String>> multiValuedParams,Path path,boolean makeQualified) throws IOException {
  if (makeQualified) {
    path = makeQualified(path);
  }
  final URL url = Httpfsutils.createURL(path,params,multiValuedParams);
  try {
    return UserGroup@R_630_404[email protected]().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 {

  UserGroup@R_630_4045@ion ugi = loginUGI(ZOOKEEPER,keytab_zk);
  RegistrySecurity.UgiInfo ugiInfo =
      new RegistrySecurity.UgiInfo(ugi);
  LOG.info("logged in as: {}",ugiInfo);
  assertTrue("security is not enabled: " + ugiInfo,UserGroup@R_630_404[email protected]ecurityEnabled());
  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;
                    }
                },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 UserGroup@R_630_404[email protected]().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,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,KerberosConfiguration.createClientConfig(user,keytab));
  try {
    loginContext.login();
    subject = loginContext.getSubject();
    UserGroup@R_630_4045@ion ugi =
        UserGroup@R_630_404[email protected](subject);
    return ugi.doAs(action);
  } finally {
    loginContext.logout();
  }
}
项目:hadoop    文件TestClientRMTokens.java   
private long renewDelegationToken(final UserGroup@R_630_4045@ion 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,request);
        }
      });
    } catch (InterruptedException ie) {
      InterruptedioException iioe = new InterruptedioException();
      iioe.initCause(ie);
      throw iioe;
    }
  }
}
项目:hadoop    文件JobClient.java   
/**
 * Get status @R_630_4045@ion about the Map-Reduce cluster.
 *  
 * @param  detailed if true then get a detailed status including the
 *         tracker names
 * @return the status @R_630_4045@ion 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,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 {
    UserGroup@R_630_404[email protected]().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;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。