Example usage for java.security PrivilegedAction PrivilegedAction

List of usage examples for java.security PrivilegedAction PrivilegedAction

Introduction

In this page you can find the example usage for java.security PrivilegedAction PrivilegedAction.

Prototype

PrivilegedAction

Source Link

Usage

From source file:org.apache.ranger.admin.client.RangerAdminRESTClient.java

@Override
public void grantAccess(final GrantRevokeRequest request) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> RangerAdminRESTClient.grantAccess(" + request + ")");
    }/*from w  w w  .  j  a  va2 s . c  om*/

    ClientResponse response = null;
    UserGroupInformation user = MiscUtil.getUGILoginUser();
    boolean isSecureMode = user != null && UserGroupInformation.isSecurityEnabled();

    if (isSecureMode) {
        PrivilegedAction<ClientResponse> action = new PrivilegedAction<ClientResponse>() {
            public ClientResponse run() {
                WebResource secureWebResource = createWebResource(
                        RangerRESTUtils.REST_URL_SECURE_SERVICE_GRANT_ACCESS + serviceName)
                                .queryParam(RangerRESTUtils.REST_PARAM_PLUGIN_ID, pluginId);
                return secureWebResource.accept(RangerRESTUtils.REST_EXPECTED_MIME_TYPE)
                        .type(RangerRESTUtils.REST_EXPECTED_MIME_TYPE)
                        .post(ClientResponse.class, restClient.toJson(request));
            };
        };
        if (LOG.isDebugEnabled()) {
            LOG.debug("grantAccess as user " + user);
        }
        response = user.doAs(action);
    } else {
        WebResource webResource = createWebResource(RangerRESTUtils.REST_URL_SERVICE_GRANT_ACCESS + serviceName)
                .queryParam(RangerRESTUtils.REST_PARAM_PLUGIN_ID, pluginId);
        response = webResource.accept(RangerRESTUtils.REST_EXPECTED_MIME_TYPE)
                .type(RangerRESTUtils.REST_EXPECTED_MIME_TYPE)
                .post(ClientResponse.class, restClient.toJson(request));
    }
    if (response != null && response.getStatus() != 200) {
        RESTResponse resp = RESTResponse.fromClientResponse(response);
        LOG.error("grantAccess() failed: HTTP status=" + response.getStatus() + ", message=" + resp.getMessage()
                + ", isSecure=" + isSecureMode + (isSecureMode ? (", user=" + user) : ""));

        if (response.getStatus() == 401) {
            throw new AccessControlException();
        }

        throw new Exception("HTTP " + response.getStatus() + " Error: " + resp.getMessage());
    } else if (response == null) {
        throw new Exception("unknown error during grantAccess. serviceName=" + serviceName);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== RangerAdminRESTClient.grantAccess(" + request + ")");
    }
}

From source file:org.pepstock.jem.util.ClassLoaderUtil.java

/**
 * Loads all classpath information from plugin configuration and creates a
 * custom classloader to load the plugin.
 * /*from ww  w.j  a va2 s  .  co  m*/
 * @param pluginDef plugin defintion
 * @param props list of properties to used to substitute if necessary
 * @param knownLoader ClassLoader already created previously
 * @return containers with object instantiated and class path based on URLs
 * @throws InstantiationException if any error occurs
 * @throws IllegalAccessException if any error occurs
 * @throws ClassNotFoundException if any error occurs
 * @throws IOException if any error occurs
 */
