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.ranger.services.hbase.client.HBaseClient.java

public boolean getHBaseStatus() throws HadoopException {
    boolean hbaseStatus = false;
    subj = getLoginSubject();//from  w w  w  .ja v  a 2 s  .c  o m
    final String errMsg = " You can still save the repository and start creating "
            + "policies, but you would not be able to use autocomplete for "
            + "resource names. Check ranger_admin.log for more info.";
    if (subj != null) {
        try {

            hbaseStatus = Subject.doAs(subj, new PrivilegedAction<Boolean>() {
                @Override
                public Boolean run() {
                    Boolean hbaseStatus1 = false;
                    try {
                        LOG.info("getHBaseStatus: creating default Hbase configuration");

                        LOG.info("getHBaseStatus: setting config values from client");
                        setClientConfigValues(conf);
                        LOG.info("getHBaseStatus: checking HbaseAvailability with the new config");
                        HBaseAdmin.checkHBaseAvailable(conf);
                        LOG.info("getHBaseStatus: no exception: HbaseAvailability true");
                        hbaseStatus1 = true;
                    } catch (ZooKeeperConnectionException zce) {
                        String msgDesc = "getHBaseStatus: Unable to connect to `ZooKeeper` "
                                + "using given config parameters.";
                        HadoopException hdpException = new HadoopException(msgDesc, zce);
                        hdpException.generateResponseDataMap(false, getMessage(zce), msgDesc + errMsg, null,
                                null);

                        LOG.error(msgDesc + zce);
                        throw hdpException;

                    } catch (MasterNotRunningException mnre) {
                        String msgDesc = "getHBaseStatus: Looks like `Master` is not running, "
                                + "so couldn't check that running HBase is available or not, "
                                + "Please try again later.";
                        HadoopException hdpException = new HadoopException(msgDesc, mnre);
                        hdpException.generateResponseDataMap(false, getMessage(mnre), msgDesc + errMsg, null,
                                null);
                        LOG.error(msgDesc + mnre);
                        throw hdpException;

                    } catch (ServiceException se) {
                        String msgDesc = "getHBaseStatus: Unable to check availability of "
                                + "Hbase environment [" + getConfigHolder().getDatasourceName() + "].";
                        HadoopException hdpException = new HadoopException(msgDesc, se);
                        hdpException.generateResponseDataMap(false, getMessage(se), msgDesc + errMsg, null,
                                null);
                        LOG.error(msgDesc + se);
                        throw hdpException;

                    } catch (IOException io) {
                        String msgDesc = "getHBaseStatus: Unable to check availability of"
                                + " Hbase environment [" + getConfigHolder().getDatasourceName() + "].";
                        HadoopException hdpException = new HadoopException(msgDesc, io);
                        hdpException.generateResponseDataMap(false, getMessage(io), msgDesc + errMsg, null,
                                null);
                        LOG.error(msgDesc + io);
                        throw hdpException;

                    } catch (Throwable e) {
                        String msgDesc = "getHBaseStatus: Unable to check availability of"
                                + " Hbase environment [" + getConfigHolder().getDatasourceName() + "].";
                        LOG.error(msgDesc + e);
                        hbaseStatus1 = false;
                        HadoopException hdpException = new HadoopException(msgDesc, e);
                        hdpException.generateResponseDataMap(false, getMessage(e), msgDesc + errMsg, null,
                                null);
                        throw hdpException;
                    }
                    return hbaseStatus1;
                }
            });
        } catch (SecurityException se) {
            String msgDesc = "getHBaseStatus: Unable to connect to HBase Server instance ";
            HadoopException hdpException = new HadoopException(msgDesc, se);
            hdpException.generateResponseDataMap(false, getMessage(se), msgDesc + errMsg, null, null);
            LOG.error(msgDesc + se);
            throw hdpException;
        }
    } else {
        LOG.error("getHBaseStatus: secure login not done, subject is null");
    }

    return hbaseStatus;
}

From source file:io.fabric8.elasticsearch.plugin.auth.OpenShiftTokenAuthentication.java

