Example usage for java.security AccessController doPrivileged

List of usage examples for java.security AccessController doPrivileged

Introduction

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

Prototype

@CallerSensitive
public static <T> T doPrivileged(PrivilegedExceptionAction<T> action) throws PrivilegedActionException 

Source Link

Document

Performs the specified PrivilegedExceptionAction with privileges enabled.

Usage

From source file:org.apache.servicemix.platform.testing.support.SmxPlatform.java

public void start() throws Exception {
    Set<String> jars = getJars(Felix.class);
    ClassLoader classLoader = new GuardClassLoader(toURLs(jars.toArray(new String[jars.size()])), null);

    BundleActivator activator = new BundleActivator() {
        private ServiceRegistration registration;

        public void start(BundleContext context) {
            registration = context.registerService(MainService.class.getName(), new MainService() {
                public String[] getArgs() {
                    return new String[0];
                }/*w  w  w.j  a v a 2 s. co m*/

                public int getExitCode() {
                    return 0;
                }

                public void setExitCode(int exitCode) {
                }
            }, null);
        }

        public void stop(BundleContext context) {
            registration.unregister();
        }
    };
    List<BundleActivator> activations = new ArrayList<BundleActivator>();
    activations.add(activator);

    Properties props = getConfigurationProperties();
    props.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, activations);

    Thread.currentThread().setContextClassLoader(classLoader);
    Class cl = classLoader.loadClass(Felix.class.getName());
    Constructor cns = cl.getConstructor(Map.class);
    platform = cns.newInstance(props);
    platform.getClass().getMethod("start").invoke(platform);

    Bundle systemBundle = (Bundle) platform;

    // call getBundleContext
    final Method getContext = systemBundle.getClass().getMethod("getBundleContext", null);

    AccessController.doPrivileged(new PrivilegedAction() {

        public Object run() {
            getContext.setAccessible(true);
            return null;
        }
    });
    context = (BundleContext) getContext.invoke(systemBundle, null);
}

From source file:org.apache.openjpa.persistence.AnnotationPersistenceXMLMetaDataParser.java

/**
 * Read annotations for the current type.
 *//*  www .ja va  2  s  . c  om*/
private XMLMetaData parseXMLClassAnnotations(Class<?> cls) {
    // check immediately whether the class has JAXB XML annotations
    if (cls == null || xmlTypeClass == null
            || !((AccessController.doPrivileged(J2DoPrivHelper.isAnnotationPresentAction(cls, xmlTypeClass)))
                    .booleanValue()
                    && (AccessController
                            .doPrivileged(J2DoPrivHelper.isAnnotationPresentAction(cls, xmlRootElementClass)))
                                    .booleanValue()))
        return null;

    // find / create metadata
    XMLMetaData meta = getXMLMetaData(cls);

    return meta;
}

From source file:org.codice.solr.factory.impl.HttpClientBuilder.java

private static KeyStore getKeyStore(String location, String password) {
    LOGGER.debug("Loading keystore from {}", location);
    KeyStore keyStore = null;// w  w w  .j  a  v a 2s  .  com

    try (FileInputStream storeStream = new FileInputStream(location)) {
        keyStore = KeyStore.getInstance(AccessController.doPrivileged(
                (PrivilegedAction<String>) () -> System.getProperty("javax.net.ssl.keyStoreType")));
        keyStore.load(storeStream, password.toCharArray());
    } catch (CertificateException | IOException | NoSuchAlgorithmException | KeyStoreException e) {
        LOGGER.warn("Unable to load keystore at {}", location, e);
    }

    return keyStore;
}

From source file:SecuritySupport.java

ClassLoader getParentClassLoader(final ClassLoader cl) {
    return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            ClassLoader parent = null;
            try {
                parent = cl.getParent();
            } catch (SecurityException ex) {
            }//  ww w.  j a  va 2s  .co  m

            // eliminate loops in case of the boot
            // ClassLoader returning itself as a parent
            return (parent == cl) ? null : parent;
        }
    });
}

From source file:org.eclipse.gemini.blueprint.extender.internal.support.NamespacePlugins.java

public NamespaceHandler resolve(final String namespaceUri) {
    if (System.getSecurityManager() != null) {
        return AccessController.doPrivileged(new PrivilegedAction<NamespaceHandler>() {

            public NamespaceHandler run() {
                return doResolve(namespaceUri);
            }//from   www  .  j  av  a2  s. c  o m
        });

    } else {
        return doResolve(namespaceUri);
    }
}