public static ObjectAndClassPathContainer loadAbstractPlugin(AbstractPluginDefinition pluginDef,
        Properties props, ClassLoader knownLoader)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException, IOException {
    // creates the result to return
    ObjectAndClassPathContainer result = new ObjectAndClassPathContainer();

    if (knownLoader != null) {
        // there already a classloader
        // loads the plugin from classloader
        Class<?> clazz = knownLoader.loadClass(pluginDef.getClassName());
        // sets the object
        result.setObject(clazz.newInstance());
        return result;
    } else if (pluginDef.getClasspath() == null || pluginDef.getClasspath().isEmpty()) {
        // if plugin defintion doesn't have the classpath, that means that the
        // plugin is already placed in JEM classpath
        // therefore it's enough to call it
        // load by Class.forName of factory
        result.setObject(Class.forName(pluginDef.getClassName()).newInstance());
    } else {
        // CLASSPATH has been set therefore it an try to load the plugin by
        // a custom classloader
        // collection of all file of classpath
        Collection<File> files = new LinkedList<File>();
        // scans all strings of classpath
        for (ClassPath classPath : pluginDef.getClasspath()) {
            // substitute variables if there are
            String path = VariableSubstituter.substitute(classPath.getContent(), props);
            // creates the file
            File file = new File(path);
            // if file ends with * could be only this folder or all folders
            // in cascade
            if (path.endsWith(ALL_FOLDER)) {
                // checks if is all folders in cascade
                boolean cascade = path.endsWith(ALL_FOLDER_IN_CASCADE);
                // gets the parent and asks for all JAR files
                File parent = file.getParentFile();
                Collection<File> newFiles = FileUtils.listFiles(parent, EXTENSIONS.toArray(new String[0]),
                        cascade);
                // loads to the collection
                files.addAll(newFiles);
                if (cascade) {
                    // scan all files to extract folder to add classpath
                    // with *, standard JAVA
                    for (File newFile : newFiles) {
                        String parentNormalized = newFile.getParentFile().getAbsolutePath() + File.separator
                                + ALL_FOLDER;
                        // if the path is not already in the result, load it
                        if (!result.getClassPath().contains(parentNormalized)) {
                            result.getClassPath().add(parentNormalized);
                        }
                    }
                } else {
                    // loads all files
                    if (!result.getClassPath().contains(file.getAbsolutePath())) {
                        result.getClassPath().add(file.getAbsolutePath());
                    }
                }
            } else if (file.isDirectory() && file.exists()) {
                // if here, we have a directory
                // adds the directory to collection
                files.add(file);
                if (!result.getClassPath().contains(file.getAbsolutePath())) {
                    result.getClassPath().add(file.getAbsolutePath());
                }
            } else if (file.isFile() && file.exists()) {
                // if here, a file has been indicated
                // adds the directory to collection
                files.add(file);
                if (!result.getClassPath().contains(file.getAbsolutePath())) {
                    result.getClassPath().add(file.getAbsolutePath());
                }
            }
        }
        // checks if the collection is empty.
        // if yes, all classpath definiton is wrong and no files have been
        // loaded
        if (!files.isEmpty()) {
            // exports files in URLs, for our classloader
            final URL[] urls = FileUtils.toURLs(files.toArray(new File[files.size()]));
            // loads a our classloader by access controller
            ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
                public ClassLoader run() {
                    return new ReverseURLClassLoader(urls, Main.class.getClassLoader());
                }
            });
            // loads the plugin from classloader
            Class<?> clazz = loader.loadClass(pluginDef.getClassName());
            // sets the object
            result.setObject(clazz.newInstance());
            result.setLoader(loader);
        } else {
            throw new IOException(UtilMessage.JEMB009E.toMessage().getMessage());
        }
    }
    return result;
}

From source file:org.codehaus.groovy.grails.web.pages.discovery.DefaultGroovyPageLocator.java

protected GroovyPageCompiledScriptSource createGroovyPageCompiledScriptSource(final String uri, String fullPath,
        Class<?> viewClass) {
    GroovyPageCompiledScriptSource scriptSource = new GroovyPageCompiledScriptSource(uri, fullPath, viewClass);
    if (reloadEnabled) {
        scriptSource.setResourceCallable(new PrivilegedAction<Resource>() {
            public Resource run() {
                return findReloadablePage(uri);
            }//from w  w  w.j a v a 2s. c om
        });
    }
    return scriptSource;
}

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

private ClassLoader getContextClassLoader_doPriv() {
    return (ClassLoader) org.apache.axis2.java.security.AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return Thread.currentThread().getContextClassLoader();
        }/*from w w  w.j  a va2s .c  o  m*/
    });
}

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.
 *//* w  w w. j av a2 s  .  c o  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.nebulaframework.core.job.archive.GridArchive.java