private Collection<String> retrieveBackendRoles(OpenshiftRequestContext context) {
    List<String> roles = new ArrayList<>();
    if (PluginServiceFactory.isReady()) {
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(new SpecialPermission());
        }//from  w  w w  .j  a  v  a  2s .c  o m
        OpenshiftAPIService apiService = PluginServiceFactory.getApiService();
        for (Map.Entry<String, Settings> sar : sars.entrySet()) {
            boolean allowed = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {

                @Override
                public Boolean run() {
                    try {
                        Settings params = sar.getValue();
                        return apiService.localSubjectAccessReview(context.getToken(), params.get("namespace"),
                                params.get("verb"), params.get("resource"), params.get("resourceAPIGroup"),
                                ArrayUtils.EMPTY_STRING_ARRAY);
                    } catch (Exception e) {
                        LOGGER.error("Exception executing LSAR", e);
                    }
                    return false;
                }

            });
            if (allowed) {
                roles.add(sar.getKey());
            }
        }
    }
    return roles;
}

From source file:org.flowerplatform.web.tests.codesync.CodeSyncWikiTest.java

public void testDokuWiki() {
    Subject subject = new Subject();
    final FlowerWebPrincipal principal = new FlowerWebPrincipal(0);
    final String technology = "Doku";
    String url = "http://csp1/dokuwiki/lib/exe/xmlrpc.php";
    String user = "";
    String password = "";
    principal.getWikiClientConfigurations().put(technology,
            new DokuWikiClientConfiguration(url, user, password));
    subject.getPrincipals().add(principal);
    Subject.doAsPrivileged(subject, new PrivilegedAction<Void>() {

        @Override/*from  w ww  .j  a v a2  s .c o m*/
        public Void run() {
            FlexContext.setThreadLocalSession(new HttpFlexSession());
            FlexContext.setUserPrincipal(principal);
            RecordingTestWebCommunicationChannel cc = new RecordingTestWebCommunicationChannel();
            cc.setPrincipal((FlowerWebPrincipal) principal);
            ServiceInvocationContext context = new ServiceInvocationContext(cc);

            Object wiki = DokuWikiPlugin.getInstance().getWikiPages("proiecte:flower:teste");

            WikiPlugin.getInstance().getConfigurationProviders().put(technology,
                    new DokuWikiConfigurationProvider());

            WikiPlugin wikiPlugin = WikiPlugin.getInstance();
            File project = getProject();
            ResourceSet resourceSet = CodeSyncPlugin.getInstance().getOrCreateResourceSet(project,
                    "mindmapEditorStatefulService");
            CodeSyncRoot leftRoot = wikiPlugin.getWikiTree(null, resourceSet, wiki, "proiecte:flower:teste",
                    technology);
            CodeSyncRoot rightRoot = wikiPlugin.getWikiTree(project, resourceSet, null, "proiecte:flower:teste",
                    technology);

            expected = new Pair[] { new Pair(WikiPlugin.FOLDER_CATEGORY, 0), // Crispico
                    new Pair(WikiPlugin.FOLDER_CATEGORY, 1), // proiecte
                    new Pair(WikiPlugin.FOLDER_CATEGORY, 2), // flower
                    new Pair(WikiPlugin.PAGE_CATEGORY, 3), // teste

                    new Pair(WikiPlugin.FOLDER_CATEGORY, 4), // teste
                    new Pair(WikiPlugin.PAGE_CATEGORY, 5), // new_test
                    new Pair(WikiPlugin.HEADING_LEVEL_2_CATEGORY, 6),
                    new Pair(WikiPlugin.HEADING_LEVEL_3_CATEGORY, 7),
                    new Pair(WikiPlugin.PARAGRAPH_CATEGORY, 8),

                    new Pair(WikiPlugin.HEADING_LEVEL_1_CATEGORY, 4),
                    new Pair(WikiPlugin.HEADING_LEVEL_1_CATEGORY, 4),
                    new Pair(WikiPlugin.HEADING_LEVEL_2_CATEGORY, 5),
                    new Pair(WikiPlugin.PARAGRAPH_CATEGORY, 6), new Pair(WikiPlugin.FLOWER_BLOCK_CATEGORY, 6),
                    new Pair(WikiPlugin.PARAGRAPH_CATEGORY, 6), new Pair(WikiPlugin.PARAGRAPH_CATEGORY, 6),
                    new Pair(WikiPlugin.PARAGRAPH_CATEGORY, 6), new Pair(WikiPlugin.PARAGRAPH_CATEGORY, 6),
                    new Pair(WikiPlugin.HEADING_LEVEL_2_CATEGORY, 5),
                    new Pair(WikiPlugin.HEADING_LEVEL_1_CATEGORY, 4)

            };
            test(leftRoot, rightRoot, resourceSet, technology, expected);

            return null;
        }
    }, null);
}

