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:freemarker.ext.jsp._FreeMarkerPageContext21.java

/**
 * Attempts to locate and manufacture an expression evaulator instance. For this
 * to work you <b>must</b> have the Apache Commons-EL package in the classpath. If
 * Commons-EL is not available, this method will throw an UnsupportedOperationException. 
 *//*from www  . j  av  a  2s.c om*/
@Override
public ExpressionEvaluator getExpressionEvaluator() {
    try {
        Class type = ((ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                return Thread.currentThread().getContextClassLoader();
            }
        })).loadClass("org.apache.commons.el.ExpressionEvaluatorImpl");
        return (ExpressionEvaluator) type.newInstance();
    } catch (Exception e) {
        throw new UnsupportedOperationException("In order for the getExpressionEvaluator() "
                + "method to work, you must have downloaded the apache commons-el jar and "
                + "made it available in the classpath.");
    }
}

From source file:com.mycompany.kerberosbyip.NewMain.java

private void runPrivileged() throws Exception {
    final CallbackHandler handler = new ProvidedAuthCallback(username, password);
    final LoginContext lc = new LoginContext("KrbLogin", handler);
    lc.login();// www  .  j a va 2 s .c  om

    PrivilegedAction<Void> sendAction = new PrivilegedAction<Void>() {
        @Override
        public Void run() {
            try {
                doSendRequest();
                return null;
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }

        }
    };

    Subject.doAs(lc.getSubject(), sendAction);
}

From source file:org.ow2.chameleon.core.utils.FrameworkClassLoader.java

/**
 * Gets an instance of {@link org.ow2.chameleon.core.utils.FrameworkClassLoader}.
 *
 * @param basedir       the base directory. The 'libs' folder must be a direct child of this directory.
 * @param configuration the Chameleon configuration.
 * @return the instance of classloader./*from  www.j  a va 2s.  com*/
 */
public static ClassLoader getFrameworkClassLoader(final File basedir, final Map<String, String> configuration) {
    return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
        @Override
        public ClassLoader run() {
            if (configuration != null) {
                return new FrameworkClassLoader(basedir, configuration.get("chameleon.libraries.parent"));
            } else {
                return new FrameworkClassLoader(basedir, null);
            }
        }
    });
}

From source file:org.apache.hadoop.yarn.client.ConfiguredFailoverProxyProvider.java

@Override
public T getProxy() {
    UserGroupInformation ugi;/*from   w  w  w .j a va  2  s .  c  o m*/
    final InetSocketAddress rmAddress;
    try {
        ugi = UserGroupInformation.getCurrentUser();
        rmAddress = getRMAddress();
        if (LOG.isTraceEnabled()) {
            LOG.trace("Connecting to RM at " + rmAddress);
        }
    } catch (IOException ioe) {
        return null;
    }

    if (ugi == null) {
        return null;
    }

    return ugi.doAs(new PrivilegedAction<T>() {
        @Override
        public T run() {
            return (T) YarnRPC.create(conf).getProxy(protocol, rmAddress, conf);
        }
    });
}

From source file:org.broadleafcommerce.common.extensibility.InstrumentationRuntimeFactory.java

/**
 * This method returns the Instrumentation object provided by the JVM. If the Instrumentation object is null,
 * it does its best to add an instrumentation agent to the JVM and then the instrumentation object.
 * @return Instrumentation//w ww  .  j ava 2 s.co  m
 */
public static synchronized Instrumentation getInstrumentation() {
    if (inst != null) {
        return inst;
    }

    if (System.getProperty("java.vendor").toUpperCase().contains("IBM")) {
        isIBM = true;
    }

    AccessController.doPrivileged(new PrivilegedAction<Object>() {
        public Object run() {
            try {
                if (!InstrumentationRuntimeFactory.class.getClassLoader()
                        .equals(ClassLoader.getSystemClassLoader())) {
                    return null;
                }
            } catch (Throwable t) {
                return null;
            }
            File toolsJar = null;
            // When running on IBM, the attach api classes are packaged in vm.jar which is a part
            // of the default vm classpath.
            if (!isIBM) {
                // If we can't find the tools.jar and we're not on IBM we can't load the agent.
                toolsJar = findToolsJar();
                if (toolsJar == null) {
                    return null;
                }
            }

            Class<?> vmClass = loadVMClass(toolsJar);
            if (vmClass == null) {
                return null;
            }
            String agentPath = getAgentJar();
            if (agentPath == null) {
                return null;
            }
            loadAgent(agentPath, vmClass);
            return null;
        }
    });

    return inst;
}

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

