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.tika.parser.pkg.TikaArchiveStreamFactory.java

/**
 * Constructs a new sorted map from input stream provider names to provider
 * objects./*from w w w  .  j a  v  a  2s .co m*/
 *
 * <p>
 * The map returned by this method will have one entry for each provider for
 * which support is available in the current Java virtual machine. If two or
 * more supported provider have the same name then the resulting map will
 * contain just one of them; which one it will contain is not specified.
 * </p>
 *
 * <p>
 * The invocation of this method, and the subsequent use of the resulting
 * map, may cause time-consuming disk or network I/O operations to occur.
 * This method is provided for applications that need to enumerate all of
 * the available providers, for example to allow user provider selection.
 * </p>
 *
 * <p>
 * This method may return different results at different times if new
 * providers are dynamically made available to the current Java virtual
 * machine.
 * </p>
 *
 * @return An immutable, map from names to provider objects
 * @since 1.13
 */
public static SortedMap<String, ArchiveStreamProvider> findAvailableArchiveInputStreamProviders() {
    return AccessController.doPrivileged(new PrivilegedAction<SortedMap<String, ArchiveStreamProvider>>() {
        @Override
        public SortedMap<String, ArchiveStreamProvider> run() {
            TreeMap<String, ArchiveStreamProvider> map = new TreeMap<>();
            putAll(SINGLETON.getInputStreamArchiveNames(), SINGLETON, map);
            for (ArchiveStreamProvider provider : findArchiveStreamProviders()) {
                putAll(provider.getInputStreamArchiveNames(), provider, map);
            }
            return map;
        }
    });
}

From source file:org.apache.openjpa.lib.ant.AbstractTask.java

private MultiClassLoader getConfigPropertiesResourceLoader() {
    MultiClassLoader loader = AccessController.doPrivileged(J2DoPrivHelper.newMultiClassLoaderAction());
    loader.addClassLoader(getClassLoader());
    loader.addClassLoader(AccessController.doPrivileged(J2DoPrivHelper.getClassLoaderAction(_conf.getClass())));
    return loader;
}

From source file:org.keycloak.adapters.cloned.SniSSLSocketFactory.java

private Socket applySNI(final Socket socket, String hostname) {
    if (socket instanceof SSLSocket) {
        try {/*from   w ww. j  a v  a2s  .  c  om*/
            Method setHostMethod = AccessController.doPrivileged(new PrivilegedExceptionAction<Method>() {
                @Override
                public Method run() throws NoSuchMethodException {
                    return socket.getClass().getMethod("setHost", String.class);
                }
            });

            setHostMethod.invoke(socket, hostname);
            LOG.log(Level.FINEST, "Applied SNI to socket for host {0}", hostname);
        } catch (PrivilegedActionException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException e) {
            LOG.log(Level.WARNING, "Failed to apply SNI to SSLSocket", e);
        }
    }
    return socket;
}

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

/**
 * @param cfgFile/*from   w  ww .  j a va2  s .c om*/
 * @return
 */
public static Resource findResource(final String cfgFile) {
    try {
        return AccessController.doPrivileged(new PrivilegedAction<Resource>() {

            @Override
            public Resource run() {
                Resource cpr = new ClassPathResource(cfgFile);
                if (cpr.exists()) {
                    return cpr;
                }
                try {
                    // see if it's a URL
                    URL url = new URL(cfgFile);
                    cpr = new UrlResource(url);
                    if (cpr.exists()) {
                        return cpr;
                    }
                } catch (MalformedURLException e) {
                    // ignore
                }
                // try loading it our way
                URL url = ClassLoaderUtils.getResource(cfgFile, ContainerApplicationContext.class);
                if (url != null) {
                    cpr = new UrlResource(url);
                    if (cpr.exists()) {
                        return cpr;
                    }
                }
                cpr = new FileSystemResource(cfgFile);
                if (cpr.exists()) {
                    return cpr;
                }
                return null;
            }
        });
    } catch (AccessControlException ex) {
        // cannot read the user config file
        return null;
    }
}

From source file:org.apache.axis2.receivers.AbstractMessageReceiver.java

/**
 * Several pieces of information need to be available to the service
 * implementation class.  For one, the ThreadContextClassLoader needs
 * to be correct, and for another we need to give the service code
 * access to the MessageContext (getCurrentContext()).  So we toss these
 * things in TLS./*  w w w .  ja v  a 2 s  . c o  m*/
 *
 * @param msgContext the current MessageContext
 * @return a ThreadContextDescriptor containing the old values
 */
