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:org.apache.hadoop.crypto.key.kms.KMSClientProvider.java

@Override
public long renewDelegationToken(final Token<?> dToken) throws IOException {
    try {//from  w ww  . ja v a  2  s . c  om
        final String doAsUser = getDoAsUser();
        final DelegationTokenAuthenticatedURL.Token token = generateDelegationToken(dToken);
        final URL url = createURL(null, null, null, null);
        LOG.debug("Renewing delegation token {} with url:{}, as:{}", token, url, doAsUser);
        final DelegationTokenAuthenticatedURL authUrl = new DelegationTokenAuthenticatedURL(configurator);
        return getActualUgi().doAs(new PrivilegedExceptionAction<Long>() {
            @Override
            public Long run() throws Exception {
                return authUrl.renewDelegationToken(url, token, doAsUser);
            }
        });
    } catch (Exception ex) {
        if (ex instanceof IOException) {
            throw (IOException) ex;
        } else {
            throw new IOException(ex);
        }
    }
}

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

@Override
public Void cancelDelegationToken(final Token<?> dToken) throws IOException {
    try {/* w  ww  . jav a 2 s .c  o m*/
        final String doAsUser = getDoAsUser();
        final DelegationTokenAuthenticatedURL.Token token = generateDelegationToken(dToken);
        return getActualUgi().doAs(new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws Exception {
                final URL url = createURL(null, null, null, null);
                LOG.debug("Cancelling delegation token {} with url:{}, as:{}", dToken, url, doAsUser);
                final DelegationTokenAuthenticatedURL authUrl = new DelegationTokenAuthenticatedURL(
                        configurator);
                authUrl.cancelDelegationToken(url, token, doAsUser);
                return null;
            }
        });
    } catch (Exception ex) {
        if (ex instanceof IOException) {
            throw (IOException) ex;
        } else {
            throw new IOException(ex);
        }
    }
}

From source file:com.cloudera.beeswax.BeeswaxServiceImpl.java

/**
 * Get the query plan for a query./*from  ww  w.  j a v  a  2  s.c o m*/
 */
@Override
public QueryExplanation explain(final Query query) throws BeeswaxException, TException {
    final String contextName = UUID.randomUUID().toString();
    LogContext lc = LogContext.registerCurrentThread(contextName);
    final RunningQueryState state = new RunningQueryState(query, lc);
    try {
        return doWithState(state, new PrivilegedExceptionAction<QueryExplanation>() {
            public QueryExplanation run() throws Exception {
                state.initialize();
                QueryExplanation exp;
                // All kinds of things can go wrong when we compile it. So catch all.
                try {
                    exp = state.explain();
                } catch (BeeswaxException perr) {
                    throw perr;
                } catch (Throwable t) {
                    throw new BeeswaxException(t.toString(), contextName, null);
                }
                // On success, we remove the LogContext
                LogContext.destroyContext(contextName);
                return exp;
            }
        });
    } catch (BeeswaxException e) {
        throw e;
    }
}

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

@Test
public void testVisibilityLabelsWithDeleteFamilyWithPutsReAppearing() throws Exception {
    final TableName tableName = TableName.valueOf(TEST_NAME.getMethodName());
    Admin hBaseAdmin = TEST_UTIL.getAdmin();
    HColumnDescriptor colDesc = new HColumnDescriptor(fam);
    colDesc.setMaxVersions(5);//from  w w  w  . j  av a 2  s .c  om
    HTableDescriptor desc = new HTableDescriptor(tableName);
    desc.addFamily(colDesc);
    hBaseAdmin.createTable(desc);
    try (Table table = TEST_UTIL.getConnection().getTable(tableName)) {
        Put put = new Put(Bytes.toBytes("row1"));
        put.addColumn(fam, qual, value);
        put.setCellVisibility(new CellVisibility(CONFIDENTIAL));
        table.put(put);
        put = new Put(Bytes.toBytes("row1"));
        put.addColumn(fam, qual, value);
        put.setCellVisibility(new CellVisibility(SECRET));
        table.put(put);
        TEST_UTIL.getAdmin().flush(tableName);
        PrivilegedExceptionAction<Void> actiona = new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws Exception {
                try (Connection connection = ConnectionFactory.createConnection(conf);
                        Table table = connection.getTable(tableName)) {
                    Delete d = new Delete(row1);
                    d.setCellVisibility(new CellVisibility(CONFIDENTIAL));
                    d.addFamily(fam);
                    table.delete(d);
                } catch (Throwable t) {
                    throw new IOException(t);
                }
                return null;
            }
        };
        SUPERUSER.runAs(actiona);
        Scan s = new Scan();
        s.setMaxVersions(5);
        s.setAuthorizations(new Authorizations(SECRET));
        ResultScanner scanner = table.getScanner(s);
        Result[] next = scanner.next(3);
        assertEquals(next.length, 1);
        put = new Put(Bytes.toBytes("row1"));
        put.addColumn(fam, qual, value1);
        put.setCellVisibility(new CellVisibility(CONFIDENTIAL));
        table.put(put);
        actiona = new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws Exception {
                try (Connection connection = ConnectionFactory.createConnection(conf);
                        Table table = connection.getTable(tableName)) {
                    Delete d = new Delete(row1);
                    d.setCellVisibility(new CellVisibility(SECRET));
                    d.addFamily(fam);
                    table.delete(d);
                } catch (Throwable t) {
                    throw new IOException(t);
                }
                return null;
            }
        };
        SUPERUSER.runAs(actiona);
        s = new Scan();
        s.setMaxVersions(5);
        s.setAuthorizations(new Authorizations(CONFIDENTIAL));
        scanner = table.getScanner(s);
        next = scanner.next(3);
        assertEquals(next.length, 1);
        s = new Scan();
        s.setMaxVersions(5);
        s.setAuthorizations(new Authorizations(SECRET));
        scanner = table.getScanner(s);
        Result[] next1 = scanner.next(3);
        assertEquals(next1.length, 0);
    }
}

