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:io.syndesis.maven.ExtractConnectorDescriptorsMojo.java

private URLClassLoader createClassLoader(File jar) throws MalformedURLException {
    return AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {
        public URLClassLoader run() {
            try {
                return new URLClassLoader(new URL[] { jar.toURI().toURL() });
            } catch (MalformedURLException e) {
                return null;
            }//from w  w w  . jav  a 2  s.  c o m
        }
    });
}

From source file:org.apache.ranger.admin.client.RangerAdminJersey2RESTClient.java

@Override
public ServicePolicies getServicePoliciesIfUpdated(final long lastKnownVersion,
        final long lastActivationTimeInMillis) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> RangerAdminJersey2RESTClient.getServicePoliciesIfUpdated(" + lastKnownVersion + ", "
                + lastActivationTimeInMillis + ")");
    }//from w w  w.  j  a v  a 2  s .  c om

    UserGroupInformation user = MiscUtil.getUGILoginUser();
    boolean isSecureMode = user != null && UserGroupInformation.isSecurityEnabled();

    String url = null;
    try {
        ServicePolicies servicePolicies = null;
        Response response = null;
        if (isSecureMode) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Checking Service policy if updated as user : " + user);
            }
            url = _utils.getSecureUrlForPolicyUpdate(_baseUrl, _serviceName);
            final String secureUrl = url;
            PrivilegedAction<Response> action = new PrivilegedAction<Response>() {
                public Response run() {
                    return _client.target(secureUrl)
                            .queryParam(RangerRESTUtils.REST_PARAM_LAST_KNOWN_POLICY_VERSION,
                                    Long.toString(lastKnownVersion))
                            .queryParam(RangerRESTUtils.REST_PARAM_PLUGIN_ID, _pluginId)
                            .request(MediaType.APPLICATION_JSON_TYPE).get();
                };
            };
            response = user.doAs(action);
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Checking Service policy if updated with old api call");
            }
            url = _utils.getUrlForPolicyUpdate(_baseUrl, _serviceName);
            response = _client.target(url)
                    .queryParam(RangerRESTUtils.REST_PARAM_LAST_KNOWN_POLICY_VERSION,
                            Long.toString(lastKnownVersion))
                    .queryParam(RangerRESTUtils.REST_PARAM_PLUGIN_ID, _pluginId)
                    .request(MediaType.APPLICATION_JSON_TYPE).get();
        }

        int httpResponseCode = response == null ? -1 : response.getStatus();
        String body = null;

        switch (httpResponseCode) {
        case 200:
            body = response.readEntity(String.class);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Response from 200 server: " + body);
            }

            Gson gson = getGson();
            servicePolicies = gson.fromJson(body, ServicePolicies.class);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Deserialized response to: " + servicePolicies);
            }
            break;
        case 304:
            LOG.debug("Got response: 304. Ok. Returning null");
            break;
        case -1:
            LOG.warn(
                    "Unexpected: Null response from policy server while trying to get policies! Returning null!");
            break;
        default:
            body = response.readEntity(String.class);
            LOG.warn(String.format("Unexpected: Received status[%d] with body[%s] form url[%s]",
                    httpResponseCode, body, url));
            break;
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("<== RangerAdminJersey2RESTClient.getServicePoliciesIfUpdated(" + lastKnownVersion + ", "
                    + lastActivationTimeInMillis + "): " + servicePolicies);
        }
        return servicePolicies;
    } catch (Exception ex) {
        LOG.error("Failed getting policies from server. url=" + url + ", pluginId=" + _pluginId
                + ", lastKnownVersion=" + lastKnownVersion + ", " + lastActivationTimeInMillis);
        throw ex;
    }
}

From source file:com.ideabase.repository.core.service.UserServiceImpl.java

/**
 * {@inheritDoc}/* w  ww  . j av  a  2 s  .com*/
 */
