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:com.tmind.framework.pub.utils.MethodUtils.java

private static synchronized Method[] getPublicDeclaredMethods(Class clz) {
    // Looking up Class.getDeclaredMethods is relatively expensive,
    // so we cache the results.
    final Class fclz = clz;
    Method[] result = (Method[]) declaredMethodCache.get(fclz);
    if (result != null) {
        return result;
    }//from   w w  w  .ja  v  a  2 s.  c  o m

    // We have to raise privilege for getDeclaredMethods
    result = (Method[]) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            try {

                return fclz.getDeclaredMethods();

            } catch (SecurityException ex) {
                // this means we're in a limited security environment
                // so let's try going through the public methods
                // and null those those that are not from the declaring
                // class
                Method[] methods = fclz.getMethods();
                for (int i = 0, size = methods.length; i < size; i++) {
                    Method method = methods[i];
                    if (!(fclz.equals(method.getDeclaringClass()))) {
                        methods[i] = null;
                    }
                }
                return methods;
            }
        }
    });

    // Null out any non-public methods.
    for (int i = 0; i < result.length; i++) {
        Method method = result[i];
        if (method != null) {
            int mods = method.getModifiers();
            if (!Modifier.isPublic(mods)) {
                result[i] = null;
            }
        }
    }

    // Add it to the cache.
    declaredMethodCache.put(clz, result);
    return result;
}

From source file:com.sun.socialsite.business.EmfProvider.java

/**
 * Get the context class loader associated with the current thread. This is
 * done in a doPrivileged block because it is a secure method.
 * @return the current thread's context class loader.
 *//*from www .  j a  v  a2s.  co m*/
private static ClassLoader getContextClassLoader() {
    PrivilegedAction<ClassLoader> action = new PrivilegedAction<ClassLoader>() {
        public ClassLoader run() {
            return Thread.currentThread().getContextClassLoader();
        }
    };
    return AccessController.doPrivileged(action);
}

From source file:org.elasticsearch.client.RestClientBuilder.java

/**
 * Creates a new {@link RestClient} based on the provided configuration.
 *//*from  ww  w .j  a  va  2s . c o  m*/
public RestClient build() {
    if (failureListener == null) {
        failureListener = new RestClient.FailureListener();
    }
    CloseableHttpAsyncClient httpClient = AccessController
            .doPrivileged(new PrivilegedAction<CloseableHttpAsyncClient>() {
                @Override
                public CloseableHttpAsyncClient run() {
                    return createHttpClient();
                }
            });
    RestClient restClient = new RestClient(httpClient, maxRetryTimeout, defaultHeaders, hosts, pathPrefix,
            failureListener);
    httpClient.start();
    return restClient;
}

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

