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.ibm.liberty.starter.service.swagger.api.v1.ProviderEndpoint.java

private int generateCode(String javaHome, String swaggerCodeGenJarPath, String javaClientTemplates,
        String codeGenLanguage, String filePath, String outputDir) throws java.io.IOException {

    try {//ww  w  .j  a v  a 2 s.co  m
        final ArrayList<String> commandList = new ArrayList<String>();

        if (javaHome == null || javaHome.trim().isEmpty()) {
            //Get java home
            javaHome = AccessController.doPrivileged(new PrivilegedAction<String>() {
                @Override
                public String run() {
                    return System.getProperty("java.home");
                }

            });
            if (!javaHome.endsWith("/")) {
                javaHome += "/";
            }
            log.fine("Retrieved Java home location from System property : " + javaHome);
        }

        commandList.add(javaHome + "bin/java");
        commandList.add("-jar");
        commandList.add(swaggerCodeGenJarPath);

        commandList.add("generate");
        commandList.add("-l");
        commandList.add(codeGenLanguage);

        if (javaClientTemplates != null && !javaClientTemplates.trim().isEmpty()) {
            commandList.add("-t");
            commandList.add(javaClientTemplates);
        }

        commandList.add("-i");
        commandList.add(filePath);
        commandList.add("-o");
        commandList.add(outputDir);

        StringBuilder sb = new StringBuilder();
        for (String command : commandList) {
            sb.append(command);
            sb.append(" ");
        }

        log.finer("Swagger code gen commands:\n" + sb.toString());

        //Run the command
        ProcessBuilder builder = new ProcessBuilder(commandList);
        builder.redirectErrorStream(true); //merge error and output together

        Process codeGenProc = builder.start();
        int exitVal = codeGenProc.waitFor();

        log.finer("Exit values: " + exitVal);

        if (exitVal != 0) {
            log.fine("Error : exit value is not 0. exitVal=" + exitVal);
            log.finer("output=" + getOutput(codeGenProc));
        } else {
            log.finer("Successfully generated code using SwaggerCodegen");
        }

        return exitVal;
    } catch (Exception e) {
        log.fine("Exception occurred while executing SwaggerCodegen : e=" + e);
        return -1;
    }
}

From source file:org.apache.axiom.om.util.StAXUtils.java

public static XMLStreamWriter createXMLStreamWriter(StAXWriterConfiguration configuration,
        final OutputStream out) throws XMLStreamException {
    final XMLOutputFactory outputFactory = getXMLOutputFactory(configuration);
    try {//  w  w w.j a v  a  2  s.  c  om
        XMLStreamWriter writer = (XMLStreamWriter) AccessController
                .doPrivileged(new PrivilegedExceptionAction() {
                    public Object run() throws XMLStreamException {
                        return outputFactory.createXMLStreamWriter(out, OMConstants.DEFAULT_CHAR_SET_ENCODING);
                    }
                });

        if (isDebugEnabled) {
            log.debug("XMLStreamWriter is " + writer.getClass().getName());
        }
        return writer;
    } catch (PrivilegedActionException pae) {
        throw (XMLStreamException) pae.getException();
    }
}

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

public Enumeration getAttributeNamesInScope(final int scope) {
    if (SecurityUtil.isPackageProtectionEnabled()) {
        return (Enumeration) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                return doGetAttributeNamesInScope(scope);
            }//from   w w w  . j ava2  s.  c o m
        });
    } else {
        return doGetAttributeNamesInScope(scope);
    }
}

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

/**
 * Return whether the given persistence unit uses an OpenJPA provider.
 *///w  w w.j  a  v  a  2 s.  c om
private static boolean isOpenJPAPersistenceProvider(PersistenceUnitInfo pinfo, ClassLoader loader) {
    String provider = pinfo.getPersistenceProviderClassName();
    if (StringUtils.isEmpty(provider) || PersistenceProviderImpl.class.getName().equals(provider))
        return true;

    if (loader == null)
        loader = (ClassLoader) AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction());
    try {
        if (PersistenceProviderImpl.class.isAssignableFrom(Class.forName(provider, false, loader)))
            return true;
    } catch (Throwable t) {
        log(_loc.get("unloadable-provider", provider, t).getMessage());
        return false;
    }
    return false;
}