public boolean isAllowed(final Subject pSubject, final Permission pPermission) {
    final SecurityManager securityManager;
    if (System.getSecurityManager() == null) {
        mLog.debug("No predefined security manager found.");
        securityManager = new SecurityManager();
    } else {
        securityManager = System.getSecurityManager();
    }

    try {
        mLog.debug("Do as privileged action.");
        Subject.doAsPrivileged(pSubject, new PrivilegedAction() {
            public Object run() {
                securityManager.checkPermission(pPermission);
                return null;
            }
        }, null);
        mLog.debug("user action is previleged.");
        return true;
    } catch (RuntimeException e) {
        // No logging here, because, if exception raised it refers to permission
        // failure.
        mLog.warn("Exception raised during verifying the authorization", e);
        return false;
    }
}

From source file:org.apache.ranger.hbase.client.HBaseClient.java

public boolean getHBaseStatus() {
    boolean hbaseStatus = false;
    subj = getLoginSubject();//  w  ww .  j  a  v a2s. c  om
    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 xa_portal.log for more info.";
    if (subj != null) {
        ClassLoader prevCl = Thread.currentThread().getContextClassLoader();
        try {
            Thread.currentThread().setContextClassLoader(getConfigHolder().getClassLoader());

            hbaseStatus = Subject.doAs(subj, new PrivilegedAction<Boolean>() {
                @Override
                public Boolean run() {
                    Boolean hbaseStatus1 = false;
                    try {
                        LOG.info("getHBaseStatus: creating default Hbase configuration");
                        Configuration conf = HBaseConfiguration.create();
                        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);
                        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);
                        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);
                        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);
                        throw hdpException;

                    } catch (Throwable e) {
                        String msgDesc = "getHBaseStatus: Unable to check availability of"
                                + " Hbase environment [" + getConfigHolder().getDatasourceName() + "].";
                        LOG.error(msgDesc);
                        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, "
                    + "current thread might not be able set the context ClassLoader.";
            HadoopException hdpException = new HadoopException(msgDesc, se);
            hdpException.generateResponseDataMap(false, getMessage(se), msgDesc + errMsg, null, null);
            throw hdpException;
        } finally {
            Thread.currentThread().setContextClassLoader(prevCl);
        }
    } else {
        LOG.error("getHBaseStatus: secure login not done, subject is null");
    }

    return hbaseStatus;
}

From source file:SecuritySupport.java

ClassLoader getContextClassLoader() {
    return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            ClassLoader cl = null;
            try {
                cl = Thread.currentThread().getContextClassLoader();
            } catch (SecurityException ex) {
            }/*w w  w  .  j  a v a  2s .c om*/
            return cl;
        }
    });
}

From source file:com.googlecode.jsonschema2pojo.ant.Jsonschema2PojoTask.java

/**
 * Build a classloader using the additional elements specified in
 * <code>classpath</code> and <code>classpathRef</code>.
 * /*from   ww  w  .ja va  2s .c  om*/
 * @return a new classloader that includes the extra path elements found in
 *         the <code>classpath</code> and <code>classpathRef</code> config
 *         values
 */
private ClassLoader buildExtendedClassloader() {
    final List<URL> classpathUrls = new ArrayList<URL>();
    for (String pathElement : getClasspath().list()) {
        try {
            classpathUrls.add(new File(pathElement).toURI().toURL());
        } catch (MalformedURLException e) {
            throw new BuildException(
                    "Unable to use classpath entry as it could not be understood as a valid URL: "
                            + pathElement,
                    e);
        }
    }

    final ClassLoader parentClassloader = Thread.currentThread().getContextClassLoader();

    return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
        @Override
        public ClassLoader run() {
            return new URLClassLoader(classpathUrls.toArray(new URL[classpathUrls.size()]), parentClassloader);
        }
    });
}

From source file:org.eclipse.gemini.blueprint.extender.internal.blueprint.event.EventAdminDispatcher.java

public void afterRefresh(final BlueprintEvent event) {
    if (dispatcher != null) {
        try {// w  w  w  .j  a v a2 s .c  o m
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged(new PrivilegedAction<Object>() {
                    public Object run() {
                        dispatcher.afterRefresh(event);
                        return null;
                    }
                });
            } else {
                dispatcher.afterRefresh(event);
            }
        } catch (Throwable th) {
            log.warn("Cannot dispatch event " + event, th);
        }
    }
}