From source file:org.elasticsearch.hadoop.script.GroovyScriptEngineService.java

@Override
public Object compile(String scriptName, String scriptSource, Map<String, String> params) {
    // Create the script class name
    String className = MessageDigests
            .toHexString(MessageDigests.sha1().digest(scriptSource.getBytes(StandardCharsets.UTF_8)));

    final SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new SpecialPermission());
    }/*from  www. j a  va2  s .  c o  m*/
    return AccessController.doPrivileged(new PrivilegedAction<Object>() {
        @Override
        public Object run() {
            try {
                GroovyCodeSource codeSource = new GroovyCodeSource(scriptSource, className,
                        BootstrapInfo.UNTRUSTED_CODEBASE);
                codeSource.setCachable(false);

                CompilerConfiguration configuration = new CompilerConfiguration()
                        .addCompilationCustomizers(new ImportCustomizer().addStarImports("org.joda.time")
                                .addStaticStars("java.lang.Math"))
                        .addCompilationCustomizers(new GroovyBigDecimalTransformer(CompilePhase.CONVERSION));

                // always enable invokeDynamic, not the crazy softreference-based stuff
                configuration.getOptimizationOptions().put(GROOVY_INDY_SETTING_NAME, true);

                GroovyClassLoader groovyClassLoader = new GroovyClassLoader(loader, configuration);
                return groovyClassLoader.parseClass(codeSource);
            } catch (Exception e) {
                if (log.isTraceEnabled()) {
                    log.trace("Exception compiling Groovy script:", e);
                }
                throw convertToScriptException("Error compiling script " + className, scriptSource, e);
            }
        }
    });
}

From source file:org.eclipse.ecr.runtime.api.login.LoginComponent.java

@Override
public LoginContext loginAs(final String username) throws LoginException {
    // login as system user is a privileged action
    try {//from w w  w. j a  v  a 2s. com
        return AccessController.doPrivileged(new PrivilegedExceptionAction<LoginContext>() {
            @Override
            public LoginContext run() throws LoginException {
                SecurityManager sm = System.getSecurityManager();
                if (sm != null) {
                    sm.checkPermission(new SystemLoginPermission());
                }
                return systemLogin(username);
            }
        });
    } catch (PrivilegedActionException e) {
        throw (LoginException) e.getException();
    }
}

From source file:org.apache.openjpa.lib.util.Files.java

/**
 * Check the given string for a matching file. The string is first
 * tested to see if it is an existing file path. If it does not
 * represent an existing file, it is checked as a resource name of a
 * file. If no resource exists, then it is interpreted as a path
 * to a file that does not exist yet.//from  ww w  . jav a 2 s. co m
 *
 * @param name the file path or resource name
 * @param loader a class loader to use in resource lookup, or null
 * to use the thread's context loader
 */
public static File getFile(String name, ClassLoader loader) {
    if (name == null)
        return null;

    File file = new File(name);
    if ((AccessController.doPrivileged(J2DoPrivHelper.existsAction(file))).booleanValue())
        return file;

    if (loader == null)
        loader = AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction());
    URL url = AccessController.doPrivileged(J2DoPrivHelper.getResourceAction(loader, name));
    if (url != null) {
        String urlFile = url.getFile();
        if (urlFile != null) {
            File rsrc = new File(URLDecoder.decode(urlFile));
            if ((AccessController.doPrivileged(J2DoPrivHelper.existsAction(rsrc))).booleanValue())
                return rsrc;
        }
    }

    // go back to original non-existant file path
    return file;
}

From source file:org.codice.solr.factory.impl.HttpSolrClientFactory.java

private static String getDefaultHttpsAddress() {
    return AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getProperty(SOLR_HTTP_URL));
}

From source file:com.liferay.portal.template.soy.internal.SoyTemplate.java

protected SoyFileSet getSoyFileSet(List<TemplateResource> templateResources) throws Exception {

    SoyFileSet soyFileSet = null;/*from   w  w w  .  ja v a 2 s  . c  o  m*/

    if (_privileged) {
        soyFileSet = AccessController.doPrivileged(new TemplatePrivilegedExceptionAction(templateResources));
    } else {
        Builder builder = SoyFileSet.builder();

        for (TemplateResource templateResource : templateResources) {
            String templateContent = getTemplateContent(templateResource);

            builder.add(templateContent, templateResource.getTemplateId());
        }

        soyFileSet = builder.build();
    }

    return soyFileSet;
}