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.axis2.jaxws.description.builder.DescriptionBuilderUtils.java

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

    return cl;
}

From source file:org.apache.bsf.BSFManager.java

/**
 * Evaluate the given expression of the given language and return the
 * resulting value.//from  w  w w.  java2  s  . co m
 *
 * @param lang language identifier
 * @param source (context info) the source of this expression
 (e.g., filename)
 * @param lineNo (context info) the line number in source for expr
 * @param columnNo (context info) the column number in source for expr
 * @param expr the expression to evaluate
 *
 * @exception BSFException if anything goes wrong while running the script
 */
public Object eval(String lang, String source, int lineNo, int columnNo, Object expr) throws BSFException {
    logger.debug("BSFManager:eval");

    final BSFEngine e = loadScriptingEngine(lang);
    final String sourcef = source;
    final int lineNof = lineNo, columnNof = columnNo;
    final Object exprf = expr;
    Object result = null;

    try {
        final Object resultf = AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws Exception {
                return e.eval(sourcef, lineNof, columnNof, exprf);
            }
        });
        result = resultf;
    } catch (PrivilegedActionException prive) {

        logger.error("Exception: ", prive);
        throw (BSFException) prive.getException();
    }

    return result;
}

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

public static XMLStreamWriter createXMLStreamWriter(StAXWriterConfiguration configuration, final Writer out)
        throws XMLStreamException {
    final XMLOutputFactory outputFactory = getXMLOutputFactory(configuration);
    try {//from  ww  w  .jav a2  s  .  c o  m
        XMLStreamWriter writer = (XMLStreamWriter) AccessController
                .doPrivileged(new PrivilegedExceptionAction() {
                    public Object run() throws XMLStreamException {
                        return outputFactory.createXMLStreamWriter(out);
                    }
                });
        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.ipc.BlockingRpcConnection.java

/**
 * If multiple clients with the same principal try to connect to the same server at the same time,
 * the server assumes a replay attack is in progress. This is a feature of kerberos. In order to
 * work around this, what is done is that the client backs off randomly and tries to initiate the
 * connection again. The other problem is to do with ticket expiry. To handle that, a relogin is
 * attempted.//from  ww  w.jav a2s.  c  om
 * <p>
 * The retry logic is governed by the {@link #shouldAuthenticateOverKrb} method. In case when the
 * user doesn't have valid credentials, we don't need to retry (from cache or ticket). In such
 * cases, it is prudent to throw a runtime exception when we receive a SaslException from the
 * underlying authentication implementation, so there is no retry from other high level (for eg,
 * HCM or HBaseAdmin).
 * </p>
 */
private void handleSaslConnectionFailure(final int currRetries, final int maxRetries, final Exception ex,
        final UserGroupInformation user) throws IOException, InterruptedException {
    closeSocket();
    user.doAs(new PrivilegedExceptionAction<Object>() {
        @Override
        public Object run() throws IOException, InterruptedException {
            if (shouldAuthenticateOverKrb()) {
                if (currRetries < maxRetries) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Exception encountered while connecting to " + "the server : " + ex);
                    }
                    // try re-login
                    relogin();
                    disposeSasl();
                    // have granularity of milliseconds
                    // we are sleeping with the Connection lock held but since this
                    // connection instance is being used for connecting to the server
                    // in question, it is okay
                    Thread.sleep(ThreadLocalRandom.current().nextInt(reloginMaxBackoff) + 1);
                    return null;
                } else {
                    String msg = "Couldn't setup connection for "
                            + UserGroupInformation.getLoginUser().getUserName() + " to " + serverPrincipal;
                    LOG.warn(msg, ex);
                    throw (IOException) new IOException(msg).initCause(ex);
                }
            } else {
                LOG.warn("Exception encountered while connecting to " + "the server : " + ex);
            }
            if (ex instanceof RemoteException) {
                throw (RemoteException) ex;
            }
            if (ex instanceof SaslException) {
                String msg = "SASL authentication failed."
                        + " The most likely cause is missing or invalid credentials." + " Consider 'kinit'.";
                LOG.fatal(msg, ex);
                throw new RuntimeException(msg, ex);
            }
            throw new IOException(ex);
        }
    });
}

From source file:org.apache.coheigea.bigdata.hdfs.ranger.HDFSRangerTest.java

