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:com.hortonworks.streamline.streams.storm.common.StormRestAPIClient.java

private Map doPostRequestWithEmptyBody(String requestUrl) {
    try {/* w w w .j  av  a 2 s .com*/
        LOG.debug("POST request to Storm cluster: " + requestUrl);
        return Subject.doAs(subject, new PrivilegedAction<Map>() {
            @Override
            public Map run() {
                return JsonClientUtil.postForm(client.target(requestUrl), new MultivaluedHashMap<>(),
                        STORM_REST_API_MEDIA_TYPE, Map.class);
            }
        });
    } catch (javax.ws.rs.ProcessingException e) {
        if (e.getCause() instanceof IOException) {
            throw new StormNotReachableException("Exception while requesting " + requestUrl, e);
        }

        throw e;
    } catch (WebApplicationException e) {
        throw WrappedWebApplicationException.of(e);
    }
}

From source file:com.alibaba.otter.shared.common.utils.NioUtilsPerformance.java

public static void mappedTest(File source, File target) throws Exception {
    FileInputStream fis = null;//  ww w  .j a va2 s .  co m
    FileOutputStream fos = null;
    MappedByteBuffer mapbuffer = null;

    try {
        long fileSize = source.length();
        final byte[] outputData = new byte[(int) fileSize];
        fis = new FileInputStream(source);
        fos = new FileOutputStream(target);
        FileChannel sChannel = fis.getChannel();

        target.createNewFile();

        mapbuffer = sChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileSize);
        for (int i = 0; i < fileSize; i++) {
            outputData[i] = mapbuffer.get();
        }

        mapbuffer.clear();
        fos.write(outputData);
        fos.flush();
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(fos);

        if (mapbuffer == null) {
            return;
        }

        final Object buffer = mapbuffer;

        AccessController.doPrivileged(new PrivilegedAction() {

            public Object run() {
                try {
                    Method clean = buffer.getClass().getMethod("cleaner", new Class[0]);

                    if (clean == null) {
                        return null;
                    }
                    clean.setAccessible(true);
                    sun.misc.Cleaner cleaner = (sun.misc.Cleaner) clean.invoke(buffer, new Object[0]);
                    cleaner.clean();
                } catch (Throwable ex) {
                }

                return null;
            }
        });
    }
}

From source file:org.apache.storm.hdfs.security.AutoHDFS.java

