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

private ClassLoader getThreadClassLoader() {
    return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return Thread.currentThread().getContextClassLoader();
        }//from   ww w  .j a v  a2  s .  com
    });
}

From source file:com.openkm.jcr.JCRUtils.java

/**
 * Get JCR Session/*from   w w w  .j av  a2  s .co m*/
 */
public static Session getSession()
        throws javax.jcr.LoginException, javax.jcr.RepositoryException, DatabaseException {
    Object obj = null;

    try {
        InitialContext ctx = new InitialContext();
        Subject subject = (Subject) ctx.lookup("java:comp/env/security/subject");
        obj = Subject.doAs(subject, new PrivilegedAction<Object>() {
            public Object run() {
                Session s = null;

                try {
                    s = DirectRepositoryModule.getRepository().login();
                } catch (javax.jcr.LoginException e) {
                    return e;
                } catch (javax.jcr.RepositoryException e) {
                    return e;
                }

                return s;
            }
        });
    } catch (NamingException e) {
        throw new javax.jcr.LoginException(e.getMessage());
    }

    if (obj instanceof javax.jcr.LoginException) {
        throw (javax.jcr.LoginException) obj;
    } else if (obj instanceof javax.jcr.RepositoryException) {
        throw (javax.jcr.LoginException) obj;
    } else if (obj instanceof javax.jcr.Session) {
        Session session = (javax.jcr.Session) obj;
        log.debug("#{} - {} Create session {} from {}", new Object[] { ++sessionCreationCount, ++activeSessions,
                session, StackTraceUtils.whoCalledMe() });
        DirectAuthModule.loadUserData(session);
        return session;
    } else {
        return null;
    }
}

From source file:org.apache.axis2.jaxws.description.impl.EndpointDescriptionImpl.java

EndpointDescriptionImpl(Class theClass, QName portName, boolean dynamicPort, ServiceDescriptionImpl parent,
        DescriptionBuilderComposite sparseComposite, Object sparseCompositeKey) {

    if (log.isDebugEnabled()) {
        log.debug("entry ");
        log.debug("  theClass=" + theClass);
        log.debug("  portName= " + portName);
        log.debug("  dynamicPort= " + dynamicPort);
        log.debug("  parent=" + parent);
        log.debug("  sparseComposite=" + DescriptionUtils.dumpString(sparseComposite));
    }//  ww  w.j a v  a  2s.  co m

    this.axisConfig = parent.getAxisConfigContext().getAxisConfiguration();

    this.parentServiceDescription = parent;
    composite = new DescriptionBuilderComposite();
    composite.setSparseComposite(sparseCompositeKey, sparseComposite);
    composite.setCorrespondingClass(theClass);
    ClassLoader loader = (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return this.getClass().getClassLoader();
        }
    });
    composite.setClassLoader(loader);
    composite.setIsServiceProvider(false);

    webServiceAnnotation = composite.getWebServiceAnnot();

    this.isDynamicPort = dynamicPort;
    if (DescriptionUtils.isEmpty(portName)) {
        // If the port name is null, then per JAX-WS 2.0 spec p. 55, the runtime is responsible for selecting the port.
        this.portQName = selectPortToUse();
    } else {
        this.portQName = portName;
    }
    // At this point, there must be a port QName set, either as passed in, or determined from the WSDL and/or annotations.
    // If not, that is an error.
    if (this.portQName == null) {
        String msg = Messages.getMessage("endpointDescriptionErr1", theClass.getName(),
                parent.getClass().getName());
        throw ExceptionFactory.makeWebServiceException(msg);
    }

    setupAxisService(sparseCompositeKey);
    addToAxisService();
    setupReleaseResources(getServiceDescription().getAxisConfigContext());

    buildDescriptionHierachy();
    addAnonymousAxisOperations();

    // This will set the serviceClient field after adding the AxisService to the AxisConfig
    getServiceClient();
    // Give the configuration builder a chance to finalize configuration for this service
    try {
        getServiceDescriptionImpl().getClientConfigurationFactory().completeAxis2Configuration(axisService);
    } catch (Exception e) {
        String msg = Messages.getMessage("endpointDescriptionErr2", e.getClass().getName(),
                parent.getClass().getName());
        throw ExceptionFactory.makeWebServiceException(msg, e);
    } finally {
        releaseAxisServiceResources();
    }
    if (log.isDebugEnabled()) {
        log.debug("exit");
    }
}

