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.bsf.BSFManager.java

/**
 * Load a scripting engine based on the lang string identifying it.
 *
 * @param lang string identifying language
 * @exception BSFException if the language is unknown (i.e., if it
 *            has not been registered) with a reason of
 *            REASON_UNKNOWN_LANGUAGE. If the language is known but
 *            if the interface can't be created for some reason, then
 *            the reason is set to REASON_OTHER_ERROR and the actual
 *            exception is passed on as well.
 *//*from   w  w w .jav  a  2s .c om*/
public BSFEngine loadScriptingEngine(String lang) throws BSFException {
    logger.debug("BSFManager:loadScriptingEngine");

    // if its already loaded return that
    BSFEngine eng = (BSFEngine) loadedEngines.get(lang);
    if (eng != null) {
        return eng;
    }

    // is it a registered language?
    String engineClassName = (String) registeredEngines.get(lang);
    if (engineClassName == null) {
        logger.error("unsupported language: " + lang);
        throw new BSFException(BSFException.REASON_UNKNOWN_LANGUAGE, "unsupported language: " + lang);
    }

    // create the engine and initialize it. if anything goes wrong
    // except.
    try {
        Class engineClass = (classLoader == null) ? Class.forName(engineClassName)
                : classLoader.loadClass(engineClassName);
        final BSFEngine engf = (BSFEngine) engineClass.newInstance();
        final BSFManager thisf = this;
        final String langf = lang;
        final Vector dbf = declaredBeans;
        AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws Exception {
                engf.initialize(thisf, langf, dbf);
                return null;
            }
        });
        eng = engf;
        loadedEngines.put(lang, eng);
        pcs.addPropertyChangeListener(eng);
        return eng;
    } catch (PrivilegedActionException prive) {

        logger.error("Exception :", prive);
        throw (BSFException) prive.getException();
    } catch (Throwable t) {

        logger.error("Exception :", t);
        throw new BSFException(BSFException.REASON_OTHER_ERROR, "unable to load language: " + lang, t);
    }
}

From source file:org.apache.hadoop.hdfs.server.datanode.DataNode.java

public static InterDatanodeProtocol createInterDataNodeProtocolProxy(DatanodeID datanodeid,
        final Configuration conf, final int socketTimeout) throws IOException {
    final InetSocketAddress addr = NetUtils
            .createSocketAddr(datanodeid.getHost() + ":" + datanodeid.getIpcPort());
    if (InterDatanodeProtocol.LOG.isDebugEnabled()) {
        InterDatanodeProtocol.LOG.info("InterDatanodeProtocol addr=" + addr);
    }//from w w w. java 2s  .c om

    UserGroupInformation loginUgi = UserGroupInformation.getLoginUser();
    try {
        return loginUgi.doAs(new PrivilegedExceptionAction<InterDatanodeProtocol>() {
            public InterDatanodeProtocol run() throws IOException {
                return (InterDatanodeProtocol) RPC.getProxy(InterDatanodeProtocol.class,
                        InterDatanodeProtocol.versionID, addr, conf, socketTimeout);
            }
        });
    } catch (InterruptedException ie) {
        throw new IOException(ie.getMessage());
    }
}

From source file:org.apache.ambari.view.slider.SliderAppsViewControllerImpl.java