From source file:org.beangle.model.persist.hibernate.internal.ClassUtils.java

/**
 * Returns the first matching class from the given array, that doens't
 * belong to common libraries such as the JDK or OSGi API. Useful for
 * filtering OSGi services by type to prevent class cast problems.
 * <p/>//from ww w  . j a  v a  2 s  . com
 * No sanity checks are done on the given array class.
 * 
 * @param classes
 *            array of classes
 * @return a 'particular' (non JDK/OSGi) class if one is found. Else the
 *         first available entry is returned.
 */
public static Class<?> getParticularClass(Class<?>[] classes) {
    boolean hasSecurity = (System.getSecurityManager() != null);
    for (int i = 0; i < classes.length; i++) {
        final Class<?> clazz = classes[i];
        ClassLoader loader = null;
        if (hasSecurity) {
            loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
                public ClassLoader run() {
                    return clazz.getClassLoader();
                }
            });
        } else {
            loader = clazz.getClassLoader();
        }
        // quick boot/system check
        if (loader != null) {
            // consider known loaders
            if (!knownNonOsgiLoadersSet.contains(loader)) {
                return clazz;
            }
        }
    }

    return (ObjectUtils.isEmpty(classes) ? null : classes[0]);
}

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

public int getAttributesScope(final String name) {

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

    if (System.getSecurityManager() != null) {
        return ((Integer) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                return new Integer(doGetAttributeScope(name));
            }
        })).intValue();
    } else {
        return doGetAttributeScope(name);
    }
}

From source file:com.fitbur.testify.system.SpringSystemTest.java

public ClientContext getClientContext(TestContext testContext, ServerContext serverContext) {
    return testContext.getAnnotation(App.class).map(app -> {
        SpringSystemClientDescriptor descriptor = new SpringSystemClientDescriptor(app, testContext,
                serverContext.getInstance().getURI());

        ServiceLoader<ClientProvider> clientProviderLoader = ServiceLoader.load(ClientProvider.class);
        ArrayList<ClientProvider> clientProviders = Lists.newArrayList(clientProviderLoader);

        checkState(!clientProviders.isEmpty(),
                "ClientProvider provider implementation not found in the classpath");

        checkState(clientProviders.size() == 1,
                "Multiple ClientProvider provider implementations found in the classpath. "
                        + "Please insure there is only one ClientProvider provider implementations "
                        + "in the classpath.");

        ClientProvider clientProvider = clientProviders.get(0);
        Object configuration = clientProvider.configuration(descriptor);

        testContext.getConfigMethod(configuration.getClass()).map(m -> m.getMethod()).ifPresent(m -> {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                try {
                    m.setAccessible(true);
                    m.invoke(testContext.getTestInstance(), configuration);
                } catch (Exception e) {
                    checkState(false, "Call to config method '%s' in test class '%s' failed due to: ",
                            m.getName(), descriptor.getTestClassName(), e.getMessage());
                }/* w  ww. j  a va2s . co  m*/

                return null;
            });
        });

        ClientInstance instance = clientProvider.init(descriptor, configuration);
        ServiceLocator serviceLocator = serverContext.getLocator();
        ClientContext context = new ClientContext(clientProvider, descriptor, instance, configuration);

        serviceLocator.addConstant(context.getClass().getSimpleName(), context);
        serviceLocator.addConstant(instance.getClass().getSimpleName(), instance);

        return context;

    }).get();
}

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

/**
 * Assign default source files to the given metadatas.
 *
 * @param clsNames map of class names to metadatas
 * @return set of existing files used by these metadatas, or
 * null if no existing files//from   ww w.  ja  v a2 s  .  c  o  m
 */