protected ThreadContextDescriptor setThreadContext(final MessageContext msgContext) {
    ThreadContextDescriptor tc = new ThreadContextDescriptor();
    tc.oldMessageContext = (MessageContext) MessageContext.currentMessageContext.get();
    final ClassLoader contextClassLoader = getContextClassLoader_doPriv();
    tc.oldClassLoader = contextClassLoader;

    AxisService service = msgContext.getAxisService();
    String serviceTCCL = (String) service.getParameterValue(Constants.SERVICE_TCCL);
    if (serviceTCCL != null) {
        serviceTCCL = serviceTCCL.trim().toLowerCase();

        if (serviceTCCL.equals(Constants.TCCL_COMPOSITE)) {
            final ClassLoader loader = (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
                public Object run() {
                    return new MultiParentClassLoader(new URL[] {}, new ClassLoader[] {
                            msgContext.getAxisService().getClassLoader(), contextClassLoader });
                }
            });
            org.apache.axis2.java.security.AccessController.doPrivileged(new PrivilegedAction() {
                public Object run() {
                    Thread.currentThread().setContextClassLoader(loader);
                    return null;
                }
            });
        } else if (serviceTCCL.equals(Constants.TCCL_SERVICE)) {
            org.apache.axis2.java.security.AccessController.doPrivileged(new PrivilegedAction() {
                public Object run() {
                    Thread.currentThread().setContextClassLoader(msgContext.getAxisService().getClassLoader());
                    return null;
                }
            });
        }
    }
    MessageContext.setCurrentMessageContext(msgContext);
    return tc;
}

From source file:org.apache.stanbol.commons.sphinx.impl.ModelProviderImpl.java

/**
 * /*w w  w  .  j  ava2 s  .  com*/
 * @param modelDataStream {@link InputStream} of the Model, received from {@link DataFileProvider} Service
 * @param resourceName Model File Name
 * @param path path to copy the @resourceName i.e. /tmp
 * @throws PrivilegedActionException
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private void createTempResource(final InputStream modelDataStream, String resourceName, String path)
        throws PrivilegedActionException {
    final File resource = new File(path + "/" + resourceName);

    AccessController.doPrivileged(new PrivilegedAction() {
        @Override
        public Object run() {
            try {
                FileUtils.copyInputStreamToFile(modelDataStream, resource);
            } catch (IOException e) {
                log.debug("Unable to copy Resource {} to temp", resource.getAbsolutePath());
            }
            return null;
        }
    });
}

From source file:org.apache.openjpa.meta.InterfaceImplGenerator.java

/**
 * Invalidate methods on the interface which are not managed.
 *///from  w  ww  .  j a  v a  2 s.c  om
private void invalidateNonBeanMethods(BCClass bc, Class<?> iface, Set<Method> methods) {
    Method[] meths = (Method[]) AccessController.doPrivileged(J2DoPrivHelper.getDeclaredMethodsAction(iface));
    BCMethod meth;
    Code code;
    Class<?> type = _repos.getMetaDataFactory().getDefaults().getUnimplementedExceptionType();
    for (int i = 0; i < meths.length; i++) {
        if (methods.contains(meths[i]))
            continue;
        meth = bc.declareMethod(meths[i].getName(), meths[i].getReturnType(), meths[i].getParameterTypes());
        meth.makePublic();
        code = meth.getCode(true);
        code.anew().setType(type);
        code.dup();
        code.invokespecial().setMethod(type, "<init>", void.class, null);
        code.athrow();
        code.calculateMaxLocals();
        code.calculateMaxStack();
    }
}

From source file:org.elasticsearch.xpack.security.authc.kerberos.SpnegoHttpClientConfigCallbackHandler.java

/**
 * If logged in {@link LoginContext} is not available, it attempts login and
 * returns {@link LoginContext}//  w  w w .  ja  v  a 2s .co m
 *
 * @return {@link LoginContext}
 * @throws PrivilegedActionException
 */
public synchronized LoginContext login() throws PrivilegedActionException {
    if (this.loginContext == null) {
        AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
            final Subject subject = new Subject(false,
                    Collections.singleton(new KerberosPrincipal(userPrincipalName)), Collections.emptySet(),
                    Collections.emptySet());
            Configuration conf = null;
            final CallbackHandler callback;
            if (password != null) {
                conf = new PasswordJaasConf(userPrincipalName, enableDebugLogs);
                callback = new KrbCallbackHandler(userPrincipalName, password);
            } else {
                conf = new KeytabJaasConf(userPrincipalName, keytabPath, enableDebugLogs);
                callback = null;
            }
            loginContext = new LoginContext(CRED_CONF_NAME, subject, callback, conf);
            loginContext.login();
            return null;
        });
    }
    return loginContext;
}

From source file:org.codice.ddf.commands.solr.SolrCommands.java

protected final String getBackupUrl() {
    return AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getProperty(SOLR_URL_PROP));
}

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

public void grace(final BlueprintEvent event) {
    if (dispatcher != null) {
        try {/*from  ww w  .jav  a 2 s .  c om*/
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged(new PrivilegedAction<Object>() {
                    public Object run() {
                        dispatcher.grace(event);
                        return null;
                    }
                });
            } else {
                dispatcher.grace(event);
            }
        } catch (Throwable th) {
            log.warn("Cannot dispatch event " + event, th);
        }
    }
}