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.event.TCPRemoteCommitProvider.java

/**
 * Sets the list of addresses of peers to which this provider will
 * send events to. The peers are semicolon-separated <code>names</code>
 * list in the form of "myhost1:portA;myhost2:portB".
 *///from ww  w  .  j  a  v a2 s.c  om
public void setAddresses(String names) throws UnknownHostException {
    // NYI. Could look for equivalence of addresses and avoid
    // changing those that didn't change.

    _addressesLock.lock();
    try {
        for (Iterator iter = _addresses.iterator(); iter.hasNext();) {
            ((HostAddress) iter.next()).close();
        }
        String[] toks = Strings.split(names, ";", 0);
        _addresses = new ArrayList(toks.length);

        InetAddress localhost = InetAddress.getLocalHost();
        String localhostName = localhost.getHostName();

        for (int i = 0; i < toks.length; i++) {
            String host = toks[i];
            String hostname;
            int tmpPort;
            int colon = host.indexOf(':');
            if (colon != -1) {
                hostname = host.substring(0, colon);
                tmpPort = Integer.parseInt(host.substring(colon + 1));
            } else {
                hostname = host;
                tmpPort = DEFAULT_PORT;
            }
            InetAddress tmpAddress = AccessController.doPrivileged(J2DoPrivHelper.getByNameAction(hostname));

            // bleair: For each address we would rather make use of
            // the jdk1.4 isLinkLocalAddress () || isLoopbackAddress ().
            // (Though in practice on win32 they don't work anyways!)
            // Instead we will check hostname. Not perfect, but
            // it will match often enough (people will typically
            // use the DNS machine names and be cutting/pasting.)
            if (localhostName.equals(hostname)) {
                // This string matches the hostname for for ourselves, we
                // don't actually need to send ourselves messages.
                if (log.isTraceEnabled()) {
                    log.trace(s_loc.get("tcp-address-asself", tmpAddress.getHostName() + ":" + tmpPort));
                }
            } else {
                HostAddress newAddress = new HostAddress(host);
                _addresses.add(newAddress);
                if (log.isTraceEnabled()) {
                    log.trace(s_loc.get("tcp-address-set",
                            newAddress._address.getHostName() + ":" + newAddress._port));
                }
            }
        }
    } catch (PrivilegedActionException pae) {
        throw (UnknownHostException) pae.getException();
    } finally {
        _addressesLock.unlock();
    }
}

From source file:ddf.catalog.source.solr.rest.SolrRest.java

private String getPassword() {
    return encryptionService.decryptValue(AccessController
            .doPrivileged((PrivilegedAction<String>) () -> System.getProperty("solr.password")));
}

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

public void setAttribute(final String name, final Object attribute) {

    if (name == null) {
        throw new NullPointerException(Localizer.getMessage("jsp.error.attribute.null_name"));
    }//from ww w  . j  a  v a2  s .co m

    if (SecurityUtil.isPackageProtectionEnabled()) {
        AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                doSetAttribute(name, attribute);
                return null;
            }
        });
    } else {
        doSetAttribute(name, attribute);
    }
}

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

/**
 * Return an output stream to the stream(stdout or stderr) or file named
 * by the given string./*from w  ww.  j  a  va2  s  .c o  m*/
 *
 * @see #getFile
 */
public static OutputStream getOutputStream(String file, ClassLoader loader) {
    if (file == null)
        return null;
    if ("stdout".equals(file))
        return System.out;
    if ("stderr".equals(file))
        return System.err;
    try {
        return AccessController.doPrivileged(J2DoPrivHelper.newFileOutputStreamAction(getFile(file, loader)));
    } catch (PrivilegedActionException pae) {
        throw new NestableRuntimeException(pae.getException());
    } catch (IOException ioe) {
        throw new NestableRuntimeException(ioe);
    }
}

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

/**
 * Load the given given resource, or return false if it is not a resource
 * this provider understands. The given class loader may be null.
 *
 * @param anchor optional named anchor within a multiple-configuration
 * resource/*from   w  w w  .j  a  va 2 s.  c  o  m*/
 */
public static ConfigurationProvider load(String resource, String anchor, ClassLoader loader) {
    if (StringUtils.isEmpty(resource))
        return null;
    if (loader == null)
        loader = AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction());
    ConfigurationProvider provider = null;
    StringBuilder errs = null;
    // most specific to least
    Throwable err = null;
    for (int i = _derivations.length - 1; i >= 0; i--) {
        try {
            provider = _derivations[i].load(resource, anchor, loader);
            if (provider != null)
                return provider;
        } catch (Throwable t) {
            err = t;
            errs = (errs == null) ? new StringBuilder() : errs.append("\n");
            errs.append(_derivations[i].getClass().getName() + ":" + t);
        }
    }
    reportErrors(errs, resource, err);
    String rsrc = resource + "#" + anchor;
    MissingResourceException ex = new MissingResourceException(rsrc, ProductDerivations.class.getName(), rsrc);
    ex.initCause(err);
    throw ex;
}

