Example usage for java.security PrivilegedExceptionAction PrivilegedExceptionAction

List of usage examples for java.security PrivilegedExceptionAction PrivilegedExceptionAction

Introduction

In this page you can find the example usage for java.security PrivilegedExceptionAction PrivilegedExceptionAction.

Prototype

PrivilegedExceptionAction

Source Link

Usage

From source file:it.staiger.jmeter.protocol.http.sampler.HTTPHC4DynamicFilePost.java

/**
 * Execute request either as is or under PrivilegedAction 
 * if a Subject is available for url/*from   ww  w. j  a  v a2  s .  c o m*/
 * @param httpClient
 * @param httpRequest
 * @param localContext
 * @param url
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 */
private HttpResponse executeRequest(final HttpClient httpClient, final HttpRequestBase httpRequest,
        final HttpContext localContext, final URL url) throws IOException, ClientProtocolException {
    AuthManager authManager = getAuthManager();
    if (authManager != null) {
        Subject subject = authManager.getSubjectForUrl(url);
        if (subject != null) {
            try {
                return Subject.doAs(subject, new PrivilegedExceptionAction<HttpResponse>() {

                    @Override
                    public HttpResponse run() throws Exception {
                        return httpClient.execute(httpRequest, localContext);
                    }
                });
            } catch (PrivilegedActionException e) {
                log.error("Can't execute httpRequest with subject:" + subject, e);
                throw new RuntimeException("Can't execute httpRequest with subject:" + subject, e);
            }
        }
    }
    return httpClient.execute(httpRequest, localContext);
}

From source file:org.apache.axis2.jaxws.server.dispatcher.JavaBeanDispatcher.java

/**
 * @return ClassLoader//from   w w w.jav  a2s  .c o m
 */
private static ClassLoader getContextClassLoader() {
    // NOTE: This method must remain private because it uses AccessController
    ClassLoader cl = null;
    try {
        cl = (ClassLoader) org.apache.axis2.java.security.AccessController
                .doPrivileged(new PrivilegedExceptionAction() {
                    public Object run() throws ClassNotFoundException {
                        return Thread.currentThread().getContextClassLoader();
                    }
                });
    } catch (PrivilegedActionException e) {
        // The privileged method will throw a PriviledgedActionException which
        // contains the actual exception.
        if (log.isDebugEnabled()) {
            log.debug("Exception thrown from AccessController: " + e);
        }
        Exception wrappedE = e.getException();
        if (wrappedE instanceof RuntimeException) {
            throw (RuntimeException) wrappedE;
        } else {
            throw new RuntimeException(wrappedE);
        }
    }

    return cl;
}

From source file:org.apache.hadoop.hive.common.FileUtils.java

/**
 * Perform a check to determine if the user is able to access the file passed in.
 * If the user name passed in is different from the current user, this method will
 * attempt to do impersonate the user to do the check; the current user should be
 * able to create proxy users in this case.
 * @param fs   FileSystem of the path to check
 * @param stat FileStatus representing the file
 * @param action FsAction that will be checked
 * @param user User name of the user that will be checked for access.  If the user name
 *             is null or the same as the current user, no user impersonation will be done
 *             and the check will be done as the current user. Otherwise the file access
 *             check will be performed within a doAs() block to use the access privileges
 *             of this user. In this case the user must be configured to impersonate other
 *             users, otherwise this check will fail with error.
 * @param children List of children to be collected. If this is null, no children are collected.
 *        To be set only if this is a directory
 * @throws IOException//ww  w.  j  a  va2 s.c o  m
 * @throws AccessControlException
 * @throws InterruptedException
 * @throws Exception
 */
public static void checkFileAccessWithImpersonation(final FileSystem fs, final FileStatus stat,
        final FsAction action, final String user, final List<FileStatus> children)
        throws IOException, AccessControlException, InterruptedException, Exception {
    UserGroupInformation ugi = Utils.getUGI();
    String currentUser = ugi.getShortUserName();

    if (user == null || currentUser.equals(user)) {
        // No need to impersonate user, do the checks as the currently configured user.
        ShimLoader.getHadoopShims().checkFileAccess(fs, stat, action);
        addChildren(fs, stat.getPath(), children);
        return;
    }

    // Otherwise, try user impersonation. Current user must be configured to do user impersonation.
    UserGroupInformation proxyUser = UserGroupInformation.createProxyUser(user,
            UserGroupInformation.getLoginUser());
    try {
        proxyUser.doAs(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                FileSystem fsAsUser = FileSystem.get(fs.getUri(), fs.getConf());
                ShimLoader.getHadoopShims().checkFileAccess(fsAsUser, stat, action);
                addChildren(fsAsUser, stat.getPath(), children);
                return null;
            }
        });
    } finally {
        FileSystem.closeAllForUGI(proxyUser);
    }
}

From source file:org.apache.hadoop.crypto.key.kms.server.KMS.java

