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.services.sqoop.client.SqoopClient.java

public List<String> getLinkList(final String linkMatching, final List<String> existingLinks) {
    if (LOG.isDebugEnabled()) {
        LOG.debug(/*  www .  j  av  a2s.co m*/
                "Get sqoop link list for linkMatching: " + linkMatching + ", existingLinks: " + existingLinks);
    }
    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_LINK_API_ENDPOINT, userName);

            SqoopLinksResponse sqoopLinksResponse = getSqoopResourceResponse(response,
                    SqoopLinksResponse.class);
            if (sqoopLinksResponse == null || CollectionUtils.isEmpty(sqoopLinksResponse.getLinks())) {
                return Collections.emptyList();
            }
            List<String> linkResponses = new ArrayList<>();
            for (SqoopLinkResponse sqoopLinkResponse : sqoopLinksResponse.getLinks()) {
                linkResponses.add(sqoopLinkResponse.getName());
            }

            List<String> links = null;
            if (CollectionUtils.isNotEmpty(linkResponses)) {
                links = filterResourceFromResponse(linkMatching, existingLinks, linkResponses);
            }
            return links;
        }
    });

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

From source file:com.stratuscom.harvester.classloading.VirtualFileSystemClassLoader.java

@Override
public Enumeration<URL> findResources(final String name) throws IOException {

    if (log.isLoggable(Level.FINE)) {
        log.fine("findResourceFileObjects(" + name + ")");
    }/*from  w w  w . jav  a2s .c  o  m*/
    Enumeration result = (Enumeration) Security.doPrivileged(new PrivilegedAction<Enumeration>() {

        public Enumeration run() {
            List<URL> urlList = new ArrayList<URL>();
            try {

                List<FileObject> foList = findResourceFileObjects(name);
                for (FileObject fo : foList) {
                    urlList.add(fo.getURL());
                    if (log.isLoggable(Level.FINE)) {
                        log.fine("..found file object with URL:" + fo.getURL());
                        log.fine("..trying to open it");
                    }
                    /* For unknown reasons, actually getting the resources
                    will fail iff the target folder is not under the current working
                    directory, unless we try to open it while we're here.
                    */
                    InputStream in = null;
                    //BufferedReader r = null;
                    try {
                        in = fo.getURL().openStream();
                        //r = new BufferedReader(new InputStreamReader(in, "utf-8"));

                    } catch (Exception x) {
                        log.log(Level.FINE, "..Got an exception:" + x);
                    } finally {
                        try {
                            //                                if (r != null) {
                            //                                    r.close();
                            //                                }
                            if (in != null) {
                                in.close();
                            }
                        } catch (IOException y) {
                            log.log(Level.FINE, "..Additionally, got an exception on close:" + y);
                        }
                    }

                }
            } catch (FileSystemException ex) {
                Logger.getLogger(VirtualFileSystemClassLoader.class.getName()).log(Level.SEVERE, null, ex);
            }
            return Collections.enumeration(urlList);
        }
    });
    return result;
}

From source file:org.eclipse.gemini.blueprint.extender.internal.support.NamespacePlugins.java

public NamespaceHandler resolve(final String namespaceUri) {
    if (System.getSecurityManager() != null) {
        return AccessController.doPrivileged(new PrivilegedAction<NamespaceHandler>() {

            public NamespaceHandler run() {
                return doResolve(namespaceUri);
            }/*  www  .  j  ava 2  s.c om*/
        });

    } else {
        return doResolve(namespaceUri);
    }
}

From source file:org.elasticsearch.hadoop.script.GroovyScriptEngineService.java