From source file:io.hops.security.TestUsersGroups.java

public void testMultiUserMultiGrp(int cacheTime, int cacheSize) throws Exception {
    Configuration conf = new HdfsConfiguration();
    final int NUM_NAMENODES = 2;

    String userName = UserGroupInformation.getCurrentUser().getShortUserName();
    conf.set(String.format("hadoop.proxyuser.%s.hosts", userName), "*");
    conf.set(String.format("hadoop.proxyuser.%s.users", userName), "*");
    conf.set(String.format("hadoop.proxyuser.%s.groups", userName), "*");
    conf.set(CommonConfigurationKeys.HOPS_UG_CACHE_SECS, Integer.toString(cacheTime));
    conf.set(CommonConfigurationKeys.HOPS_UG_CACHE_SIZE, Integer.toString(cacheSize));

    final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf)
            .nnTopology(MiniDFSNNTopology.simpleHOPSTopology(NUM_NAMENODES)).numDataNodes(1).format(true)
            .build();/* w ww  .  j  av a  2s.c o m*/
    cluster.waitActive();

    try {

        DistributedFileSystem superFS = cluster.getFileSystem(rand.nextInt(NUM_NAMENODES));

        int numUsers = 10; //>=1
        DistributedFileSystem[] fss = new DistributedFileSystem[numUsers];
        Path[] files = new Path[numUsers];

        for (int i = 0; i < numUsers; i++) {
            superFS.addUser("user" + i);
            LOG.info("Adding User " + i);
            superFS.addGroup("group" + i);
            LOG.info("Adding Group " + i);
        }

        //add all users to all groups
        for (int i = 0; i < numUsers; i++) {
            for (int j = 0; j < numUsers; j++) {
                superFS.addUserToGroup("user" + i, "group" + j);
                LOG.info("Adding User " + i + " to Group " + j);
            }
        }

        // create file system objects
        for (int i = 0; i < numUsers; i++) {
            UserGroupInformation ugi = UserGroupInformation.createRemoteUser("user" + i);

            DistributedFileSystem fs = (DistributedFileSystem) ugi
                    .doAs(new PrivilegedExceptionAction<FileSystem>() {
                        @Override
                        public FileSystem run() throws Exception {
                            return cluster.getFileSystem(rand.nextInt(NUM_NAMENODES));
                        }
                    });
            fss[i] = fs;
        }

        Path path = new Path("/Projects");
        superFS.mkdirs(path);
        superFS.setPermission(path, new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.ALL));

        path = new Path("/Projects/dataset");
        fss[0].mkdirs(path);
        fss[0].setPermission(path, new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.NONE));
        fss[0].setOwner(path, "user0", "group0");

        for (int i = 0; i < numUsers; i++) {
            path = new Path("/Projects/dataset/user" + i);
            fss[i].mkdirs(path);
            fss[i].setPermission(path, new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.NONE));
            fss[i].setOwner(path, "user" + i, "group" + i);
            path = new Path("/Projects/dataset/user" + i + "/file" + i);
            fss[i].create(path).close();
            fss[i].setPermission(path, new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.NONE));
            fss[i].setOwner(path, "user" + i, "group" + i);
            files[i] = path;
        }

        Thread[] threads = new Thread[numUsers];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(new Worker(fss[i], files));
            threads[i].start();
        }

        for (int i = 0; i < threads.length; i++) {
            threads[i].join();
        }

        if (fail.get()) {
            fail("Test failed no exception should have occurred during the test");
        }

    } catch (Exception e) {
        e.printStackTrace();
        fail();
    } finally {
        cluster.shutdown();
    }
}