From source file:org.javascool.polyfilewriter.Gateway.java

/**
 * Remove a file or directory/*from w  w w. j a  v a 2s . c  o m*/
 *
 * @param location The path to file or directory
 * @return true On success false If the file or folder don't exist
 */
public boolean remove(final String location) throws Exception {
    assertSafeUsage();
    try {
        return AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
            public Boolean run() {
                try {
                    if (location != null) {
                        if (!new File(location).exists()) {
                            throw new IllegalArgumentException("" + location + " does not exist");
                        }
                        new File(location).delete();
                    } else {
                        throw new IllegalArgumentException("location is null");
                    }
                } catch (Exception e) {
                    return false;
                }
                return true;
            }
        });

    } catch (Exception e) {
        popException(e);
        throw e;
    }
}

From source file:com.continuuity.weave.internal.yarn.ports.AMRMClientImpl.java

@Override
public synchronized void start() {
    final YarnConfiguration conf = new YarnConfiguration(getConfig());
    final YarnRPC rpc = YarnRPC.create(conf);
    final InetSocketAddress rmAddress = conf.getSocketAddr(YarnConfiguration.RM_SCHEDULER_ADDRESS,
            YarnConfiguration.DEFAULT_RM_SCHEDULER_ADDRESS, YarnConfiguration.DEFAULT_RM_SCHEDULER_PORT);

    UserGroupInformation currentUser;/* w w  w  . j av a  2 s.  co  m*/
    try {
        currentUser = UserGroupInformation.getCurrentUser();
    } catch (IOException e) {
        throw new YarnException(e);
    }

    if (UserGroupInformation.isSecurityEnabled()) {
        String tokenURLEncodedStr = System.getenv().get(ApplicationConstants.APPLICATION_MASTER_TOKEN_ENV_NAME);
        Token<? extends TokenIdentifier> token = new Token<TokenIdentifier>();

        try {
            token.decodeFromUrlString(tokenURLEncodedStr);
        } catch (IOException e) {
            throw new YarnException(e);
        }

        SecurityUtil.setTokenService(token, rmAddress);
        if (LOG.isDebugEnabled()) {
            LOG.debug("AppMasterToken is " + token);
        }
        currentUser.addToken(token);
    }

    rmClient = currentUser.doAs(new PrivilegedAction<AMRMProtocol>() {
        @Override
        public AMRMProtocol run() {
            return (AMRMProtocol) rpc.getProxy(AMRMProtocol.class, rmAddress, conf);
        }
    });
    LOG.debug("Connecting to ResourceManager at " + rmAddress);
    super.start();
}

From source file:SecuritySupport.java

ClassLoader getSystemClassLoader() {
    return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            ClassLoader cl = null;
            try {
                cl = ClassLoader.getSystemClassLoader();
            } catch (SecurityException ex) {
            }// www .java 2  s .  c om
            return cl;
        }
    });
}

From source file:org.apache.tajo.master.rm.YarnTajoResourceManager.java

