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.openjpa.meta.InterfaceImplGenerator.java

/**
 * Create a concrete implementation of the given type, possibly
 * returning a cached version of the class.
 *//*from   w  w  w  .j  a va2s  .c o  m*/
public synchronized Class<?> createImpl(ClassMetaData meta) {
    Class<?> iface = meta.getDescribedType();

    // check cache.
    Class<?> impl = _impls.get(iface);
    if (impl != null)
        return impl;

    ClassLoader parentLoader = AccessController.doPrivileged(J2DoPrivHelper.getClassLoaderAction(iface));
    BCClassLoader loader = AccessController
            .doPrivileged(J2DoPrivHelper.newBCClassLoaderAction(_project, parentLoader));
    BCClassLoader enhLoader = AccessController
            .doPrivileged(J2DoPrivHelper.newBCClassLoaderAction(_enhProject, parentLoader));
    BCClass bc = _project.loadClass(getClassName(meta));
    bc.declareInterface(iface);
    ClassMetaData sup = meta.getPCSuperclassMetaData();
    if (sup != null) {
        bc.setSuperclass(sup.getInterfaceImpl());
        enhLoader = AccessController.doPrivileged(J2DoPrivHelper.newBCClassLoaderAction(_enhProject,
                AccessController.doPrivileged(J2DoPrivHelper.getClassLoaderAction(sup.getInterfaceImpl()))));
    }

    FieldMetaData[] fields = meta.getDeclaredFields();
    Set<Method> methods = new HashSet<Method>();
    for (int i = 0; i < fields.length; i++)
        addField(bc, iface, fields[i], methods);
    invalidateNonBeanMethods(bc, iface, methods);

    // first load the base Class<?> as the enhancer requires the class
    // to be available
    try {
        meta.setInterfaceImpl(Class.forName(bc.getName(), true, loader));
    } catch (Throwable t) {
        throw new InternalException(_loc.get("interface-load", iface, loader), t).setFatal(true);
    }
    // copy the BCClass<?> into the enhancer project.
    bc = _enhProject.loadClass(new ByteArrayInputStream(bc.toByteArray()), loader);
    PCEnhancer enhancer = new PCEnhancer(_repos, bc, meta);

    int result = enhancer.run();
    if (result != PCEnhancer.ENHANCE_PC)
        throw new InternalException(_loc.get("interface-badenhance", iface)).setFatal(true);
    try {
        // load the Class<?> for real.
        impl = Class.forName(bc.getName(), true, enhLoader);
    } catch (Throwable t) {
        throw new InternalException(_loc.get("interface-load2", iface, enhLoader), t).setFatal(true);
    }
    // cache the generated impl.
    _impls.put(iface, impl);
    return impl;
}

From source file:org.forgerock.openam.auth.shared.SSOTokenFactory.java

/**
 * Gets a SSOToken for the Super User./*w w  w  .j av a2 s . c o  m*/
 *
 * @return The Admin users SSOToken.
 */
public SSOToken getAdminToken() {
    return AccessController.doPrivileged(AdminTokenAction.getInstance());
}

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

public static void createSolrCore(String url, String coreName, String configFileName,
        CloseableHttpClient httpClient) throws IOException, SolrServerException {

    try (CloseableHttpClient closeableHttpClient = httpClient;
            HttpSolrClient client = (httpClient != null
                    ? new HttpSolrClient.Builder(url).withHttpClient(closeableHttpClient).build()
                    : new HttpSolrClient.Builder(url).build())) {

        HttpResponse ping = client.getHttpClient().execute(new HttpHead(url));
        if (ping != null && ping.getStatusLine().getStatusCode() == 200) {
            ConfigurationFileProxy configProxy = new ConfigurationFileProxy(ConfigurationStore.getInstance());
            configProxy.writeSolrConfiguration(coreName);
            if (!solrCoreExists(client, coreName)) {
                LOGGER.debug("Solr({}): Creating Solr core", coreName);

                String configFile = StringUtils.defaultIfBlank(configFileName, DEFAULT_SOLRCONFIG_XML);
                String solrDir;//from ww  w  . ja v a 2 s .  c o m

                if (AccessController.doPrivileged(
                        (PrivilegedAction<Boolean>) () -> System.getProperty(SOLR_DATA_DIR) != null)) {
                    solrDir = AccessController
                            .doPrivileged((PrivilegedAction<String>) () -> System.getProperty(SOLR_DATA_DIR));
                } else {
                    solrDir = Paths.get(
                            AccessController.doPrivileged(
                                    (PrivilegedAction<String>) () -> System.getProperty("karaf.home")),
                            "data", "solr").toString();
                }

                String instanceDir = Paths.get(solrDir, coreName).toString();

                String dataDir = Paths.get(instanceDir, "data").toString();

                CoreAdminRequest.createCore(coreName, instanceDir, client, configFile, DEFAULT_SCHEMA_XML,
                        dataDir, dataDir);
            } else {
                LOGGER.debug("Solr({}): Solr core already exists; reloading it", coreName);
                CoreAdminRequest.reloadCore(coreName, client);
            }
        } else {
            LOGGER.debug("Solr({}): Unable to ping Solr core at {}", coreName, url);
            throw new SolrServerException("Unable to ping Solr core");
        }
    }
}