@Override
public GroovyPageScriptSource findPageInBinding(final String pluginName, final String uri,
        final GroovyPageBinding binding) {
    if (uri == null || pluginName == null)
        return null;

    PrivilegedAction<GroovyPageScriptSource> updater = new PrivilegedAction<GroovyPageScriptSource>() {
        public GroovyPageScriptSource run() {
            GroovyPageScriptSource scriptSource = CachingGrailsConventionGroovyPageLocator.super.findPageInBinding(
                    pluginName, uri, binding);
            if (scriptSource == null) {
                scriptSource = NULL_SCRIPT;
            }/*  www .  j a va  2  s.  c om*/
            return scriptSource;
        }
    };

    return lookupCache(GroovyPageLocatorCacheKey.build(uri, pluginName, binding), updater);
}

From source file:org.jwebsocket.plugins.scripting.app.Manifest.java

/**
 * Checks the app sandbox security permissions dependecy.
 *
 * @param aPerms//  w ww .j av  a  2  s.  com
 * @param aGrantedPerms
 * @param aAppDirPath
 * @throws Exception
 */
public static void checkPermissions(List<String> aPerms, Permissions aGrantedPerms, String aAppDirPath)
        throws Exception {
    for (String lPerm : aPerms) {
        final String lExpandedPerm = JWebSocketConfig
                .expandEnvVarsAndProps(lPerm.replace("${APP_HOME}", aAppDirPath));
        try {
            Tools.doPrivileged(aGrantedPerms, new PrivilegedAction<Boolean>() {
                @Override
                public Boolean run() {
                    AccessController.checkPermission(Tools.stringToPermission(lExpandedPerm));
                    return true;
                }
            });
        } catch (AccessControlException lEx) {
            throw new Exception(
                    "Unable to load application. Permission requirement '" + lPerm + "' not satisfied!");
        }
    }
}

From source file:com.agimatec.validation.jsr303.AnnotationConstraintBuilder.java

/** build attributes, payload, groups from 'annotation' */
private void buildFromAnnotation() {
    if (constraintValidation.getAnnotation() != null) {
        SecureActions.run(new PrivilegedAction<Object>() {
            public Object run() {
                for (Method method : constraintValidation.getAnnotation().annotationType()
                        .getDeclaredMethods()) {
                    // enhancement: clarify: should groups + payload also appear in attributes?
                    if (method.getParameterTypes().length == 0) {
                        try {
                            if (ANNOTATION_PAYLOAD.equals(method.getName())) {
                                buildPayload(method);
                            } else if (ANNOTATION_GROUPS.equals(method.getName())) {
                                buildGroups(method);
                            } else {
                                constraintValidation.getAttributes().put(method.getName(),
                                        method.invoke(constraintValidation.getAnnotation()));
                            }//from  w  w w  .  j  a  va  2 s  .co  m
                        } catch (Exception e) { // do nothing
                            log.warn("error processing annotation: " + constraintValidation.getAnnotation(), e);
                        }
                    }
                }
                return null;
            }
        });
    }
    try {
        /*
        spec: Invalid constraint definitions causes are multiple but include missing or illegal message
        or groups elements
        */
        if (constraintValidation.getGroups() == null) {
            throw new ConstraintDefinitionException(
                    constraintValidation.getAnnotation().annotationType().getName()
                            + " does not contain a groups parameter.");
        }
        if (constraintValidation.getMessageTemplate() == null) {
            throw new ConstraintDefinitionException(
                    constraintValidation.getAnnotation().annotationType().getName()
                            + " does not contain a message parameter.");
        }
        if (constraintValidation.getPayload() == null) {
            throw new ConstraintDefinitionException(
                    constraintValidation.getAnnotation().annotationType().getName()
                            + " does not contain a payload parameter.");
        }
    } catch (ConstraintDefinitionException e) {
        throw e;
    } catch (Exception e) {
        throw new IllegalArgumentException(e); // execution never reaches this point
    }
}