@Override
public void init(Configuration conf) {
    this.conf = conf;
    connectYarnClient();/*from   w w w  .  ja va2s  . c om*/

    final YarnConfiguration yarnConf = new YarnConfiguration(conf);
    final YarnRPC rpc = YarnRPC.create(conf);
    final InetSocketAddress rmAddress = conf.getSocketAddr(YarnConfiguration.RM_SCHEDULER_ADDRESS,
            YarnConfiguration.DEFAULT_RM_SCHEDULER_ADDRESS, YarnConfiguration.DEFAULT_RM_SCHEDULER_PORT);

    UserGroupInformation currentUser;
    try {
        currentUser = UserGroupInformation.getCurrentUser();
    } catch (IOException e) {
        throw new YarnRuntimeException(e);
    }

    rmClient = currentUser.doAs(new PrivilegedAction<ApplicationMasterProtocol>() {
        @Override
        public ApplicationMasterProtocol run() {
            return (ApplicationMasterProtocol) rpc.getProxy(ApplicationMasterProtocol.class, rmAddress,
                    yarnConf);
        }
    });
}

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

@Override
public BundleManagerRemote getBundleManager() {
    return AccessController.doPrivileged(new PrivilegedAction<BundleManagerRemote>() {
        @Override/*from  w  ww  .  j a va  2 s.c  o  m*/
        public BundleManagerRemote run() {
            return AccessController.doPrivileged(new PrivilegedAction<BundleManagerRemote>() {
                @Override
                public BundleManagerRemote run() {
                    return getProxy(LookupUtil.getBundleManager(), BundleManagerRemote.class);
                }
            });
        }
    });
}

From source file:org.apache.hadoop.yarn.client.GroupMembershipProxyService.java

private void updateFromConfigFile() {
    int tries = 0;
    while (tries < rmServiceIds.length) {
        currentProxyIndex = (currentProxyIndex + 1) % rmServiceIds.length;
        conf.set(YarnConfiguration.RM_HA_ID, rmServiceIds[currentProxyIndex]);
        try {//from w w  w .ja va 2  s .co m
            LOG.info("connecting to " + rmServiceIds[currentProxyIndex]);
            final InetSocketAddress rmAddress = rmProxy.getRMAddress(conf, protocol);
            UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
            if (ugi.getRealUser() != null) {
                ugi = ugi.getRealUser();
            }
            LiveRMsResponse response = ugi.doAs(new PrivilegedAction<LiveRMsResponse>() {
                @Override
                public LiveRMsResponse run() {
                    try {
                        GroupMembership proxy = oldProxies.get(rmAddress);
                        if (proxy == null) {
                            proxy = RMProxy.getProxy(conf, protocol, rmAddress);
                            oldProxies.put(rmAddress, proxy);
                        }
                        return (LiveRMsResponse) proxy.getLiveRMList();
                    } catch (IOException ex) {
                        LOG.warn(ex, ex);
                    } catch (YarnException ex) {
                        LOG.warn(ex, ex);
                    }
                    return null;
                }
            });
            if (response == null) {
                LOG.info("Unable to create proxy to the ResourceManager " + rmServiceIds[currentProxyIndex]);
                anList = null;
                tries++;
                continue;
            }
            LOG.debug("create proxy to the ResourceManager " + rmServiceIds[currentProxyIndex]);
            anList = response.getLiveRMsList();
            return;
        } catch (IOException e) {
            LOG.error(e, e);
        }
    }
}

From source file:org.apache.axis.AxisProperties.java

public static Object newInstance(final Class spiClass, final Class constructorParamTypes[],
        final Object constructorParams[]) {
    return AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            ResourceClassIterator services = getResourceClassIterator(spiClass);

            Object obj = null;// w w w .j a  va 2s  .  c om
            while (obj == null && services.hasNext()) {
                Class service = services.nextResourceClass().loadClass();

                /* service == null
                 * if class resource wasn't loadable
                 */
                if (service != null) {
                    /* OK, class loaded.. attempt to instantiate it.
                     */
                    try {
                        ClassUtils.verifyAncestory(spiClass, service);
                        obj = ClassUtils.newInstance(service, constructorParamTypes, constructorParams);
                    } catch (InvocationTargetException e) {
                        if (e.getTargetException() instanceof java.lang.NoClassDefFoundError) {
                            log.debug(Messages.getMessage("exception00"), e);
                        } else {
                            log.warn(Messages.getMessage("exception00"), e);
                        }
                    } catch (Exception e) {
                        log.warn(Messages.getMessage("exception00"), e);
                    }
                }
            }

            return obj;
        }
    });
}