@org.junit.Test
public void readTestUsingTagPolicy() throws Exception {
    FileSystem fileSystem = hdfsCluster.getFileSystem();

    // Write a file - the AccessControlEnforcer won't be invoked as we are the "superuser"
    final Path file = new Path("/tmp/tmpdir6/data-file2");
    FSDataOutputStream out = fileSystem.create(file);
    for (int i = 0; i < 1024; ++i) {
        out.write(("data" + i + "\n").getBytes("UTF-8"));
        out.flush();//from  ww  w . j a  v  a 2 s . c om
    }
    out.close();

    // Change permissions to read-only
    fileSystem.setPermission(file, new FsPermission(FsAction.READ, FsAction.NONE, FsAction.NONE));

    // Now try to read the file as "bob" - this should be allowed (by the policy - user)
    UserGroupInformation ugi = UserGroupInformation.createUserForTesting("bob", new String[] {});
    ugi.doAs(new PrivilegedExceptionAction<Void>() {

        public Void run() throws Exception {
            Configuration conf = new Configuration();
            conf.set("fs.defaultFS", defaultFs);

            FileSystem fs = FileSystem.get(conf);

            // Read the file
            FSDataInputStream in = fs.open(file);
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            IOUtils.copy(in, output);
            String content = new String(output.toByteArray());
            Assert.assertTrue(content.startsWith("data0"));

            fs.close();
            return null;
        }
    });

    // Now try to read the file as "alice" - this should be allowed (by the policy - group)
    ugi = UserGroupInformation.createUserForTesting("alice", new String[] { "IT" });
    ugi.doAs(new PrivilegedExceptionAction<Void>() {

        public Void run() throws Exception {
            Configuration conf = new Configuration();
            conf.set("fs.defaultFS", defaultFs);

            FileSystem fs = FileSystem.get(conf);

            // Read the file
            FSDataInputStream in = fs.open(file);
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            IOUtils.copy(in, output);
            String content = new String(output.toByteArray());
            Assert.assertTrue(content.startsWith("data0"));

            fs.close();
            return null;
        }
    });

    // Now try to read the file as unknown user "eve" - this should not be allowed
    ugi = UserGroupInformation.createUserForTesting("eve", new String[] {});
    ugi.doAs(new PrivilegedExceptionAction<Void>() {

        public Void run() throws Exception {
            Configuration conf = new Configuration();
            conf.set("fs.defaultFS", defaultFs);

            FileSystem fs = FileSystem.get(conf);

            // Read the file
            try {
                fs.open(file);
                Assert.fail("Failure expected on an incorrect permission");
            } catch (RemoteException ex) {
                // expected
                Assert.assertTrue(RangerAccessControlException.class.getName().equals(ex.getClassName()));
            }

            fs.close();
            return null;
        }
    });

    // Now try to read the file as known user "dave" - this should not be allowed, as he doesn't have the correct permissions
    ugi = UserGroupInformation.createUserForTesting("dave", new String[] {});
    ugi.doAs(new PrivilegedExceptionAction<Void>() {

        public Void run() throws Exception {
            Configuration conf = new Configuration();
            conf.set("fs.defaultFS", defaultFs);

            FileSystem fs = FileSystem.get(conf);

            // Read the file
            try {
                fs.open(file);
                Assert.fail("Failure expected on an incorrect permission");
            } catch (RemoteException ex) {
                // expected
                Assert.assertTrue(RangerAccessControlException.class.getName().equals(ex.getClassName()));
            }

            fs.close();
            return null;
        }
    });
}

From source file:org.apache.hadoop.hbase.regionserver.wal.AbstractTestWALReplay.java

/**
 * Test case of HRegion that is only made out of bulk loaded files.  Assert
 * that we don't 'crash'.//  w w  w  . j a va 2 s. c  om
 * @throws IOException
 * @throws IllegalAccessException
 * @throws NoSuchFieldException
 * @throws IllegalArgumentException
 * @throws SecurityException
 */