private <T> T invokeHDFSClientRunnable(final HDFSClientRunnable<T> runnable,
        final Map<String, String> hadoopConfigs) throws IOException, InterruptedException {
    ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    try {//ww w  .  j av  a2 s. c  o m
        boolean securityEnabled = Boolean.valueOf(hadoopConfigs.get("security_enabled"));
        final HdfsConfiguration hdfsConfiguration = new HdfsConfiguration();
        for (Entry<String, String> entry : hadoopConfigs.entrySet()) {
            hdfsConfiguration.set(entry.getKey(), entry.getValue());
        }
        UserGroupInformation.setConfiguration(hdfsConfiguration);
        UserGroupInformation sliderUser;
        String loggedInUser = getUserToRunAs(hadoopConfigs);
        if (securityEnabled) {
            String viewPrincipal = getViewParameterValue(PARAM_VIEW_PRINCIPAL);
            String viewPrincipalKeytab = getViewParameterValue(PARAM_VIEW_PRINCIPAL_KEYTAB);
            UserGroupInformation ambariUser = UserGroupInformation
                    .loginUserFromKeytabAndReturnUGI(viewPrincipal, viewPrincipalKeytab);
            if (loggedInUser.equals(ambariUser.getShortUserName())) {
                // HDFS throws exception when caller tries to impresonate themselves.
                // User: admin@EXAMPLE.COM is not allowed to impersonate admin
                sliderUser = ambariUser;
            } else {
                sliderUser = UserGroupInformation.createProxyUser(loggedInUser, ambariUser);
            }
        } else {
            sliderUser = UserGroupInformation.getBestUGI(null, loggedInUser);
        }
        try {
            T value = sliderUser.doAs(new PrivilegedExceptionAction<T>() {
                @Override
                public T run() throws Exception {
                    String fsPath = hadoopConfigs.get("fs.defaultFS");
                    FileSystem fs = FileSystem.get(URI.create(fsPath), hdfsConfiguration);
                    try {
                        return runnable.run(fs);
                    } finally {
                        fs.close();
                    }
                }
            });
            return value;
        } catch (UndeclaredThrowableException e) {
            throw e;
        }
    } finally {
        Thread.currentThread().setContextClassLoader(currentClassLoader);
    }
}

From source file:org.apache.hadoop.mapred.TaskTracker.java

private FileSystem getFS(final Path filePath, JobID jobId, final Configuration conf)
        throws IOException, InterruptedException {
    RunningJob rJob = runningJobs.get(jobId);
    FileSystem userFs = rJob.ugi.doAs(new PrivilegedExceptionAction<FileSystem>() {
        public FileSystem run() throws IOException {
            return filePath.getFileSystem(conf);
        }// ww w.  java 2s .c o  m
    });
    return userFs;
}

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

@Test
public void testDeleteColumnsWithoutAndWithVisibilityLabels() throws Exception {
    final TableName tableName = TableName.valueOf(TEST_NAME.getMethodName());
    Admin hBaseAdmin = TEST_UTIL.getAdmin();
    HColumnDescriptor colDesc = new HColumnDescriptor(fam);
    HTableDescriptor desc = new HTableDescriptor(tableName);
    desc.addFamily(colDesc);/*from   ww w.j av a 2  s .  c  o m*/
    hBaseAdmin.createTable(desc);
    try (Table table = TEST_UTIL.getConnection().getTable(tableName)) {
        Put put = new Put(row1);
        put.addColumn(fam, qual, value);
        put.setCellVisibility(new CellVisibility(CONFIDENTIAL));
        table.put(put);
        Delete d = new Delete(row1);
        // without visibility
        d.addColumns(fam, qual, HConstants.LATEST_TIMESTAMP);
        table.delete(d);
        PrivilegedExceptionAction<Void> scanAction = new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws Exception {
                try (Connection connection = ConnectionFactory.createConnection(conf);
                        Table table = connection.getTable(tableName)) {
                    Scan s = new Scan();
                    ResultScanner scanner = table.getScanner(s);
                    Result[] next = scanner.next(3);
                    assertEquals(next.length, 1);
                } catch (Throwable t) {
                    throw new IOException(t);
                }
                return null;
            }
        };
        SUPERUSER.runAs(scanAction);
        d = new Delete(row1);
        // with visibility
        d.setCellVisibility(new CellVisibility(CONFIDENTIAL));
        d.addColumns(fam, qual, HConstants.LATEST_TIMESTAMP);
        table.delete(d);
        scanAction = new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws Exception {
                try (Connection connection = ConnectionFactory.createConnection(conf);
                        Table table = connection.getTable(tableName)) {
                    Scan s = new Scan();
                    ResultScanner scanner = table.getScanner(s);
                    Result[] next = scanner.next(3);
                    assertEquals(next.length, 0);
                } catch (Throwable t) {
                    throw new IOException(t);
                }
                return null;
            }
        };
        SUPERUSER.runAs(scanAction);
    }
}