From source file:com.agimatec.validation.jsr303.util.SecureActions.java

/**
 * Returns the <b>public method</b> with the specified name or null if it does not exist.
 *
 * @return Returns the method or null if not found.
 *//*from   ww w. j  av a  2 s  .c  o m*/
public static Method getGetter(final Class<?> clazz, final String methodName) {
    return run(new PrivilegedAction<Method>() {
        public Method run() {
            try {
                String methodName0 = StringUtils.capitalize(methodName);
                try {
                    return clazz.getMethod("get" + methodName0);
                } catch (NoSuchMethodException e) {
                    return clazz.getMethod("is" + methodName0);
                }
            } catch (NoSuchMethodException e) {
                return null;
            }
        }
    });

}

From source file:org.beanlet.springframework.impl.SpringHelper.java

public static synchronized ListableBeanFactory getListableBeanFactory(BeanletConfiguration<?> configuration,
        Element element) {/*from w  w w  .  j a  v  a 2s  .  c  o  m*/
    SpringContext springContext = getSpringContext(configuration, element);
    if (springContext == null) {
        throw new ApplicationContextException("No spring context specified.");
    }
    final ClassLoader loader = configuration.getComponentUnit().getClassLoader();
    Map<SpringContext, ListableBeanFactory> map = factories.get(loader);
    if (map == null) {
        map = new HashMap<SpringContext, ListableBeanFactory>();
        factories.put(loader, map);
    }
    ListableBeanFactory factory = map.get(springContext);
    if (factory == null) {
        ClassLoader org = null;
        try {
            org = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
                public ClassLoader run() {
                    // PERMISSION: java.lang.RuntimePermission getClassLoader
                    ClassLoader org = Thread.currentThread().getContextClassLoader();
                    // PERMISSION: java.lang.RuntimePermission setContextClassLoader
                    Thread.currentThread().setContextClassLoader(loader);
                    return org;
                }
            });
            if (springContext.applicationContext()) {
                factory = new GenericApplicationContext();
            } else {
                factory = new DefaultListableBeanFactory();
            }
            // Do not create spring context in priviliged scope!
            for (SpringResource r : springContext.value()) {
                String path = r.value();
                Resource resource = null;
                BeanDefinitionReader reader = null;
                switch (r.type()) {
                case CLASSPATH:
                    resource = new ClassPathResource(path);
                    break;
                case FILESYSTEM:
                    resource = new FileSystemResource(path);
                    break;
                case URL:
                    resource = new UrlResource(path);
                    break;
                default:
                    assert false : r.type();
                }
                switch (r.format()) {
                case XML:
                    reader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) factory);
                    break;
                case PROPERTIES:
                    reader = new PropertiesBeanDefinitionReader((BeanDefinitionRegistry) factory);
                    break;
                default:
                    assert false : r.format();
                }
                if (resource != null && resource.exists()) {
                    reader.loadBeanDefinitions(resource);
                }
            }
            if (factory instanceof ConfigurableApplicationContext) {
                ((ConfigurableApplicationContext) factory).refresh();
            }
            map.put(springContext, factory);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new ApplicationContextException("Failed to construct spring "
                    + (springContext.applicationContext() ? "application context" : "bean factory") + ".", e);
        } finally {
            final ClassLoader tmp = org;
            AccessController.doPrivileged(new PrivilegedAction<Object>() {
                public Object run() {
                    // PERMISSION: java.lang.RuntimePermission setContextClassLoader
                    Thread.currentThread().setContextClassLoader(tmp);
                    return null;
                }
            });
        }
    }
    return factory;
}