From source file:Main.java

/**
 * Writes a DOM document to a stream. The precise output format is not
 * guaranteed but this method will attempt to indent it sensibly.
 *
 * <p class="nonnormative"><b>Important</b>: There might be some problems
 * with <code>&lt;![CDATA[ ]]&gt;</code> sections in the DOM tree you pass
 * into this method. Specifically, some CDATA sections my not be written as
 * CDATA section or may be merged with other CDATA section at the same
 * level. Also if plain text nodes are mixed with CDATA sections at the same
 * level all text is likely to end up in one big CDATA section.
 * <br>/*from   w  w  w . j ava2s  .  c  om*/
 * For nodes that only have one CDATA section this method should work fine.
 * </p>
 *
 * @param doc DOM document to be written
 * @param out data sink
 * @param enc XML-defined encoding name (for example, "UTF-8")
 * @throws IOException if JAXP fails or the stream cannot be written to
 */
public static void write(Document doc, OutputStream out, String enc) throws IOException {
    if (enc == null) {
        throw new NullPointerException(
                "You must set an encoding; use \"UTF-8\" unless you have a good reason not to!"); // NOI18N
    }
    Document doc2 = normalize(doc);
    ClassLoader orig = Thread.currentThread().getContextClassLoader();
    Thread.currentThread()
            .setContextClassLoader(AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { // #195921
                @Override
                public ClassLoader run() {
                    return new ClassLoader(ClassLoader.getSystemClassLoader().getParent()) {
                        @Override
                        public InputStream getResourceAsStream(String name) {
                            if (name.startsWith("META-INF/services/")) {
                                return new ByteArrayInputStream(new byte[0]); // JAXP #6723276
                            }
                            return super.getResourceAsStream(name);
                        }
                    };
                }
            }));
    try {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer(new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT)));
        DocumentType dt = doc2.getDoctype();
        if (dt != null) {
            String pub = dt.getPublicId();
            if (pub != null) {
                t.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, pub);
            }
            String sys = dt.getSystemId();
            if (sys != null) {
                t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, sys);
            }
        }
        t.setOutputProperty(OutputKeys.ENCODING, enc);
        try {
            t.setOutputProperty(ORACLE_IS_STANDALONE, "yes");
        } catch (IllegalArgumentException x) {
            // fine, introduced in JDK 7u4
        }

        // See #123816
        Set<String> cdataQNames = new HashSet<String>();
        collectCDATASections(doc2, cdataQNames);
        if (cdataQNames.size() > 0) {
            StringBuilder cdataSections = new StringBuilder();
            for (String s : cdataQNames) {
                cdataSections.append(s).append(' '); //NOI18N
            }
            t.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, cdataSections.toString());
        }

        Source source = new DOMSource(doc2);
        Result result = new StreamResult(out);
        t.transform(source, result);
    } catch (javax.xml.transform.TransformerException | RuntimeException e) { // catch anything that happens
        throw new IOException(e);
    } finally {
        Thread.currentThread().setContextClassLoader(orig);
    }
}

From source file:org.geotoolkit.index.tree.manager.postgres.LucenePostgresSQLTreeEltMapper.java

/**
 * Obtain the Thread Context ClassLoader.
 *//* ww w .  java 2 s  . c  om*/
private static ClassLoader getContextClassLoader() {
    return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
        @Override
        public ClassLoader run() {
            return Thread.currentThread().getContextClassLoader();
        }
    });
}

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

@Override
public AvailabilityManagerRemote getAvailabilityManager() {
    return AccessController.doPrivileged(new PrivilegedAction<AvailabilityManagerRemote>() {
        @Override//from w  w  w. ja  va2 s  .  c  om
        public AvailabilityManagerRemote run() {
            return getProxy(LookupUtil.getAvailabilityManager(), AvailabilityManagerRemote.class);
        }
    });
}