private void populateFromReflection(Class cls, XMLMetaData meta) {
    Member[] members;//  w  ww  .j a  va2s  .com

    Class superclass = cls.getSuperclass();

    // handle inheritance at sub-element level
    if ((AccessController.doPrivileged(J2DoPrivHelper.isAnnotationPresentAction(superclass, xmlTypeClass)))
            .booleanValue())
        populateFromReflection(superclass, meta);

    try {
        if (StringUtils.equals(
                xmlAccessorValue.invoke(cls.getAnnotation(xmlAccessorTypeClass), new Object[] {}).toString(),
                "FIELD"))
            members = cls.getDeclaredFields();
        else
            members = cls.getDeclaredMethods();

        for (int i = 0; i < members.length; i++) {
            Member member = members[i];
            AnnotatedElement el = (AnnotatedElement) member;
            XMLMetaData field = null;
            if (el.getAnnotation(xmlElementClass) != null) {
                String xmlname = (String) xmlElementName.invoke(el.getAnnotation(xmlElementClass),
                        new Object[] {});
                // avoid JAXB XML bind default name
                if (StringUtils.equals(XMLMetaData.defaultName, xmlname))
                    xmlname = member.getName();
                if ((AccessController.doPrivileged(
                        J2DoPrivHelper.isAnnotationPresentAction(((Field) member).getType(), xmlTypeClass)))
                                .booleanValue()) {
                    field = _repos.addXMLClassMetaData(((Field) member).getType());
                    parseXmlRootElement(((Field) member).getType(), field);
                    populateFromReflection(((Field) member).getType(), field);
                    field.setXmltype(XMLMetaData.XMLTYPE);
                    field.setXmlname(xmlname);
                } else {
                    field = _repos.newXMLFieldMetaData(((Field) member).getType(), member.getName());
                    field.setXmltype(XMLMetaData.ELEMENT);
                    field.setXmlname(xmlname);
                    field.setXmlnamespace((String) xmlElementNamespace.invoke(el.getAnnotation(xmlElementClass),
                            new Object[] {}));
                }
            } else if (el.getAnnotation(xmlAttributeClass) != null) {
                field = _repos.newXMLFieldMetaData(((Field) member).getType(), member.getName());
                field.setXmltype(XMLFieldMetaData.ATTRIBUTE);
                String xmlname = (String) xmlAttributeName.invoke(el.getAnnotation(xmlAttributeClass),
                        new Object[] {});
                // avoid JAXB XML bind default name
                if (StringUtils.equals(XMLMetaData.defaultName, xmlname))
                    xmlname = member.getName();
                field.setXmlname("@" + xmlname);
                field.setXmlnamespace((String) xmlAttributeNamespace.invoke(el.getAnnotation(xmlAttributeClass),
                        new Object[] {}));
            }
            if (field != null)
                meta.addField(member.getName(), field);
        }
    } catch (Exception e) {
    }
}

From source file:org.apache.openjpa.lib.conf.Configurations.java

/**
 * Helper method used by members of this package to instantiate plugin
 * values.//from   w  ww  .  jav  a 2 s.  c  om
 */
static Object newInstance(String clsName, Value val, Configuration conf, ClassLoader loader, boolean fatal) {
    if (StringUtils.isEmpty(clsName))
        return null;

    Class<?> cls = loadClass(clsName, findDerivedLoader(conf, loader));
    if (cls == null) {
        cls = loadClass(clsName, findDerivedLoader(conf, null));
    }
    if (cls == null && conf.getUserClassLoader() != null) {
        cls = loadClass(clsName, conf.getUserClassLoader());
    }

    if (cls == null) {
        if (fatal)
            throw getCreateException(clsName, val, new ClassNotFoundException(clsName));
        Log log = (conf == null) ? null : conf.getConfigurationLog();
        if (log != null && log.isErrorEnabled())
            log.error(_loc.get("plugin-creation-exception", val));
        return null;
    }

    try {
        return AccessController.doPrivileged(J2DoPrivHelper.newInstanceAction(cls));
    } catch (Exception e) {
        if (e instanceof PrivilegedActionException) {
            e = ((PrivilegedActionException) e).getException();
        }
        RuntimeException re = new NestableRuntimeException(_loc.get("obj-create", cls).getMessage(), e);
        if (fatal)
            throw re;
        Log log = (conf == null) ? null : conf.getConfigurationLog();
        if (log != null && log.isErrorEnabled())
            log.error(_loc.get("plugin-creation-exception", val), re);
        return null;
    }
}

From source file:SecuritySupport.java

long getLastModified(final File f) {
    return ((Long) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return new Long(f.lastModified());
        }//from ww  w .  ja  v a 2  s .c  om
    })).longValue();
}

From source file:org.apache.tika.parser.pkg.TikaArchiveStreamFactory.java

/**
 * Constructs a new sorted map from output stream provider names to provider
 * objects./*  ww  w  . j a v  a2  s  . c  om*/
 *
 * <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> findAvailableArchiveOutputStreamProviders() {
    return AccessController.doPrivileged(new PrivilegedAction<SortedMap<String, ArchiveStreamProvider>>() {
        @Override
        public SortedMap<String, ArchiveStreamProvider> run() {
            TreeMap<String, ArchiveStreamProvider> map = new TreeMap<>();
            putAll(SINGLETON.getOutputStreamArchiveNames(), SINGLETON, map);
            for (ArchiveStreamProvider provider : findArchiveStreamProviders()) {
                putAll(provider.getOutputStreamArchiveNames(), provider, map);
            }
            return map;
        }
    });
}