private Set assignDefaultMetaDataFiles(ClassMetaData[] metas, QueryMetaData[] queries, SequenceMetaData[] seqs,
        int mode, Map clsNames) {
    Set files = null;
    for (int i = 0; i < metas.length; i++) {
        if (getSourceFile(metas[i]) == null)
            setSourceFile(metas[i], defaultSourceFile(metas[i]));
        if ((AccessController.doPrivileged(J2DoPrivHelper.existsAction(getSourceFile(metas[i]))))
                .booleanValue()) {
            if (files == null)
                files = new HashSet();
            files.add(getSourceFile(metas[i]));
        }
    }
    for (int i = 0; i < queries.length; i++) {
        if (queries[i].getSourceMode() == MODE_QUERY || (mode & queries[i].getSourceMode()) == 0)
            continue;
        if (queries[i].getSourceFile() == null) {
            File defaultFile = defaultSourceFile(queries[i], clsNames);
            queries[i].setSource(defaultFile, queries[i].getSourceScope(), queries[i].getSourceType(),
                    defaultFile == null ? "" : defaultFile.getPath());
        }
        if ((AccessController.doPrivileged(J2DoPrivHelper.existsAction(queries[i].getSourceFile())))
                .booleanValue()) {
            if (files == null)
                files = new HashSet();
            files.add(queries[i].getSourceFile());
        }
    }
    if ((mode & MODE_MAPPING) != 0) {
        for (int i = 0; i < seqs.length; i++) {
            if (getSourceFile(seqs[i]) == null)
                setSourceFile(seqs[i], defaultSourceFile(seqs[i], clsNames));
            if ((AccessController.doPrivileged(J2DoPrivHelper.existsAction(getSourceFile(seqs[i]))))
                    .booleanValue()) {
                if (files == null)
                    files = new HashSet();
                files.add(getSourceFile(seqs[i]));
            }
        }
    }
    return files;
}

From source file:org.apache.axis2.deployment.util.Utils.java

/**
 * Get a ClassLoader which contains a classpath of a) the passed directory and b) any jar files
 * inside the "lib/" or "Lib/" subdirectory of the passed directory.
 *
 * @param parent parent ClassLoader which will be the parent of the result of this method
 * @param file   a File which must be a directory for this to be useful
 * @return a new ClassLoader pointing to both the passed dir and jar files under lib/
 * @throws DeploymentException if problems occur
 *//*from  w w  w.  j  av  a  2s. c  o m*/
public static ClassLoader getClassLoader(final ClassLoader parent, File file,
        final boolean isChildFirstClassLoading) throws DeploymentException {
    URLClassLoader classLoader;

    if (file == null)
        return null; // Shouldn't this just return the parent?

    try {
        ArrayList urls = new ArrayList();
        urls.add(file.toURL());

        // lower case directory name
        File libfiles = new File(file, "lib");
        if (!addFiles(urls, libfiles)) {
            // upper case directory name
            libfiles = new File(file, "Lib");
            addFiles(urls, libfiles);
        }

        final URL urllist[] = new URL[urls.size()];
        for (int i = 0; i < urls.size(); i++) {
            urllist[i] = (URL) urls.get(i);
        }
        classLoader = (URLClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                if (useJarFileClassLoader()) {
                    return new JarFileClassLoader(urllist, parent);
                } else {
                    return new DeploymentClassLoader(urllist, null, parent, isChildFirstClassLoading);
                }
            }
        });
        return classLoader;
    } catch (MalformedURLException e) {
        throw new DeploymentException(e);
    }
}

From source file:org.codice.ddf.cxf.client.impl.SecureCxfClientFactoryImpl.java

/**
 * Clients produced by this method will be secured with two-way ssl and the provided security
 * subject./*www  .j a  v a  2 s . com*/
 *
 * <p>The returned client should NOT be reused between requests! This method should be called for
 * each new request in order to ensure that the security token is up-to-date each time.
 */
public final T getClientForSubject(Subject subject) {
    final java.lang.SecurityManager security = System.getSecurityManager();

    if (security != null) {
        security.checkPermission(CREATE_CLIENT_PERMISSION);
    }

    return AccessController.doPrivileged((PrivilegedAction<T>) () -> {
        String asciiString = clientFactory.getAddress();

        T newClient = getNewClient();

        if (!basicAuth && StringUtils.startsWithIgnoreCase(asciiString, HTTPS)) {
            if (subject instanceof ddf.security.Subject) {
                RestSecurity.setSubjectOnClient((ddf.security.Subject) subject, WebClient.client(newClient));
            }
        }

        auditRemoteConnection(asciiString);

        return newClient;
    });
}