From source file:org.apache.flink.yarn.appMaster.ApplicationMaster.java

public static void main(String[] args) throws Exception {
    // execute Application Master using the client's user
    final String yarnClientUsername = System.getenv(Client.ENV_CLIENT_USERNAME);
    LOG.info("YARN daemon runs as '" + UserGroupInformation.getCurrentUser().getShortUserName() + "' setting"
            + " user to execute Flink ApplicationMaster/JobManager to '" + yarnClientUsername + "'");
    UserGroupInformation ugi = UserGroupInformation.createRemoteUser(yarnClientUsername);
    for (Token<? extends TokenIdentifier> toks : UserGroupInformation.getCurrentUser().getTokens()) {
        ugi.addToken(toks);/*from   w w w.  j a  v  a2s  .  c  om*/
    }
    ugi.doAs(new PrivilegedAction<Object>() {
        @Override
        public Object run() {
            AMRMClient<ContainerRequest> rmClient = null;
            ApplicationMaster am = null;
            try {
                Configuration conf = Utils.initializeYarnConfiguration();
                rmClient = AMRMClient.createAMRMClient();
                rmClient.init(conf);
                rmClient.start();

                // run the actual Application Master
                am = new ApplicationMaster(conf);
                am.generateConfigurationFile();
                am.startJobManager();
                am.setRMClient(rmClient);
                am.run();
            } catch (Throwable e) {
                LOG.fatal("Error while running the application master", e);
                // the AM is not available. Report error through the unregister function.
                if (rmClient != null && am == null) {
                    try {
                        rmClient.unregisterApplicationMaster(FinalApplicationStatus.FAILED,
                                "Flink YARN Application master" + " stopped unexpectedly with an exception.\n"
                                        + StringUtils.stringifyException(e),
                                "");
                    } catch (Exception e1) {
                        LOG.fatal("Unable to fail the application master", e1);
                    }
                    LOG.info("AM unregistered from RM");
                    return null;
                }
                if (rmClient == null) {
                    LOG.fatal("Unable to unregister AM since the RM client is not available");
                }
                if (am != null) {
                    LOG.info("Writing error into internal message system");
                    am.setFailed(true);
                    am.addMessage(new Message("The application master failed with an exception:\n"
                            + StringUtils.stringifyException(e)));
                    am.keepRPCAlive();
                }
            }
            return null;
        }
    });
}

From source file:org.kitesdk.spring.hbase.example.service.WebPageSnapshotService.java

/**
 * Get the WebPageSnapshotModel from HBase
 *
 * @param url The URL of the WebPageSnapshotModel
 * @param ts The snapshot timestamp of the WebPageSnapshotModel
 * @return The WebPageSnapshotModel, or null if there is no snapshot for the
 * URL at this timestamp.// w  w  w.j a  v  a 2s .  c  o  m
 */
private WebPageSnapshotModel getWebPageSnapshot(String url, final long ts, final String user)
        throws IOException {
    WebPageSnapshotModel snapshot = null;
    final String normalizedUrl = normalizeUrl(url, user);

    UserGroupInformation ugi = UserGroupInformation.createProxyUser(user, UserGroupInformation.getLoginUser());
    snapshot = ugi.doAs(new PrivilegedAction<WebPageSnapshotModel>() {

        @Override
        public WebPageSnapshotModel run() {
            Key key = new Key.Builder(webPageSnapshotModels(user)).add("url", normalizedUrl)
                    .add("fetchedAtRevTs", Long.MAX_VALUE - ts).build();
            return webPageSnapshotModels(user).get(key);
        }
    });

    return snapshot;
}

From source file:org.apache.axis2.jaxws.util.WSDL4JWrapper.java