From source file:org.beanlet.springframework.impl.SpringHelper.java

public static synchronized ListableBeanFactory getListableBeanFactory(BeanletConfiguration<?> configuration,
        Element element) {/*ww w  .j a v  a  2s .  c om*/
    SpringContext springContext = getSpringContext(configuration, element);
    if (springContext == null) {
        throw new ApplicationContextException("No spring context specified.");
    }
    final ClassLoader loader = configuration.getComponentUnit().getClassLoader();
    Map<SpringContext, ListableBeanFactory> map = factories.get(loader);
    if (map == null) {
        map = new HashMap<SpringContext, ListableBeanFactory>();
        factories.put(loader, map);
    }
    ListableBeanFactory factory = map.get(springContext);
    if (factory == null) {
        ClassLoader org = null;
        try {
            org = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
                public ClassLoader run() {
                    // PERMISSION: java.lang.RuntimePermission getClassLoader
                    ClassLoader org = Thread.currentThread().getContextClassLoader();
                    // PERMISSION: java.lang.RuntimePermission setContextClassLoader
                    Thread.currentThread().setContextClassLoader(loader);
                    return org;
                }
            });
            if (springContext.applicationContext()) {
                factory = new GenericApplicationContext();
            } else {
                factory = new DefaultListableBeanFactory();
            }
            // Do not create spring context in priviliged scope!
            for (SpringResource r : springContext.value()) {
                String path = r.value();
                Resource resource = null;
                BeanDefinitionReader reader = null;
                switch (r.type()) {
                case CLASSPATH:
                    resource = new ClassPathResource(path);
                    break;
                case FILESYSTEM:
                    resource = new FileSystemResource(path);
                    break;
                case URL:
                    resource = new UrlResource(path);
                    break;
                default:
                    assert false : r.type();
                }
                switch (r.format()) {
                case XML:
                    reader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) factory);
                    break;
                case PROPERTIES:
                    reader = new PropertiesBeanDefinitionReader((BeanDefinitionRegistry) factory);
                    break;
                default:
                    assert false : r.format();
                }
                if (resource != null && resource.exists()) {
                    reader.loadBeanDefinitions(resource);
                }
            }
            if (factory instanceof ConfigurableApplicationContext) {
                ((ConfigurableApplicationContext) factory).refresh();
            }
            map.put(springContext, factory);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new ApplicationContextException("Failed to construct spring "
                    + (springContext.applicationContext() ? "application context" : "bean factory") + ".", e);
        } finally {
            final ClassLoader tmp = org;
            AccessController.doPrivileged(new PrivilegedAction<Object>() {
                public Object run() {
                    // PERMISSION: java.lang.RuntimePermission setContextClassLoader
                    Thread.currentThread().setContextClassLoader(tmp);
                    return null;
                }
            });
        }
    }
    return factory;
}

From source file:edu.ku.brc.af.core.db.DBTableIdMgr.java

/**
 * Returns the singleton.// www  . ja v  a 2 s .c om
 * @return the singleton.
 */
public static DBTableIdMgr getInstance() {
    if (instance != null) {
        return instance;
    }

    // else
    String factoryNameStr = AccessController.doPrivileged(new java.security.PrivilegedAction<String>() {
        public String run() {
            return System.getProperty(factoryName);
        }
    });

    if (isNotEmpty(factoryNameStr)) {
        try {
            instance = (DBTableIdMgr) Class.forName(factoryNameStr).newInstance();
            instance.initialize();
            return instance;

        } catch (Exception e) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DBTableIdMgr.class, e);
            InternalError error = new InternalError("Can't instantiate WebLink factory " + factoryNameStr); //$NON-NLS-1$
            error.initCause(e);
            throw error;
        }
    }
    instance = new DBTableIdMgr(true);
    instance.initialize();
    return instance;
}