@Override
public Object compile(String scriptName, String scriptSource, Map<String, String> params) {
    // Create the script class name
    String className = MessageDigests
            .toHexString(MessageDigests.sha1().digest(scriptSource.getBytes(StandardCharsets.UTF_8)));

    final SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new SpecialPermission());
    }//from   w ww.  j a v  a  2  s. c om
    return AccessController.doPrivileged(new PrivilegedAction<Object>() {
        @Override
        public Object run() {
            try {
                GroovyCodeSource codeSource = new GroovyCodeSource(scriptSource, className,
                        BootstrapInfo.UNTRUSTED_CODEBASE);
                codeSource.setCachable(false);

                CompilerConfiguration configuration = new CompilerConfiguration()
                        .addCompilationCustomizers(new ImportCustomizer().addStarImports("org.joda.time")
                                .addStaticStars("java.lang.Math"))
                        .addCompilationCustomizers(new GroovyBigDecimalTransformer(CompilePhase.CONVERSION));

                // always enable invokeDynamic, not the crazy softreference-based stuff
                configuration.getOptimizationOptions().put(GROOVY_INDY_SETTING_NAME, true);

                GroovyClassLoader groovyClassLoader = new GroovyClassLoader(loader, configuration);
                return groovyClassLoader.parseClass(codeSource);
            } catch (Exception e) {
                if (log.isTraceEnabled()) {
                    log.trace("Exception compiling Groovy script:", e);
                }
                throw convertToScriptException("Error compiling script " + className, scriptSource, e);
            }
        }
    });
}

From source file:org.jwebsocket.plugins.scripting.app.js.JavaScriptApp.java

/**
 * {@inheritDoc }//from w  w w  . j av  a  2s. c o  m
 *
 * @param aObjectId
 * @param aMethod
 * @param aArgs
 * @return
 * @throws java.lang.Exception
 */
@Override
public Object callMethod(final String aObjectId, final String aMethod, final Collection aArgs)
        throws Exception {
    final Invocable lInvocable = (Invocable) getScriptApp();
    Boolean lExists = (Boolean) lInvocable.invokeMethod(mApp, "isPublished", new Object[] { aObjectId });
    Assert.isTrue(lExists, "The object with id ' " + aObjectId + "' is not published for client access!");

    // getting scripting plugin settings
    Settings lSettings = (Settings) JWebSocketBeanFactory.getInstance(ScriptingPlugIn.NS)
            .getBean("org.jwebsocket.plugins.scripting.settings");

    // calling method into a security sandbox
    return Tools.doPrivileged(lSettings.getAppPermissions(getName(), getPath()),
            new PrivilegedAction<Object>() {
                @Override
                public Object run() {
                    // invoking method
                    try {
                        return lInvocable.invokeMethod(mApp, "invokeObject",
                                new Object[] { aObjectId, aMethod, aArgs });
                    } catch (Exception lEx) {
                        throw new RuntimeException(lEx);
                    }
                }
            });
}

From source file:org.apache.axis2.jaxws.lifecycle.BaseLifecycleManager.java

protected boolean isPreDestroy(final Method method) {
    Annotation[] annotations = (Annotation[]) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return method.getDeclaredAnnotations();
        }//from www  .  jav a  2s. c om
    });
    for (Annotation annotation : annotations) {
        return PreDestroy.class.isAssignableFrom(annotation.annotationType());
    }
    return false;
}

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

@Override
public CallTimeDataManagerRemote getCallTimeDataManager() {
    return AccessController.doPrivileged(new PrivilegedAction<CallTimeDataManagerRemote>() {
        @Override/*from  w ww. j  a  v  a  2 s. c  o m*/
        public CallTimeDataManagerRemote run() {
            return getProxy(LookupUtil.getCallTimeDataManager(), CallTimeDataManagerRemote.class);
        }
    });
}

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

/**
 * Constructs a new sorted map from input stream provider names to provider
 * objects./*from  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> 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.solmix.runtime.support.spring.ContainerApplicationContext.java

/**
 * @param cfgFile/*from w w  w .  ja  v  a  2 s  .  c  o m*/
 * @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 . j a v  a 2s  .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;
}