@Test
public void testRegionMadeOfBulkLoadedFilesOnly() throws IOException, SecurityException,
        IllegalArgumentException, NoSuchFieldException, IllegalAccessException, InterruptedException {
    final TableName tableName = TableName.valueOf("testRegionMadeOfBulkLoadedFilesOnly");
    final HRegionInfo hri = createBasic3FamilyHRegionInfo(tableName);
    final Path basedir = new Path(this.hbaseRootDir, tableName.getNameAsString());
    deleteDir(basedir);
    final HTableDescriptor htd = createBasic3FamilyHTD(tableName);
    Region region2 = HBaseTestingUtility.createRegionAndWAL(hri, hbaseRootDir, this.conf, htd);
    HBaseTestingUtility.closeRegionAndWAL(region2);
    WAL wal = createWAL(this.conf, hbaseRootDir, logName);
    Region region = HRegion.openHRegion(hri, htd, wal, this.conf);

    byte[] family = htd.getFamilies().iterator().next().getName();
    Path f = new Path(basedir, "hfile");
    HFileTestUtil.createHFile(this.conf, fs, f, family, family, Bytes.toBytes(""), Bytes.toBytes("z"), 10);
    List<Pair<byte[], String>> hfs = new ArrayList<Pair<byte[], String>>(1);
    hfs.add(Pair.newPair(family, f.toString()));
    region.bulkLoadHFiles(hfs, true, null);

    // Add an edit so something in the WAL
    byte[] row = tableName.getName();
    region.put((new Put(row)).addColumn(family, family, family));
    wal.sync();
    final int rowsInsertedCount = 11;

    assertEquals(rowsInsertedCount, getScannedCount(region.getScanner(new Scan())));

    // Now 'crash' the region by stealing its wal
    final Configuration newConf = HBaseConfiguration.create(this.conf);
    User user = HBaseTestingUtility.getDifferentUser(newConf, tableName.getNameAsString());
    user.runAs(new PrivilegedExceptionAction() {
        @Override
        public Object run() throws Exception {
            runWALSplit(newConf);
            WAL wal2 = createWAL(newConf, hbaseRootDir, logName);

            HRegion region2 = HRegion.openHRegion(newConf, FileSystem.get(newConf), hbaseRootDir, hri, htd,
                    wal2);
            long seqid2 = region2.getOpenSeqNum();
            assertTrue(seqid2 > -1);
            assertEquals(rowsInsertedCount, getScannedCount(region2.getScanner(new Scan())));

            // I can't close wal1.  Its been appropriated when we split.
            region2.close();
            wal2.close();
            return null;
        }
    });
}

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

public static void setAuths(final Configuration conf) throws Exception {
    PrivilegedExceptionAction<VisibilityLabelsResponse> action = new PrivilegedExceptionAction<VisibilityLabelsResponse>() {
        public VisibilityLabelsResponse run() throws Exception {
            try (Connection conn = ConnectionFactory.createConnection(conf)) {
                return VisibilityClient.setAuths(conn,
                        new String[] { SECRET, CONFIDENTIAL, PRIVATE, TOPSECRET, UNICODE_VIS_TAG }, "user1");
            } catch (Throwable e) {
                throw new Exception(e);
            }/*from  w  w  w  . j a va2 s  .  co  m*/
        }
    };
    VisibilityLabelsResponse response = SUPERUSER.runAs(action);
}

From source file:org.apache.hadoop.hdfs.TestLease.java

static public DFSClient createDFSClientAs(UserGroupInformation ugi, final Configuration conf) throws Exception {
    return ugi.doAs(new PrivilegedExceptionAction<DFSClient>() {
        @Override//www. java  2  s.co m
        public DFSClient run() throws Exception {
            return new DFSClient(null, mcp, conf, null);
        }
    });
}

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

/**
 * @return ClassLoader//from   w  ww . j a  v a 2  s  .  co  m
 */
private static ClassLoader getContextClassLoader(final ClassLoader classLoader) {
    ClassLoader cl;
    try {
        cl = (ClassLoader) AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws ClassNotFoundException {
                return classLoader != null ? classLoader : Thread.currentThread().getContextClassLoader();
            }
        });
    } catch (PrivilegedActionException e) {
        if (log.isDebugEnabled()) {
            log.debug("Exception thrown from AccessController: " + e.getMessage(), e);
        }
        throw ExceptionFactory.makeWebServiceException(e.getException());
    }

    return cl;
}

From source file:org.apache.hadoop.hbase.rest.TestSecureRESTServer.java

@Test
public void testNegativeAuthorization() throws Exception {
    Pair<CloseableHttpClient, HttpClientContext> pair = getClient();
    CloseableHttpClient client = pair.getFirst();
    HttpClientContext context = pair.getSecond();

    StringEntity entity = new StringEntity("{\"name\":\"test\", \"ColumnSchema\":[{\"name\":\"f\"}]}",
            ContentType.APPLICATION_JSON);
    HttpPut put = new HttpPut("http://localhost:" + REST_TEST.getServletPort() + "/test/schema");
    put.setEntity(entity);/*from   ww  w  .  j av  a2  s .c o  m*/

    UserGroupInformation unprivileged = UserGroupInformation.loginUserFromKeytabAndReturnUGI(CLIENT_PRINCIPAL,
            clientKeytab.getAbsolutePath());
    unprivileged.doAs(new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws Exception {
            try (CloseableHttpResponse response = client.execute(put, context)) {
                final int statusCode = response.getStatusLine().getStatusCode();
                HttpEntity entity = response.getEntity();
                assertEquals("Got response: " + EntityUtils.toString(entity), HttpURLConnection.HTTP_FORBIDDEN,
                        statusCode);
            }
            return null;
        }
    });
}