private URL getAbsoluteURL(final ClassLoader classLoader, final String filePath) {
    URL url = (URL) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return classLoader.getResource(filePath);
        }//from w ww .  ja  v  a  2s  . co m
    });
    if (url == null) {
        if (log.isDebugEnabled()) {
            log.debug("Could not get URL from classloader. Looking in a jar.");
        }
        if (classLoader instanceof URLClassLoader) {
            final URLClassLoader urlLoader = (URLClassLoader) classLoader;

            url = (URL) AccessController.doPrivileged(new PrivilegedAction() {
                public Object run() {
                    return (getURLFromJAR(urlLoader, wsdlURL));
                }
            });

        } else {
            final URLClassLoader nestedLoader = (URLClassLoader) getNestedClassLoader(URLClassLoader.class,
                    classLoader);
            if (nestedLoader != null) {
                url = (URL) AccessController.doPrivileged(new PrivilegedAction() {
                    public Object run() {
                        return (getURLFromJAR(nestedLoader, wsdlURL));
                    }
                });
            }
        }
    }
    return url;
}

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

public Object findAttribute(final String name) {
    if (SecurityUtil.isPackageProtectionEnabled()) {
        return AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                if (name == null) {
                    throw new NullPointerException(Localizer.getMessage("jsp.error.attribute.null_name"));
                }/*from w  ww  . ja v  a  2  s  .c o  m*/

                return doFindAttribute(name);
            }
        });
    } else {
        if (name == null) {
            throw new NullPointerException(Localizer.getMessage("jsp.error.attribute.null_name"));
        }

        return doFindAttribute(name);
    }
}

From source file:org.jwebsocket.plugins.scripting.ScriptingPlugIn.java

private void execAppBeforeLoadChecks(final String aAppName, String aAppPath) throws Exception {
    // parsing app manifest
    File lManifestFile = new File(aAppPath + "/manifest.json");
    if (!lManifestFile.exists() || !lManifestFile.canRead()) {
        String lMsg = "Unable to load '" + aAppName + "' application. Manifest file no found!";
        mLog.error(lMsg);// ww  w  .  j  a va 2  s.co  m
        throw new FileNotFoundException(lMsg);
    }
    // parsing app manifest file
    ObjectMapper lMapper = new ObjectMapper();
    Map<String, Object> lTree = lMapper.readValue(lManifestFile, Map.class);
    Token lManifestJSON = TokenFactory.createToken();
    lManifestJSON.setMap(lTree);

    // getting script language extension
    String lExt = lManifestJSON.getString(Manifest.LANGUAGE_EXT, "js");

    // checking jWebSocket version 
    Manifest.checkJwsVersion(lManifestJSON.getString(Manifest.JWEBSOCKET_VERSION, "1.0.0"));

    // checking jWebSocket plug-ins dependencies
    Manifest.checkJwsDependencies(
            lManifestJSON.getList(Manifest.JWEBSOCKET_PLUGINS_DEPENDENCIES, new ArrayList<String>()));

    // checking sandbox permissions dependency
    Manifest.checkPermissions(lManifestJSON.getList(Manifest.PERMISSIONS, new ArrayList()),
            mSettings.getAppPermissions(aAppName, aAppPath), aAppPath);

    // validating bootstrap file
    final File lBootstrap = new File(aAppPath + "/App." + lExt);
    if (!lBootstrap.exists() || !lBootstrap.canRead()) {
        String lMsg = "Unable to load '" + aAppName + "' application. Bootstrap file not found!";
        mLog.error(lMsg);
        throw new FileNotFoundException(lMsg);
    }

    LocalLoader lClassLoader = new LocalLoader((URLClassLoader) ClassLoader.getSystemClassLoader());
    ScriptEngineManager lManager = new ScriptEngineManager(lClassLoader);

    final ScriptEngine lScriptApp;
    final BaseScriptApp lApp;
    if ("js".equals(lExt)) {
        // making "nashorn" the default engine for JavaScript
        if (null != lManager.getEngineByName("nashorn")) {
            lScriptApp = lManager.getEngineByName("nashorn");
        } else {
            lScriptApp = lManager.getEngineByExtension(lExt);
        }
    } else {
        lScriptApp = lManager.getEngineByExtension(lExt);
    }

    // creating the high level script app instance
    if ("js".equals(lExt)) {
        lApp = new JavaScriptApp(this, aAppName, aAppPath, lScriptApp, lClassLoader);
    } else {
        String lMsg = "The extension '" + lExt + "' is not currently supported!";
        mLog.error(lMsg);
        throw new Exception(lMsg);
    }

    // loading application into security sandbox
    Tools.doPrivileged(mSettings.getAppPermissions(aAppName, aAppPath), new PrivilegedAction<Object>() {
        @Override
        public Object run() {
            try {
                // evaluating app content
                lScriptApp.eval(FileUtils.readFileToString(lBootstrap));
                return null;
            } catch (Exception lEx) {
                String lAction = (mApps.containsKey(aAppName)) ? "reloaded" : "loaded";
                String lMsg = "Script applicaton '" + aAppName + "' not " + lAction
                        + " because it failed the 'before-load' checks: " + lEx.getMessage();
                mLog.info(lMsg);
                throw new RuntimeException(lMsg);
            }
        }
    });

    if (mLog.isDebugEnabled()) {
        mLog.debug(aAppName + "(" + lExt + ") application passed the 'before-load' checks successfully!");
    }
}

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