From source file:com.cloudera.beeswax.BeeswaxServiceImpl.java

/**
 * Get the results of a query. This is non-blocking. Caller should check
 * Results.ready to determine if the results are in yet.
 *
 * @param handle  The handle from query()
 * @param fromBeginning  If true, rewind to the first row. Otherwise fetch from last position.
 * @param fetchSize  Number of rows to return with this fetch
 *//*w w  w  .j a  v a2 s .c o m*/
@Override
public Results fetch(final QueryHandle handle, final boolean fromBeginning, final int fetchSize)
        throws QueryNotFoundException, BeeswaxException {
    LogContext.unregisterCurrentThread();
    validateHandle(handle);
    LogContext.registerCurrentThread(handle.log_context);
    final RunningQueryState state = runningQueries.get(handle.id);
    try {
        return doWithState(state, new PrivilegedExceptionAction<Results>() {
            public Results run() throws Exception {
                if (state == null) {
                    throw new QueryNotFoundException();
                }
                return state.fetch(fromBeginning, fetchSize);
            }
        });
    } catch (BeeswaxException e) {
        throw e;
    }
}

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

@Override
public Token<?>[] addDelegationTokens(final String renewer, Credentials credentials) throws IOException {
    Token<?>[] tokens = null;/*ww w.ja va2 s  . co m*/
    Text dtService = getDelegationTokenService();
    Token<?> token = credentials.getToken(dtService);
    if (token == null) {
        final URL url = createURL(null, null, null, null);
        final DelegationTokenAuthenticatedURL authUrl = new DelegationTokenAuthenticatedURL(configurator);
        try {
            final String doAsUser = getDoAsUser();
            token = getActualUgi().doAs(new PrivilegedExceptionAction<Token<?>>() {
                @Override
                public Token<?> run() throws Exception {
                    // Not using the cached token here.. Creating a new token here
                    // everytime.
                    return authUrl.getDelegationToken(url, new DelegationTokenAuthenticatedURL.Token(), renewer,
                            doAsUser);
                }
            });
            if (token != null) {
                credentials.addToken(token.getService(), token);
                tokens = new Token<?>[] { token };
            } else {
                throw new IOException("Got NULL as delegation token");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } catch (Exception e) {
            throw new IOException(e);
        }
    }
    return tokens;
}

From source file:ApplicationMaster.java

private void renameScriptFile(final Path renamedScriptPath) throws IOException, InterruptedException {
    appSubmitterUgi.doAs(new PrivilegedExceptionAction<Void>() {
        @Override// w w w  .j  a  v  a2s. c  o m
        public Void run() throws IOException {
            FileSystem fs = renamedScriptPath.getFileSystem(conf);
            fs.rename(new Path(scriptPath), renamedScriptPath);
            return null;
        }
    });
    LOG.info("User " + appSubmitterUgi.getUserName() + " added suffix(.sh/.bat) to script file as "
            + renamedScriptPath);
}

From source file:com.cloudera.beeswax.BeeswaxServiceImpl.java

/**
 * Get the results metadata// w w  w . j  av  a  2 s . c  om
 *
 * @param handle
 */
@Override
public ResultsMetadata get_results_metadata(final QueryHandle handle) throws QueryNotFoundException {
    LogContext.unregisterCurrentThread();
    validateHandle(handle);
    LogContext.registerCurrentThread(handle.log_context);
    final RunningQueryState state = runningQueries.get(handle.id);
    try {
        return doWithState(state, new PrivilegedExceptionAction<ResultsMetadata>() {
            public ResultsMetadata run() throws Exception {
                if (state == null) {
                    throw new QueryNotFoundException();
                }
                return state.getResultMetadata();
            }
        });
    } catch (BeeswaxException e) {
        LOG.error("Caught BeeswaxException.", e);
        throw new QueryNotFoundException();
    }
}

From source file:org.apache.hadoop.hive.shims.Hadoop23Shims.java

@Override
public boolean runDistCpAs(List<Path> srcPaths, Path dst, Configuration conf, String doAsUser)
        throws IOException {
    UserGroupInformation proxyUser = UserGroupInformation.createProxyUser(doAsUser,
            UserGroupInformation.getLoginUser());
    try {//from   ww  w .j ava 2 s  .  co  m
        return proxyUser.doAs(new PrivilegedExceptionAction<Boolean>() {
            @Override
            public Boolean run() throws Exception {
                return runDistCp(srcPaths, dst, conf);
            }
        });
    } catch (InterruptedException e) {
        throw new IOException(e);
    }
}