From source file:com.asakusafw.directio.hive.tools.cli.GenerateCreateTable.java

/**
 * Creates a class loader for loading plug-ins.
 * @param parent parent class loader, or {@code null} to use the system class loader
 * @param files plug-in class paths (*.jar file or class path directory)
 * @return the created class loader//w w  w  .ja v a  2s  . c om
 * @throws IllegalArgumentException if some parameters were {@code null}
 */
private static URLClassLoader buildPluginLoader(ClassLoader parent, List<File> files) {
    if (files == null) {
        throw new IllegalArgumentException("files must not be null"); //$NON-NLS-1$
    }
    List<URL> locations = new ArrayList<>();
    for (File file : files) {
        try {
            if (file.exists() == false) {
                throw new FileNotFoundException(
                        MessageFormat.format(Messages.getString("GenerateCreateTable.errorMissingPluginFile"), //$NON-NLS-1$
                                file.getAbsolutePath()));
            }
            URL url = file.toURI().toURL();
            locations.add(url);
        } catch (IOException e) {
            LOG.warn(MessageFormat.format(Messages.getString("GenerateCreateTable.warnInvalidPluginFile"), //$NON-NLS-1$
                    file.getAbsolutePath()), e);
        }
    }
    return AccessController.doPrivileged((PrivilegedAction<URLClassLoader>) () -> new URLClassLoader(
            locations.toArray(new URL[locations.size()]), parent));
}

From source file:org.codice.ddf.security.crl.generator.CrlGenerator.java

/**
 * Writes out the CRL to the given file and adds its path to the property files.
 *
 * @param byteSource - CRL byte source// w  w w. ja v a  2s. co  m
 * @param crlFile - the file to write the CRL to
 */
private void writeCrlToFile(ByteSource byteSource, File crlFile) {
    try {
        AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
            // Write out to file
            try (OutputStream outStream = new FileOutputStream(crlFile);
                    InputStream inputStream = byteSource.openStream()) {
                IOUtils.copy(inputStream, outStream);
                SecurityLogger.audit("Copied the content of the CRl at {} to the local CRL at {}.",
                        crlLocationUrl, crlFile.getPath());
                setCrlFileLocationInPropertiesFile(crlFile.getPath());
            }
            return null;
        });
    } catch (PrivilegedActionException e) {
        LOGGER.warn("Unable to save the CRL.");
        LOGGER.debug("Unable to save the CRL. {}", e.getCause());
        postErrorEvent("Unable to save the CRL.");
    }
}

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

/**
 * Attempt to find a derived loader that delegates to our target loader.
 * This allows application loaders that delegate appropriately for known
 * classes first crack at class names.//from  w  w w  .  j  a va  2s.c om
 */
private static ClassLoader findDerivedLoader(Configuration conf, ClassLoader loader) {
    // we always prefer the thread loader, because it's the only thing we
    // can access that isn't bound to the OpenJPA classloader, unless
    // the conf object is of a custom class
    ClassLoader ctxLoader = AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction());
    if (loader == null) {
        if (ctxLoader != null) {
            return ctxLoader;
        } else if (conf != null) {
            return classLoaderOf(conf.getClass());
        } else {
            return classLoaderOf(Configurations.class);
        }
    }

    for (ClassLoader parent = ctxLoader; parent != null; parent = parentClassLoaderOf(parent)) {
        if (parent == loader)
            return ctxLoader;
    }
    if (conf != null) {
        for (ClassLoader parent = classLoaderOf(conf.getClass()); parent != null; parent = parentClassLoaderOf(
                parent)) {
            if (parent == loader)
                return classLoaderOf(conf.getClass());
        }
    }
    return loader;
}

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

public static SortedMap<String, CompressorStreamProvider> findAvailableCompressorInputStreamProviders() {
    return AccessController.doPrivileged(new PrivilegedAction<SortedMap<String, CompressorStreamProvider>>() {
        @Override//from w  w  w  .java 2s  . c  o  m
        public SortedMap<String, CompressorStreamProvider> run() {
            final TreeMap<String, CompressorStreamProvider> map = new TreeMap<>();
            putAll(SINGLETON.getInputStreamCompressorNames(), SINGLETON, map);
            for (final CompressorStreamProvider provider : findCompressorStreamProviders()) {
                putAll(provider.getInputStreamCompressorNames(), provider, map);
            }
            return map;
        }
    });
}

From source file:org.apache.hadoop.filecache.TaskDistributedCacheManager.java

/**
 * Creates a class loader that includes the designated
 * files and archives./*ww  w. j  a  va 2s .c o  m*/
 */
public ClassLoader makeClassLoader(final ClassLoader parent) throws MalformedURLException {
    final URL[] urls = new URL[classPaths.size()];
    for (int i = 0; i < classPaths.size(); ++i) {
        urls[i] = new File(classPaths.get(i)).toURI().toURL();
    }
    return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
        @Override
        public ClassLoader run() {
            return new URLClassLoader(urls, parent);
        }
    });
}