@Override
public ServiceTags getServiceTagsIfUpdated(final long lastKnownVersion, final long lastActivationTimeInMillis)
        throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> RangerAdminRESTClient.getServiceTagsIfUpdated(" + lastKnownVersion + ", "
                + lastActivationTimeInMillis + "): ");
    }/*w w w .ja  va 2s.co m*/

    ServiceTags ret = null;
    ClientResponse response = null;
    WebResource webResource = null;
    UserGroupInformation user = MiscUtil.getUGILoginUser();
    boolean isSecureMode = user != null && UserGroupInformation.isSecurityEnabled();

    if (isSecureMode) {
        PrivilegedAction<ClientResponse> action = new PrivilegedAction<ClientResponse>() {
            public ClientResponse run() {
                WebResource secureWebResource = createWebResource(
                        RangerRESTUtils.REST_URL_GET_SECURE_SERVICE_TAGS_IF_UPDATED + serviceName)
                                .queryParam(RangerRESTUtils.LAST_KNOWN_TAG_VERSION_PARAM,
                                        Long.toString(lastKnownVersion))
                                .queryParam(RangerRESTUtils.REST_PARAM_LAST_ACTIVATION_TIME,
                                        Long.toString(lastActivationTimeInMillis))
                                .queryParam(RangerRESTUtils.REST_PARAM_PLUGIN_ID, pluginId);
                return secureWebResource.accept(RangerRESTUtils.REST_MIME_TYPE_JSON).get(ClientResponse.class);
            };
        };
        if (LOG.isDebugEnabled()) {
            LOG.debug("getServiceTagsIfUpdated as user " + user);
        }
        response = user.doAs(action);
    } else {
        webResource = createWebResource(RangerRESTUtils.REST_URL_GET_SERVICE_TAGS_IF_UPDATED + serviceName)
                .queryParam(RangerRESTUtils.LAST_KNOWN_TAG_VERSION_PARAM, Long.toString(lastKnownVersion))
                .queryParam(RangerRESTUtils.REST_PARAM_LAST_ACTIVATION_TIME,
                        Long.toString(lastActivationTimeInMillis))
                .queryParam(RangerRESTUtils.REST_PARAM_PLUGIN_ID, pluginId);
        response = webResource.accept(RangerRESTUtils.REST_MIME_TYPE_JSON).get(ClientResponse.class);
    }

    if (response != null && response.getStatus() == 200) {
        ret = response.getEntity(ServiceTags.class);
    } else if (!(response != null && response.getStatus() == 304)) {
        RESTResponse resp = RESTResponse.fromClientResponse(response);
        LOG.error("Error getting taggedResources. secureMode=" + isSecureMode + ", user=" + user + ", response="
                + resp.toString() + ", serviceName=" + serviceName + ", " + "lastKnownVersion="
                + lastKnownVersion + ", " + "lastActivationTimeInMillis=" + lastActivationTimeInMillis);
        throw new Exception(resp.getMessage());
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== RangerAdminRESTClient.getServiceTagsIfUpdated(" + lastKnownVersion + ", "
                + lastActivationTimeInMillis + "): ");
    }

    return ret;
}

From source file:Classes.java

/**
 * Get a system property//w  ww  .ja v a2s. c o m
 * 
 * @param name
 *          the property name
 * @param defaultValue
 *          the default value
 */
private static String getProperty(final String name, final String defaultValue) {
    return (String) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return System.getProperty(name, defaultValue);
        }
    });
}