@GET
@Path(KMSRESTConstants.KEY_RESOURCE + "/{name:.*}/" + KMSRESTConstants.CURRENT_VERSION_SUB_RESOURCE)
@Produces(MediaType.APPLICATION_JSON)/*from  ww  w .j av  a  2s  . c o  m*/
public Response getCurrentVersion(@PathParam("name") final String name) throws Exception {
    try {
        LOG.trace("Entering getCurrentVersion method.");
        UserGroupInformation user = HttpUserGroupInformation.get();
        KMSClientProvider.checkNotEmpty(name, "name");
        KMSWebApp.getKeyCallsMeter().mark();
        assertAccess(KMSACLs.Type.GET, user, KMSOp.GET_CURRENT_KEY, name);
        LOG.debug("Getting key version for key with name {}.", name);

        KeyVersion keyVersion = user.doAs(new PrivilegedExceptionAction<KeyVersion>() {
            @Override
            public KeyVersion run() throws Exception {
                return provider.getCurrentKey(name);
            }
        });

        Object json = KMSServerJSONUtils.toJSON(keyVersion);
        kmsAudit.ok(user, KMSOp.GET_CURRENT_KEY, name, "");
        LOG.trace("Exiting getCurrentVersion method.");
        return Response.ok().type(MediaType.APPLICATION_JSON).entity(json).build();
    } catch (Exception e) {
        LOG.debug("Exception in getCurrentVersion.", e);
        throw e;
    }
}

From source file:org.apache.hadoop.ipc.TestSaslRPC.java

public void testDigestAuthMethod(boolean useIp) throws Exception {
    setTokenServiceUseIp(useIp);/*from  w w w.  j a  v a 2 s .com*/

    TestTokenSecretManager sm = new TestTokenSecretManager();
    Server server = RPC.getServer(new TestSaslImpl(), ADDRESS, 0, 5, true, conf, sm);
    server.start();

    final UserGroupInformation current = UserGroupInformation.getCurrentUser();
    final InetSocketAddress addr = NetUtils.getConnectAddress(server);
    TestTokenIdentifier tokenId = new TestTokenIdentifier(new Text(current.getUserName()));
    Token<TestTokenIdentifier> token = new Token<TestTokenIdentifier>(tokenId, sm);
    SecurityUtil.setTokenService(token, addr);
    LOG.info("Service IP address for token is " + token.getService());

    InetSocketAddress tokenAddr = SecurityUtil.getTokenServiceAddr(token);
    String expectedHost, gotHost;
    if (useIp) {
        expectedHost = addr.getAddress().getHostAddress();
        gotHost = tokenAddr.getAddress().getHostAddress();
    } else {
        gotHost = tokenAddr.getHostName();
        expectedHost = ADDRESS;
    }
    Assert.assertEquals(expectedHost, gotHost);
    Assert.assertEquals(expectedHost + ":" + addr.getPort(), token.getService().toString());

    current.addToken(token);

    current.doAs(new PrivilegedExceptionAction<Object>() {
        public Object run() throws IOException {
            TestSaslProtocol proxy = null;
            try {
                proxy = (TestSaslProtocol) RPC.getProxy(TestSaslProtocol.class, TestSaslProtocol.versionID,
                        addr, conf);
                Assert.assertEquals(AuthenticationMethod.TOKEN, proxy.getAuthMethod());
            } finally {
                if (proxy != null) {
                    RPC.stopProxy(proxy);
                }
            }
            return null;
        }
    });
    server.stop();
}

From source file:org.apache.hadoop.hbase.security.visibility.TestVisibilityLabelsReplication.java

protected void verifyGet(final byte[] row, final String visString, final int expected,
        final boolean nullExpected, final String... auths) throws IOException, InterruptedException {
    PrivilegedExceptionAction<Void> scanAction = new PrivilegedExceptionAction<Void>() {
        public Void run() throws Exception {
            try (Connection connection = ConnectionFactory.createConnection(conf1);
                    Table table2 = connection.getTable(TABLE_NAME)) {
                CellScanner cellScanner;
                Cell current;/*ww  w.  ja  va2s  .  c o m*/
                Get get = new Get(row);
                get.setAuthorizations(new Authorizations(auths));
                Result result = table2.get(get);
                cellScanner = result.cellScanner();
                boolean advance = cellScanner.advance();
                if (nullExpected) {
                    assertTrue(!advance);
                    return null;
                }
                current = cellScanner.current();
                assertArrayEquals(CellUtil.cloneRow(current), row);
                for (Tag tag : TestCoprocessorForTagsAtSink.tags) {
                    LOG.info("The tag type is " + tag.getType());
                }
                assertEquals(expected, TestCoprocessorForTagsAtSink.tags.size());
                Tag tag = TestCoprocessorForTagsAtSink.tags.get(1);
                if (tag.getType() != NON_VIS_TAG_TYPE) {
                    assertEquals(TagType.VISIBILITY_EXP_SERIALIZATION_FORMAT_TAG_TYPE, tag.getType());
                }
                tag = TestCoprocessorForTagsAtSink.tags.get(0);
                boolean foundNonVisTag = false;
                for (Tag t : TestCoprocessorForTagsAtSink.tags) {
                    if (t.getType() == NON_VIS_TAG_TYPE) {
                        assertEquals(TEMP, Bytes.toString(t.getValue()));
                        foundNonVisTag = true;
                        break;
                    }
                }
                doAssert(row, visString);
                assertTrue(foundNonVisTag);
                return null;
            }
        }
    };
    USER1.runAs(scanAction);
}