@SuppressWarnings("unchecked")
private byte[] getHadoopCredentials(Map conf, final Configuration configuration) {
    try {//from  w w  w. j  ava 2  s . c  o m
        if (UserGroupInformation.isSecurityEnabled()) {
            login(configuration);

            final String topologySubmitterUser = (String) conf.get(Config.TOPOLOGY_SUBMITTER_PRINCIPAL);

            final URI nameNodeURI = conf.containsKey(TOPOLOGY_HDFS_URI)
                    ? new URI(conf.get(TOPOLOGY_HDFS_URI).toString())
                    : FileSystem.getDefaultUri(configuration);

            UserGroupInformation ugi = UserGroupInformation.getCurrentUser();

            final UserGroupInformation proxyUser = UserGroupInformation.createProxyUser(topologySubmitterUser,
                    ugi);

            Credentials creds = (Credentials) proxyUser.doAs(new PrivilegedAction<Object>() {
                @Override
                public Object run() {
                    try {
                        FileSystem fileSystem = FileSystem.get(nameNodeURI, configuration);
                        Credentials credential = proxyUser.getCredentials();

                        fileSystem.addDelegationTokens(hdfsPrincipal, credential);
                        LOG.info("Delegation tokens acquired for user {}", topologySubmitterUser);
                        return credential;
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });

            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(bao);

            creds.write(out);
            out.flush();
            out.close();

            return bao.toByteArray();
        } else {
            throw new RuntimeException("Security is not enabled for HDFS");
        }
    } catch (Exception ex) {
        throw new RuntimeException("Failed to get delegation tokens.", ex);
    }
}

From source file:eu.stratosphere.yarn.ApplicationMaster.java

public static void main(String[] args) throws Exception {
    final String yarnClientUsername = System.getenv(Client.ENV_CLIENT_USERNAME);
    LOG.info("YARN daemon runs as '" + UserGroupInformation.getCurrentUser().getShortUserName() + "' setting"
            + " user to execute Stratosphere ApplicationMaster/JobManager to '" + yarnClientUsername + "'");
    UserGroupInformation ugi = UserGroupInformation.createRemoteUser(yarnClientUsername);
    for (Token<? extends TokenIdentifier> toks : UserGroupInformation.getCurrentUser().getTokens()) {
        ugi.addToken(toks);/*from ww  w.  j a  v a  2 s .  c om*/
    }
    ugi.doAs(new PrivilegedAction<Object>() {
        @Override
        public Object run() {
            try {
                new ApplicationMaster().run();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    });
}

From source file:com.enioka.jqm.tools.JndiContext.java

/**
 * Create a new Context//from  w  ww  . j a v a 2s .  c  o  m
 * 
 * @throws NamingException
 */
private JndiContext() throws NamingException {
    super();

    // List all jars inside ext directory
    File extDir = new File("ext/");
    List<URL> urls = new ArrayList<URL>();
    if (extDir.isDirectory()) {
        for (File f : extDir.listFiles()) {
            if (!f.canRead()) {
                throw new NamingException("can't access file " + f.getAbsolutePath());
            }
            try {
                urls.add(f.toURI().toURL());
            } catch (MalformedURLException e) {
                jqmlogger.error("Error when parsing the content of ext directory. File will be ignored", e);
            }
        }

        // Create classloader
        final URL[] aUrls = urls.toArray(new URL[0]);
        for (URL u : aUrls) {
            jqmlogger.trace(u.toString());
        }
        extResources = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {
            @Override
            public URLClassLoader run() {
                return new URLClassLoader(aUrls, null);
            }
        });
    } else {
        throw new NamingException("JQM_ROOT/ext directory does not exist or cannot be read");
    }
}

From source file:org.apache.hadoop.mapreduce.v2.security.MRDelegationTokenRenewer.java

protected MRClientProtocol instantiateHistoryProxy(final Configuration conf, final InetSocketAddress hsAddress)
        throws IOException {

    if (LOG.isDebugEnabled()) {
        LOG.debug("Connecting to MRHistoryServer at: " + hsAddress);
    }//ww w .j a  v a 2 s  . com
    final YarnRPC rpc = YarnRPC.create(conf);
    UserGroupInformation currentUser = UserGroupInformation.getCurrentUser();
    return currentUser.doAs(new PrivilegedAction<MRClientProtocol>() {
        @Override
        public MRClientProtocol run() {
            return (MRClientProtocol) rpc.getProxy(HSClientProtocol.class, hsAddress, conf);
        }
    });
}

From source file:org.apache.ranger.services.sqoop.client.SqoopClient.java

public List<String> getConnectorList(final String connectorMatching, final List<String> existingConnectors) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Get sqoop connector list for connectorMatching: " + connectorMatching
                + ", existingConnectors: " + existingConnectors);
    }/*from w  ww.j a  v  a  2 s.c  o  m*/
    Subject subj = getLoginSubject();
    if (subj == null) {
        return Collections.emptyList();
    }

    List<String> ret = Subject.doAs(subj, new PrivilegedAction<List<String>>() {

        @Override
        public List<String> run() {

            ClientResponse response = getClientResponse(sqoopUrl, SQOOP_CONNECTOR_API_ENDPOINT, userName);

            SqoopConnectorsResponse sqoopConnectorsResponse = getSqoopResourceResponse(response,
                    SqoopConnectorsResponse.class);
            if (sqoopConnectorsResponse == null
                    || CollectionUtils.isEmpty(sqoopConnectorsResponse.getConnectors())) {
                return Collections.emptyList();
            }
            List<String> connectorResponses = new ArrayList<>();
            for (SqoopConnectorResponse sqoopConnectorResponse : sqoopConnectorsResponse.getConnectors()) {
                connectorResponses.add(sqoopConnectorResponse.getName());
            }

            List<String> connectors = null;
            if (CollectionUtils.isNotEmpty(connectorResponses)) {
                connectors = filterResourceFromResponse(connectorMatching, existingConnectors,
                        connectorResponses);
            }
            return connectors;
        }
    });

    if (LOG.isDebugEnabled()) {
        LOG.debug("Get sqoop connector list result: " + ret);
    }
    return ret;
}

From source file:org.rhq.enterprise.client.LocalClient.java

@Override
public AlertManagerRemote getAlertManager() {
    return AccessController.doPrivileged(new PrivilegedAction<AlertManagerRemote>() {
        @Override/* w  w  w.ja va 2 s  .  c  o m*/
        public AlertManagerRemote run() {
            return AccessController.doPrivileged(new PrivilegedAction<AlertManagerRemote>() {
                @Override
                public AlertManagerRemote run() {
                    return getProxy(LookupUtil.getAlertManager(), AlertManagerRemote.class);
                }
            });
        }
    });
}

From source file:com.twitter.hraven.hadoopJobMonitor.rpc.ClientCache.java

protected MRClientProtocol instantiateHistoryProxy() throws IOException {
    final String serviceAddr = conf.get(JHAdminConfig.MR_HISTORY_ADDRESS);
    if (StringUtils.isEmpty(serviceAddr)) {
        return null;
    }//from   w ww.j  a  v  a2s . co  m
    LOG.debug("Connecting to HistoryServer at: " + serviceAddr);
    final YarnRPC rpc = YarnRPC.create(conf);
    LOG.debug("Connected to HistoryServer at: " + serviceAddr);
    UserGroupInformation currentUser = UserGroupInformation.getCurrentUser();
    return currentUser.doAs(new PrivilegedAction<MRClientProtocol>() {
        @Override
        public MRClientProtocol run() {
            return (MRClientProtocol) rpc.getProxy(HSClientProtocol.class,
                    NetUtils.createSocketAddr(serviceAddr), conf);
        }
    });
}

From source file:org.beangle.model.persist.hibernate.internal.ClassUtils.java

public static ClassLoader getFwkClassLoader() {
    if (System.getSecurityManager() != null) {
        return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
            public ClassLoader run() {
                return Bundle.class.getClassLoader();
            }/*from  w  w  w .j  a  v  a  2s .c o m*/
        });
    } else {
        return Bundle.class.getClassLoader();
    }
}