From source file:org.apache.hadoop.hbase.ipc.AsyncRpcChannel.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.//from w w w . j  a  va2  s .  c  o m
 * The other problem is to do with ticket expiry. To handle that,
 * a relogin is attempted.
 * <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>
 *
 * @param currRetries retry count
 * @param ex          exception describing fail
 * @param user        which is trying to connect
 * @throws java.io.IOException  if IO fail
 * @throws InterruptedException if thread is interrupted
 */
private void handleSaslConnectionFailure(final int currRetries, final Throwable ex,
        final UserGroupInformation user) throws IOException, InterruptedException {
    user.doAs(new PrivilegedExceptionAction<Void>() {
        public Void run() throws IOException, InterruptedException {
            if (shouldAuthenticateOverKrb()) {
                if (currRetries < MAX_SASL_RETRIES) {
                    LOG.debug("Exception encountered while connecting to the server : " + ex);
                    //try re-login
                    if (UserGroupInformation.isLoginKeytabBased()) {
                        UserGroupInformation.getLoginUser().reloginFromKeytab();
                    } else {
                        UserGroupInformation.getLoginUser().reloginFromTicketCache();
                    }

                    // Should reconnect
                    return null;
                } else {
                    String msg = "Couldn't setup connection for "
                            + UserGroupInformation.getLoginUser().getUserName() + " to " + serverPrincipal;
                    LOG.warn(msg);
                    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.hadoop.hbase.ipc.AsyncRpcChannelImpl.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.//www  .j a v  a  2 s  . co m
 * <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>
 * @param currRetries retry count
 * @param ex exception describing fail
 * @param user which is trying to connect
 * @throws java.io.IOException if IO fail
 * @throws InterruptedException if thread is interrupted
 */
private void handleSaslConnectionFailure(final int currRetries, final Throwable ex,
        final UserGroupInformation user) throws IOException, InterruptedException {
    user.doAs(new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws IOException, InterruptedException {
            if (shouldAuthenticateOverKrb()) {
                if (currRetries < MAX_SASL_RETRIES) {
                    LOG.debug("Exception encountered while connecting to the server : " + ex);
                    // try re-login
                    if (UserGroupInformation.isLoginKeytabBased()) {
                        UserGroupInformation.getLoginUser().reloginFromKeytab();
                    } else {
                        UserGroupInformation.getLoginUser().reloginFromTicketCache();
                    }

                    // Should reconnect
                    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.axis2.jaxws.util.WSDL4JWrapper.java

public Definition loadDefinition() {

    Definition def = null;/*from  ww w  .  j a  v a2s  .  c  o m*/

    if (wsdlExplicitURL != null) {
        try {

            URLConnection urlConn = getPrivilegedURLConnection(this.wsdlURL);
            if (urlConn != null) {
                try {
                    InputStream is = getInputStream(urlConn);
                    if (is != null) {
                        if (catalogManager == null) {
                            catalogManager = new OASISCatalogManager();
                        }
                        final CatalogWSDLLocator locator = new CatalogWSDLLocator(wsdlExplicitURL, is,
                                getThreadClassLoader(), catalogManager);
                        if (log.isDebugEnabled()) {
                            log.debug("Loading WSDL using ModuleWSDLLocator from base " + "location: "
                                    + wsdlExplicitURL);
                        }
                        def = (Definition) AccessController.doPrivileged(new PrivilegedExceptionAction() {
                            public Object run() throws WSDLException {
                                WSDLReader reader = getWSDLReader();
                                return reader.readWSDL(locator);
                            }
                        });
                    }
                } catch (Exception e) {
                    if (log.isDebugEnabled()) {
                        log.debug("Using ModuleWSDLLocator was not successful for loading "
                                + "WSDL due to the following error: " + e.toString() + ". The "
                                + "WSDL will be read from the WSDL location: " + wsdlExplicitURL);
                    }
                }
            }
            if (def == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Loading WSDL from location: " + wsdlExplicitURL);
                }
                def = (Definition) AccessController.doPrivileged(new PrivilegedExceptionAction() {
                    public Object run() throws WSDLException {
                        WSDLReader reader = getWSDLReader();
                        return reader.readWSDL(wsdlExplicitURL);
                    }
                });
            }

        } catch (PrivilegedActionException e) {
            if (log.isDebugEnabled()) {
                log.debug("Exception thrown from AccessController: " + e);
            }
            throw ExceptionFactory.makeWebServiceException(e.getException());
        } catch (IOException ioe) {
            if (log.isDebugEnabled()) {
                log.debug("An error occurred while attempting to load the WSDL "
                        + "file at the following location: " + wsdlExplicitURL);
            }
            throw ExceptionFactory.makeWebServiceException(ioe);
        }
    }

    if (log.isDebugEnabled()) {
        if (def != null) {
            log.debug("loadDefinition() returning a NON-NULL definition");
        } else {
            log.debug("loadDefinition() returning a NULL definition");
        }
    }

    return def;
}

From source file:org.apache.ambari.view.slider.SliderAppsViewControllerImpl.java

private <T> T invokeSliderClientRunnable(final SliderClientContextRunnable<T> runnable)
        throws IOException, InterruptedException, YarnException {
    ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    try {//from  w w  w  .  ja  v  a  2s .co  m
        boolean securityEnabled = Boolean.valueOf(getHadoopConfigs().get("security_enabled"));
        UserGroupInformation.setConfiguration(getSliderClientConfiguration());
        UserGroupInformation sliderUser;
        String loggedInUser = getUserToRunAs();
        if (securityEnabled) {
            String viewPrincipal = getViewParameterValue(PARAM_VIEW_PRINCIPAL);
            String viewPrincipalKeytab = getViewParameterValue(PARAM_VIEW_PRINCIPAL_KEYTAB);
            UserGroupInformation ambariUser = UserGroupInformation
                    .loginUserFromKeytabAndReturnUGI(viewPrincipal, viewPrincipalKeytab);
            if (loggedInUser.equals(ambariUser.getShortUserName())) {
                // HDFS throws exception when caller tries to impresonate themselves.
                // User: admin@EXAMPLE.COM is not allowed to impersonate admin
                sliderUser = ambariUser;
            } else {
                sliderUser = UserGroupInformation.createProxyUser(loggedInUser, ambariUser);
            }
        } else {
            sliderUser = UserGroupInformation.getBestUGI(null, loggedInUser);
        }
        try {
            T value = sliderUser.doAs(new PrivilegedExceptionAction<T>() {
                @Override
                public T run() throws Exception {
                    final SliderClient sliderClient = createSliderClient();
                    try {
                        return runnable.run(sliderClient);
                    } finally {
                        destroySliderClient(sliderClient);
                    }
                }
            });
            return value;
        } catch (UndeclaredThrowableException e) {
            Throwable cause = e.getCause();
            if (cause instanceof YarnException) {
                YarnException ye = (YarnException) cause;
                throw ye;
            }
            throw e;
        }
    } finally {
        Thread.currentThread().setContextClassLoader(currentClassLoader);
    }
}

From source file:org.apache.axis2.jaxws.runtime.description.marshal.impl.ArtifactProcessor.java

/**
 * Return the class for this name/*  w  w w. ja  v a  2 s .  c  o m*/
 *
 * @return Class
 */
private static Class forName(final String className, final boolean initialize, final ClassLoader classloader)
        throws ClassNotFoundException {
    // NOTE: This method must remain protected because it uses AccessController
    Class cl = null;
    try {
        cl = (Class) AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws ClassNotFoundException {
                // Class.forName does not support primitives
                Class cls = ClassUtils.getPrimitiveClass(className);
                try {
                    if (cls == null) {
                        cls = Class.forName(className, initialize, classloader);
                    }
                    return cls;
                    //Lets catch NoClassDefFoundError as its part of Throwable
                    //Any Exception that extends Exception will be handled by doPriv method.    
                } catch (NoClassDefFoundError e) {
                    /**
                     * In different jaxws scenarios, some classes may be missing.  So it is normal behavior
                     * to get to this point.  The exception is swallowed and a null is returned.  
                     * The exception is not logged...as this would give servicability folks the idea that a problem occurred.
                     */
                }
                return cls;
            }
        });
    } catch (PrivilegedActionException e) {
        /**
         * In different jaxws scenarios, some classes may be missing.  So it is normal behavior
         * to get to this point. 
         * The exception is not logged...as this would give servicability folks the idea that a problem occurred.
         */
        throw (ClassNotFoundException) e.getException();
    }

    return cl;
}