From source file:com.buaa.cfs.fs.FileSystem.java

/**
 * Returns the FileSystem for this URI's scheme and authority and the passed user. Internally invokes {@link
 * #newInstance(URI, Configuration)}//from  w w w.  j  a v  a2s .c  o  m
 *
 * @param uri  of the filesystem
 * @param conf the configuration to use
 * @param user to perform the get as
 *
 * @return filesystem instance
 *
 * @throws IOException
 * @throws InterruptedException
 */
public static FileSystem newInstance(final URI uri, final Configuration conf, final String user)
        throws IOException, InterruptedException {
    String ticketCachePath = conf.get(CommonConfigurationKeys.KERBEROS_TICKET_CACHE_PATH);
    UserGroupInformation ugi = UserGroupInformation.getBestUGI(ticketCachePath, user);
    return ugi.doAs(new PrivilegedExceptionAction<FileSystem>() {
        @Override
        public FileSystem run() throws IOException {
            return newInstance(uri, conf);
        }
    });
}

From source file:org.apache.axiom.om.util.StAXUtils.java

public static XMLStreamWriter createXMLStreamWriter(StAXWriterConfiguration configuration,
        final OutputStream out, final String encoding) throws XMLStreamException {
    final XMLOutputFactory outputFactory = getXMLOutputFactory(configuration);
    try {/*from  www .  ja  v  a2s  .  co m*/
        XMLStreamWriter writer = (XMLStreamWriter) AccessController
                .doPrivileged(new PrivilegedExceptionAction() {
                    public Object run() throws XMLStreamException {
                        return outputFactory.createXMLStreamWriter(out, encoding);
                    }
                });

        if (isDebugEnabled) {
            log.debug("XMLStreamWriter is " + writer.getClass().getName());
        }
        return writer;
    } catch (PrivilegedActionException pae) {
        throw (XMLStreamException) pae.getException();
    }
}

From source file:org.apache.hadoop.hbase.security.token.TestTokenAuthentication.java

@Test
public void testTokenAuthentication() throws Exception {
    UserGroupInformation testuser = UserGroupInformation.createUserForTesting("testuser",
            new String[] { "testgroup" });

    testuser.setAuthenticationMethod(UserGroupInformation.AuthenticationMethod.TOKEN);
    final Configuration conf = TEST_UTIL.getConfiguration();
    UserGroupInformation.setConfiguration(conf);
    Token<AuthenticationTokenIdentifier> token = secretManager.generateToken("testuser");
    LOG.debug("Got token: " + token.toString());
    testuser.addToken(token);/* w  w w  . j  av a2s .co  m*/

    // verify the server authenticates us as this token user
    testuser.doAs(new PrivilegedExceptionAction<Object>() {
        public Object run() throws Exception {
            Configuration c = server.getConfiguration();
            RpcClient rpcClient = new RpcClient(c, clusterId.toString());
            ServerName sn = ServerName.valueOf(server.getAddress().getHostName(), server.getAddress().getPort(),
                    System.currentTimeMillis());
            try {
                BlockingRpcChannel channel = rpcClient.createBlockingRpcChannel(sn, User.getCurrent(),
                        HConstants.DEFAULT_HBASE_RPC_TIMEOUT);
                AuthenticationProtos.AuthenticationService.BlockingInterface stub = AuthenticationProtos.AuthenticationService
                        .newBlockingStub(channel);
                AuthenticationProtos.WhoAmIResponse response = stub.whoAmI(null,
                        AuthenticationProtos.WhoAmIRequest.getDefaultInstance());
                String myname = response.getUsername();
                assertEquals("testuser", myname);
                String authMethod = response.getAuthMethod();
                assertEquals("TOKEN", authMethod);
            } finally {
                rpcClient.stop();
            }
            return null;
        }
    });
}

From source file:org.apache.axis2.jaxws.description.builder.DescriptionBuilderUtils.java

/**
 * Return the class for this name// www .  j  a  v a 2  s.c  o m
 *
 * @return Class
 */
private static Class forName(final String className, final boolean initialize, final ClassLoader classloader)
        throws ClassNotFoundException {
    Class cl = null;
    try {
        cl = (Class) AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws ClassNotFoundException {
                return Class.forName(className, initialize, classloader);
            }
        });
    } catch (PrivilegedActionException e) {
        if (log.isDebugEnabled()) {
            log.debug("Exception thrown from AccessController: " + e.getMessage(), e);
        }
        throw (ClassNotFoundException) e.getException();
    }

    return cl;
}