Example usage for java.security PrivilegedAction PrivilegedAction

List of usage examples for java.security PrivilegedAction PrivilegedAction

Introduction

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

Prototype

PrivilegedAction

Source Link

Usage

From source file:org.apache.jasper.runtime.PageContextImpl.java

public void setAttribute(final String name, final Object attribute) {

    if (name == null) {
        throw new NullPointerException(Localizer.getMessage("jsp.error.attribute.null_name"));
    }/*from w  ww.j a va 2  s  . co m*/

    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                doSetAttribute(name, attribute);
                return null;
            }
        });
    } else {
        doSetAttribute(name, attribute);
    }
}

From source file:org.apache.ranger.services.hive.client.HiveClient.java

public List<String> getColumnList(String columnNameMatching, List<String> dbList, List<String> tblList,
        List<String> colList) throws HadoopException {
    final String clmNameMatching = columnNameMatching;
    final List<String> databaseList = dbList;
    final List<String> tableList = tblList;
    final List<String> clmList = colList;
    List<String> columnList = Subject.doAs(getLoginSubject(), new PrivilegedAction<List<String>>() {
        public List<String> run() {
            List<String> ret = null;
            try {
                ret = getClmList(clmNameMatching, databaseList, tableList, clmList);
            } catch (HadoopException he) {
                LOG.error("<== HiveClient getColumnList() :Unable to get the Column List", he);
                throw he;
            }// w  w  w .j a  v  a 2s .  com
            return ret;
        }
    });
    return columnList;
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.TestAMAuthorization.java

@Test
public void testUnauthorizedAccess() throws Exception {
    MyContainerManager containerManager = new MyContainerManager();
    rm = new MockRMWithAMS(conf, containerManager);
    rm.start();/*from  w w  w.ja  v  a 2s. c  om*/

    MockNM nm1 = rm.registerNode("localhost:1234", 5120);

    RMApp app = rm.submitApp(1024);

    nm1.nodeHeartbeat(true);

    int waitCount = 0;
    while (containerManager.containerTokens == null && waitCount++ < 40) {
        LOG.info("Waiting for AM Launch to happen..");
        Thread.sleep(1000);
    }
    Assert.assertNotNull(containerManager.containerTokens);

    RMAppAttempt attempt = app.getCurrentAppAttempt();
    ApplicationAttemptId applicationAttemptId = attempt.getAppAttemptId();
    waitForLaunchedState(attempt);

    final Configuration conf = rm.getConfig();
    final YarnRPC rpc = YarnRPC.create(conf);
    final InetSocketAddress serviceAddr = conf.getSocketAddr(YarnConfiguration.RM_SCHEDULER_ADDRESS,
            YarnConfiguration.DEFAULT_RM_SCHEDULER_ADDRESS, YarnConfiguration.DEFAULT_RM_SCHEDULER_PORT);

    UserGroupInformation currentUser = UserGroupInformation.createRemoteUser(applicationAttemptId.toString());

    // First try contacting NM without tokens
    ApplicationMasterProtocol client = currentUser.doAs(new PrivilegedAction<ApplicationMasterProtocol>() {
        @Override
        public ApplicationMasterProtocol run() {
            return (ApplicationMasterProtocol) rpc.getProxy(ApplicationMasterProtocol.class, serviceAddr, conf);
        }
    });

    RegisterApplicationMasterRequest request = Records.newRecord(RegisterApplicationMasterRequest.class);
    try {
        client.registerApplicationMaster(request);
        Assert.fail("Should fail with authorization error");
    } catch (Exception e) {
        if (isCause(AccessControlException.class, e)) {
            // Because there are no tokens, the request should be rejected as the
            // server side will assume we are trying simple auth.
            String expectedMessage = "";
            if (UserGroupInformation.isSecurityEnabled()) {
                expectedMessage = "Client cannot authenticate via:[TOKEN]";
            } else {
                expectedMessage = "SIMPLE authentication is not enabled.  Available:[TOKEN]";
            }
            Assert.assertTrue(e.getCause().getMessage().contains(expectedMessage));
        } else {
            throw e;
        }
    }

    // TODO: Add validation of invalid authorization when there's more data in
    // the AMRMToken
}

From source file:org.apache.ranger.biz.KmsKeyMgr.java

public VXKmsKey rolloverKey(String provider, VXKmsKey vXKey) throws Exception {
    String providers[] = null;/*from  ww  w.j a  v  a2 s  .  c  o m*/
    try {
        providers = getKMSURL(provider);
    } catch (Exception e) {
        logger.error("rolloverKey(" + provider + ", " + vXKey.getName() + ") failed", e);
    }
    VXKmsKey ret = null;
    boolean isKerberos = false;
    try {
        isKerberos = checkKerberos();
    } catch (Exception e1) {
        logger.error("checkKerberos(" + provider + ") failed", e1);
    }
    if (providers != null) {
        for (int i = 0; i < providers.length; i++) {
            Client c = getClient();
            String rollRest = KMS_ROLL_KEY_URI.replaceAll(Pattern.quote("${alias}"), vXKey.getName());
            String currentUserLoginId = ContextUtil.getCurrentUserLoginId();
            String uri = providers[i] + (providers[i].endsWith("/") ? rollRest : ("/" + rollRest));
            if (!isKerberos) {
                uri = uri.concat("?user.name=" + currentUserLoginId);
            } else {
                uri = uri.concat("?doAs=" + currentUserLoginId);
            }
            final WebResource r = c.resource(uri);
            Gson gson = new GsonBuilder().create();
            final String jsonString = gson.toJson(vXKey);
            try {
                String response = null;
                if (!isKerberos) {
                    response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE)
                            .post(String.class, jsonString);
                } else {
                    Subject sub = getSubjectForKerberos(provider);
                    response = Subject.doAs(sub, new PrivilegedAction<String>() {
                        @Override
                        public String run() {
                            return r.accept(MediaType.APPLICATION_JSON_TYPE)
                                    .type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString);
                        }
                    });
                }
                logger.debug("Roll RESPONSE: [" + response + "]");
                ret = gson.fromJson(response, VXKmsKey.class);
                break;
            } catch (Exception e) {
                if (e instanceof UniformInterfaceException || i == providers.length - 1)
                    throw e;
                else
                    continue;
            }
        }
    }
    return ret;
}