From source file:org.solmix.runtime.support.spring.SpringContainerFactory.java

/**
 * @param strings/*from   w  w  w  .ja  va2  s.  c o m*/
 * @param includeDefaults
 * @return
 */
public Container createContainer(String[] cfgFiles, boolean includeDefaults) {
    try {
        final Resource r = ContainerApplicationContext
                .findResource(ContainerApplicationContext.DEFAULT_USER_CFG_FILE);
        boolean exists = true;
        if (r != null) {
            exists = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {

                @Override
                public Boolean run() {
                    return r.exists();
                }
            });
        }
        if (parent == null && includeDefaults && (r == null || !exists)) {
            return new ContainerFactoryImpl().createContainer();
        }
        ConfigurableApplicationContext cac = createApplicationContext(cfgFiles, includeDefaults, parent);
        return completeCreating(cac);
    } catch (BeansException ex) {
        throw new java.lang.RuntimeException(ex);
    }
}

From source file:com.kenai.redminenb.repository.RedmineManagerFactoryHelper.java

public static Transport getTransportFromManager(final RedmineManager rm) {
    return AccessController.doPrivileged(new PrivilegedAction<Transport>() {

        @Override/*from   www.j  av a2s.  c om*/
        public Transport run() {
            try {
                Field transportField = RedmineManager.class.getDeclaredField("transport");
                transportField.setAccessible(true);
                return (Transport) transportField.get(rm);
            } catch (NoSuchFieldException | SecurityException | IllegalArgumentException
                    | IllegalAccessException ex) {
                throw new RuntimeException("Failed to get transport from redmine manager", ex);
            }
        }
    });
}

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

public org.apache.http.impl.client.HttpClientBuilder get() {

    final org.apache.http.impl.client.HttpClientBuilder httpClientBuilder = HttpClients.custom()
            .setDefaultCookieStore(new BasicCookieStore()).setMaxConnTotal(128).setMaxConnPerRoute(32);

    if (useTls()) {
        String[] defaultProtocols = AccessController.doPrivileged(
                (PrivilegedAction<String[]>) () -> commaSeparatedToArray(System.getProperty(HTTPS_PROTOCOLS)));

        String[] defaultCipherSuites = AccessController
                .doPrivileged((PrivilegedAction<String[]>) () -> commaSeparatedToArray(
                        System.getProperty(HTTPS_CIPHER_SUITES)));

        httpClientBuilder.setSSLSocketFactory(new SSLConnectionSocketFactory(getSslContext(), defaultProtocols,
                defaultCipherSuites, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER));
    }//from   w  w  w.java  2  s .c  o  m
    if (isConfiguredForBasicAuth()) {
        httpClientBuilder.setDefaultCredentialsProvider(getCredentialsProvider());
        httpClientBuilder.addInterceptorFirst(new PreemptiveAuth(new BasicScheme()));
    }
    return httpClientBuilder;
}

From source file:com.datos.vfs.impl.PrivilegedFileReplicator.java

/**
 * Closes the replicator.//from  w  w  w .j ava  2s.c om
 */
@Override
public void close() {
    if (replicatorComponent != null) {
        AccessController.doPrivileged(new CloseAction());
    }
}

From source file:ja.centre.util.io.nio.MappedByteBufferWrapper.java

private void clean(final MappedByteBuffer buffer) {
    AccessController.doPrivileged(new PrivilegedAction<Object>() {
        public Object run() {
            try {
                Method cleanerMethod = buffer.getClass().getMethod("cleaner");
                cleanerMethod.setAccessible(true);
                sun.misc.Cleaner cleaner = (sun.misc.Cleaner) cleanerMethod.invoke(buffer);
                cleaner.clean();/*from w  ww  .  j  a v  a  2  s  .  com*/
            } catch (IllegalAccessException e) {
                States.shouldNeverReachHere(e);
            } catch (NoSuchMethodException e) {
                States.shouldNeverReachHere(e);
            } catch (InvocationTargetException e) {
                States.shouldNeverReachHere(e);
            }
            return null;
        }
    });
}