/**
 * Returns the {@code GridJob} classes with in the given {@code .nar} file.
 * Uses {@link GridArchiveClassLoader}.//  w ww  .  j a  v a 2 s .c o  m
 * 
 * @param file
 *            {@code File} instance for {@code .nar} file.
 * 
 * @return Fully qualified class names of {@code GridJob} classes in the
 *         file.
 * 
 * @throws IOException
 *             if occurred during File I/O operations
 * 
 * @see GridArchiveClassLoader
 */
protected static String[] findJobClassNames(final File file) throws IOException {

    // Instantiate ClassLoader for given File
    ClassLoader classLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
        public GridArchiveClassLoader run() {
            return new GridArchiveClassLoader(file);
        }

    });

    // Find ClassNames of all classes inside the file (except in NEBULA-INF)
    // Content inside .jar files will not be processed
    String[] allClassNames = getAllClassNames(file);

    // Holds Class<?> instances loaded by ClassLoader, for all classes
    List<String> jobClassNames = new ArrayList<String>();

    for (String className : allClassNames) {
        try {
            // Load each Class and check if its a GridJob Class
            if (isGridJobClass(classLoader.loadClass(className))) {
                jobClassNames.add(className);
            }
        } catch (ClassNotFoundException e) {
            // Log and continue with rest
            log.debug("[GridArchive] Unable to load class " + className);
        }
    }
    return jobClassNames.toArray(new String[] {});
}

From source file:org.apache.ranger.services.sqoop.client.SqoopClient.java

public List<String> getJobList(final String jobMatching, final List<String> existingJobs) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Get sqoop job list for jobMatching: " + jobMatching + ", existingJobs: " + existingJobs);
    }/*from w  ww . j  a va  2  s .c  o m*/
    Subject subj = getLoginSubject();
    if (subj == null) {
        return Collections.emptyList();
    }

    List<String> ret = Subject.doAs(subj, new PrivilegedAction<List<String>>() {

        @Override
        public List<String> run() {

            ClientResponse response = getClientResponse(sqoopUrl, SQOOP_JOB_API_ENDPOINT, userName);

            SqoopJobsResponse sqoopJobsResponse = getSqoopResourceResponse(response, SqoopJobsResponse.class);
            if (sqoopJobsResponse == null || CollectionUtils.isEmpty(sqoopJobsResponse.getJobs())) {
                return Collections.emptyList();
            }
            List<String> jobResponses = new ArrayList<>();
            for (SqoopJobResponse sqoopJobResponse : sqoopJobsResponse.getJobs()) {
                jobResponses.add(sqoopJobResponse.getName());
            }

            List<String> jobs = null;
            if (CollectionUtils.isNotEmpty(jobResponses)) {
                jobs = filterResourceFromResponse(jobMatching, existingJobs, jobResponses);
            }
            return jobs;
        }
    });

    if (LOG.isDebugEnabled()) {
        LOG.debug("Get sqoop job list result: " + ret);
    }
    return ret;
}

From source file:org.rhq.enterprise.client.LocalClient.java

@Override
public DataAccessManagerRemote getDataAccessManager() {
    return AccessController.doPrivileged(new PrivilegedAction<DataAccessManagerRemote>() {
        @Override//w  w w.  j  ava 2s  .c  o m
        public DataAccessManagerRemote run() {
            return getProxy(LookupUtil.getDataAccessManager(), DataAccessManagerRemote.class);
        }
    });
}

From source file:org.apache.axis2.jaxws.server.endpoint.injection.impl.WebServiceContextInjectorImpl.java

/**
 * Set accessible.  This method must remain private
 *
 * @param obj   AccessibleObject/* ww w  .jav  a 2s. co  m*/
 * @param value true or false
 */
private static void setAccessible(final AccessibleObject obj, final boolean value) {
    AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            obj.setAccessible(value);
            return null;
        }
    });

}

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

public Object getAttribute(final String name, final int scope) {

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

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

}