From source file:org.apache.cxf.common.logging.LogUtils.java

private static ClassLoader getContextClassLoader() {
    final SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
            public ClassLoader run() {
                return Thread.currentThread().getContextClassLoader();
            }//  www .j  a va  2  s  .  c  o  m
        });
    }
    return Thread.currentThread().getContextClassLoader();
}

From source file:org.apache.ddlutils.task.DatabaseTaskBase.java

/**
 * {@inheritDoc}/*ww w  .  j  a v a 2 s.c  om*/
 */
public void execute() throws BuildException {
    initLogging();

    if (!hasCommands()) {
        _log.info("No sub tasks specified, so there is nothing to do.");
        return;
    }

    ClassLoader sysClassLoader = (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            try {
                ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
                AntClassLoader newClassLoader = new AntClassLoader(getClass().getClassLoader(), true);

                // we're changing the thread classloader so that we can access resources
                // from the classpath used to load this task's class
                Thread.currentThread().setContextClassLoader(newClassLoader);
                return contextClassLoader;
            } catch (SecurityException ex) {
                throw new BuildException("Could not change the context clas loader", ex);
            }
        }
    });

    try {
        executeCommands(readModel());
    } finally {
        if ((getDataSource() != null) && isShutdownDatabase()) {
            getPlatform().shutdownDatabase();
        }
        // rollback of our classloader change
        Thread.currentThread().setContextClassLoader(sysClassLoader);
    }
}

From source file:org.apache.hadoop.mapreduce.security.TestJHSSecurity.java

private MRClientProtocol getMRClientProtocol(Token token, final InetSocketAddress hsAddress, String user,
        final Configuration conf) {
    UserGroupInformation ugi = UserGroupInformation.createRemoteUser(user);
    ugi.addToken(ConverterUtils.convertFromYarn(token, hsAddress));

    final YarnRPC rpc = YarnRPC.create(conf);
    MRClientProtocol hsWithDT = ugi.doAs(new PrivilegedAction<MRClientProtocol>() {

        @Override//from www  .  ja  v a  2 s.c  o m
        public MRClientProtocol run() {
            return (MRClientProtocol) rpc.getProxy(HSClientProtocol.class, hsAddress, conf);
        }
    });
    return hsWithDT;
}

From source file:org.codehaus.groovy.grails.web.pages.ext.jsp.GroovyPagesPageContext.java

@Override
public ExpressionEvaluator getExpressionEvaluator() {
    try {//  w  ww .  j a  va 2 s. co m
        Class<?> type = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
            public ClassLoader run() {
                return Thread.currentThread().getContextClassLoader();
            }
        }).loadClass("org.apache.commons.el.ExpressionEvaluatorImpl");
        return (ExpressionEvaluator) type.newInstance();
    } catch (Exception e) {
        throw new UnsupportedOperationException("In order for the getExpressionEvaluator() "
                + "method to work, you must have downloaded the apache commons-el jar and "
                + "made it available in the classpath.");
    }
}

From source file:SocketFetcher.java

/**
 * Convenience method to get our context class loader. Assert any privileges
 * we might have and then call the Thread.getContextClassLoader method.
 *//* w  w  w.  j  av  a  2s .c  o  m*/
private static ClassLoader getContextClassLoader() {
    return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            ClassLoader cl = null;
            try {
                cl = Thread.currentThread().getContextClassLoader();
            } catch (SecurityException ex) {
            }
            return cl;
        }
    });
}

From source file:eu.europa.ejusticeportal.dss.applet.DssApplet.java

private void preloadLibraries() {
    AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            Security.addProvider(new BouncyCastleProvider());
            return null;
        }/*from w  w  w. j  av a 2 s.  c  o m*/
    });
}