From source file:org.apache.axis2.engine.DependencyManager.java

protected static ThreadContextDescriptor setThreadContext(final AxisService service) {
    ThreadContextDescriptor tc = new ThreadContextDescriptor();
    tc.oldMessageContext = (MessageContext) MessageContext.currentMessageContext.get();
    final ClassLoader contextClassLoader = getContextClassLoader_doPriv();
    tc.oldClassLoader = contextClassLoader;

    String serviceTCCL = (String) service.getParameterValue(Constants.SERVICE_TCCL);
    if (serviceTCCL != null) {
        serviceTCCL = serviceTCCL.trim().toLowerCase();
        //TODO/*from   w  w w.  ja  v a  2 s  . c  o m*/
        serviceTCCL = Constants.TCCL_COMPOSITE;
        //TODO

        if (serviceTCCL.equals(Constants.TCCL_COMPOSITE)) {
            final ClassLoader loader = (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
                public Object run() {
                    return new MultiParentClassLoader(new URL[] {},
                            new ClassLoader[] { service.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(service.getClassLoader());
                    return null;
                }
            });
        }
    }
    return tc;
}

From source file:org.apache.axiom.attachments.AttachmentCacheMonitor.java

private boolean deleteFile(final String fileName) {
    Boolean privRet = (Boolean) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return _deleteFile(fileName);
        }//from   www  .j  a  v  a 2s. c om
    });
    return privRet.booleanValue();
}

From source file:org.apache.maven.plugin.checkstyle.exec.DefaultCheckstyleExecutor.java

public CheckstyleResults executeCheckstyle(CheckstyleExecutorRequest request)
        throws CheckstyleExecutorException, CheckstyleException {
    // Checkstyle will always use the context classloader in order
    // to load resources (dtds),
    // so we have to fix it
    // olamy this hack is not anymore needed in Maven 3.x
    ClassLoader checkstyleClassLoader = PackageNamesLoader.class.getClassLoader();
    Thread.currentThread().setContextClassLoader(checkstyleClassLoader);

    if (getLogger().isDebugEnabled()) {
        getLogger().debug("executeCheckstyle start headerLocation : " + request.getHeaderLocation());
    }// w  w  w .  j  ava 2s  .  com

    MavenProject project = request.getProject();

    configureResourceLocator(locator, request, null);

    configureResourceLocator(licenseLocator, request, request.getLicenseArtifacts());

    // Config is less critical than License, locator can still be used.
    // configureResourceLocator( configurationLocator, request, request.getConfigurationArtifacts() );

    List<File> files;
    try {
        files = getFilesToProcess(request);
    } catch (IOException e) {
        throw new CheckstyleExecutorException("Error getting files to process", e);
    }

    final String suppressionsFilePath = getSuppressionsFilePath(request);
    FilterSet filterSet = getSuppressionsFilterSet(suppressionsFilePath);

    Checker checker = new Checker();

    // setup classloader, needed to avoid "Unable to get class information for ..." errors
    List<String> classPathStrings = new ArrayList<String>();
    List<String> outputDirectories = new ArrayList<String>();

    // stand-alone
    Collection<File> sourceDirectories = null;
    Collection<File> testSourceDirectories = request.getTestSourceDirectories();

    // aggregator
    Map<MavenProject, Collection<File>> sourceDirectoriesByProject = new HashMap<MavenProject, Collection<File>>();
    Map<MavenProject, Collection<File>> testSourceDirectoriesByProject = new HashMap<MavenProject, Collection<File>>();

    if (request.isAggregate()) {
        for (MavenProject childProject : request.getReactorProjects()) {
            sourceDirectories = new ArrayList<File>(childProject.getCompileSourceRoots().size());
            List<String> compileSourceRoots = childProject.getCompileSourceRoots();
            for (String compileSourceRoot : compileSourceRoots) {
                sourceDirectories.add(new File(compileSourceRoot));
            }
            sourceDirectoriesByProject.put(childProject, sourceDirectories);

            testSourceDirectories = new ArrayList<File>(childProject.getTestCompileSourceRoots().size());
            List<String> testCompileSourceRoots = childProject.getTestCompileSourceRoots();
            for (String testCompileSourceRoot : testCompileSourceRoots) {
                testSourceDirectories.add(new File(testCompileSourceRoot));
            }
            testSourceDirectoriesByProject.put(childProject, testSourceDirectories);

            prepareCheckstylePaths(request, childProject, classPathStrings, outputDirectories,
                    sourceDirectories, testSourceDirectories);
        }
    } else {
        sourceDirectories = request.getSourceDirectories();
        prepareCheckstylePaths(request, project, classPathStrings, outputDirectories, sourceDirectories,
                testSourceDirectories);
    }

    final List<URL> urls = new ArrayList<URL>(classPathStrings.size());

    for (String path : classPathStrings) {
        try {
            urls.add(new File(path).toURL());
        } catch (MalformedURLException e) {
            throw new CheckstyleExecutorException(e.getMessage(), e);
        }
    }

    for (String outputDirectoryString : outputDirectories) {
        try {
            if (outputDirectoryString != null) {
                File outputDirectoryFile = new File(outputDirectoryString);
                if (outputDirectoryFile.exists()) {
                    URL outputDirectoryUrl = outputDirectoryFile.toURL();
                    getLogger().debug("Adding the outputDirectory " + outputDirectoryUrl.toString()
                            + " to the Checkstyle class path");
                    urls.add(outputDirectoryUrl);
                }
            }
        } catch (MalformedURLException e) {
            throw new CheckstyleExecutorException(e.getMessage(), e);
        }
    }

    URLClassLoader projectClassLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {
        public URLClassLoader run() {
            return new URLClassLoader(urls.toArray(new URL[urls.size()]), null);
        }
    });

    checker.setClassloader(projectClassLoader);

    checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());

    if (filterSet != null) {
        checker.addFilter(filterSet);
    }
    Configuration configuration = getConfiguration(request);
    checker.configure(configuration);

    AuditListener listener = request.getListener();

    if (listener != null) {
        checker.addListener(listener);
    }

    if (request.isConsoleOutput()) {
        checker.addListener(request.getConsoleListener());
    }

    CheckstyleCheckerListener checkerListener = new CheckstyleCheckerListener(configuration);
    if (request.isAggregate()) {
        for (MavenProject childProject : request.getReactorProjects()) {
            sourceDirectories = sourceDirectoriesByProject.get(childProject);
            testSourceDirectories = testSourceDirectoriesByProject.get(childProject);
            addSourceDirectory(checkerListener, sourceDirectories, testSourceDirectories,
                    childProject.getResources(), request);
        }
    } else {
        addSourceDirectory(checkerListener, sourceDirectories, testSourceDirectories, request.getResources(),
                request);
    }

    checker.addListener(checkerListener);

    int nbErrors = checker.process(files);

    checker.destroy();

    if (projectClassLoader instanceof Closeable) {
        try {
            ((Closeable) projectClassLoader).close();
        } catch (IOException ex) {
            // Nothing we can do - and not detrimental to the build (save running out of file handles).
            getLogger().info("Failed to close custom Classloader - this indicated a bug in the code.", ex);
        }
    }

    if (request.getStringOutputStream() != null) {
        String message = request.getStringOutputStream().toString().trim();

        if (message.length() > 0) {
            getLogger().info(message);
        }
    }

    if (nbErrors > 0) {
        String message = "There are " + nbErrors + " checkstyle errors.";

        if (request.isFailsOnError()) {
            // TODO: should be a failure, not an error. Report is not meant to
            // throw an exception here (so site would
            // work regardless of config), but should record this information
            throw new CheckstyleExecutorException(message);
        } else {
            getLogger().info(message);
        }
    }

    return checkerListener.getResults();
}