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.lib.conf.Configurations.java

/**
 * Set the given {@link Configuration} instance from the command line
 * options provided. All property names of the given configuration are
 * recognized; additionally, if a <code>properties</code> or
 * <code>p</code> argument exists, the resource it
 * points to will be loaded and set into the given configuration instance.
 * It can point to either a file or a resource name.
 *//*from   w w  w  .  ja  va  2  s.  c  o  m*/
public static void populateConfiguration(Configuration conf, Options opts) {
    String props = opts.removeProperty("properties", "p", null);
    ConfigurationProvider provider;
    if (!StringUtils.isEmpty(props)) {
        Map<String, String> result = parseConfigResource(props);
        String path = result.get(CONFIG_RESOURCE_PATH);
        String anchor = result.get(CONFIG_RESOURCE_ANCHOR);

        File file = new File(path);
        if ((AccessController.doPrivileged(J2DoPrivHelper.isFileAction(file))).booleanValue())
            provider = ProductDerivations.load(file, anchor, null);
        else {
            file = new File("META-INF" + File.separatorChar + path);
            if ((AccessController.doPrivileged(J2DoPrivHelper.isFileAction(file))).booleanValue())
                provider = ProductDerivations.load(file, anchor, null);
            else
                provider = ProductDerivations.load(path, anchor, null);
        }
        if (provider != null)
            provider.setInto(conf);
        else
            throw new MissingResourceException(_loc.get("no-provider", props).getMessage(),
                    Configurations.class.getName(), props);
    } else {
        provider = ProductDerivations.loadDefaults(null);
        if (provider != null)
            provider.setInto(conf);
    }
    opts.setInto(conf);
}

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

public ServerContext getServerContext(TestContext testContext, String methodName) {
    Object testInstance = testContext.getTestInstance();
    return testContext.getAnnotation(App.class).map(p -> {
        Class<?> appType = p.value();
        ServiceLoader<ServerProvider> serviceLoader = ServiceLoader.load(ServerProvider.class);
        ArrayList<ServerProvider> serverProviders = Lists.newArrayList(serviceLoader);

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

        checkState(serverProviders.size() == 1,
                "Multiple ServiceProvider provider implementations found in the classpath. "
                        + "Please insure there is only one ServiceProvider provider implementation "
                        + "in the classpath.");
        ServerProvider provider = serverProviders.get(0);

        interceptor = new SpringSystemServletInterceptor(testContext, methodName, serviceAnnotations,
                classTestNeeds, classTestNeedContainers);

        Class<?> proxyAppType = BYTE_BUDDY.subclass(appType).method(not(isDeclaredBy(Object.class)))
                .intercept(to(interceptor).filter(not(isDeclaredBy(Object.class)))).make()
                .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded();

        Set<Class<?>> handles = new HashSet<>();
        handles.add(proxyAppType);/*from  w w w  . ja v  a2s.co m*/
        SpringServletContainerInitializer initializer = new SpringServletContainerInitializer();

        SpringSystemServerDescriptor descriptor = new SpringSystemServerDescriptor(p, testContext, initializer,
                handles);

        Object configuration = provider.configuration(descriptor);
        testContext.getConfigMethod(configuration.getClass()).map(m -> m.getMethod()).ifPresent(m -> {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                try {
                    m.setAccessible(true);
                    m.invoke(testInstance, configuration);
                } catch (Exception e) {
                    checkState(false, "Call to config method '%s' in test class '%s' failed.", m.getName(),
                            descriptor.getTestClassName());
                    throw Throwables.propagate(e);
                }

                return null;
            });
        });

        ServerInstance serverInstance = provider.init(descriptor, configuration);
        serverInstance.start();

        SpringServiceLocator serviceLocator = interceptor.getServiceLocator();

        serviceLocator.addConstant(serverInstance.getClass().getSimpleName(), serverInstance);

        ServerContext serverContext = new ServerContext(provider, descriptor, serverInstance, serviceLocator,
                configuration);
        serviceLocator.addConstant(serverContext.getClass().getSimpleName(), serverContext);

        TestCaseInstance testCaseInstance = new TestCaseInstance(methodName, testInstance);
        serviceLocator.addConstant(testCaseInstance.getTestName(), testCaseInstance);

        return serverContext;

    }).get();
}

From source file:org.commonjava.sshwrap.config.DefaultSSHConfiguration.java

static String userHome() {
    return AccessController.doPrivileged(new PrivilegedAction<String>() {
        @Override// w  w  w  .  j ava2 s  .com
        public String run() {
            return System.getProperty("user.home");
        }
    });
}

From source file:org.acmsl.commons.BundleI14able.java

/**
 * Builds an internationalized message for given key, parameters
 * and locale./*ww  w.j a  va  2  s.co  m*/
 * @param key the message key.
 * @param params the message parameters.
 * @param locale the locale.
 * @param bundleName the bundle name.
 * @param systemProperty the name of the bundle.
 * @param useClassLoader whether to use class loader or not.
 * @param firstBundle the first bundle.
 * @param secondBundle the second bundle.
 * @param retryBundles whether to retry bundle retrieval or not.
 * @return the customized message.
 */
protected String buildMessage(@NotNull final String key, @NotNull final Object[] params,
        @NotNull final Locale locale, @NotNull final String bundleName, @NotNull final String systemProperty,
        final boolean useClassLoader, @Nullable final ResourceBundle firstBundle,
        @Nullable final ResourceBundle secondBundle, final boolean retryBundles) {
    ResourceBundle t_FirstBundle = firstBundle;
    ResourceBundle t_SecondBundle = secondBundle;

    if (retryBundles) {
        ClassLoader t_ClassLoader = getClass().getClassLoader();

        if (useClassLoader) {
            // Identify the class loader we will be using
            final ClassLoader t_AnotherClassLoader = AccessController
                    .doPrivileged(new PrivilegedAction<ClassLoader>() {
                        public ClassLoader run() {
                            ClassLoader result = null;

                            try {
                                result = getContextClassLoader();
                            } catch (final IllegalAccessException exception) {
                                // We'll use the Class.getClassLoader();
                            } catch (final InvocationTargetException exception) {
                                // We'll use the Class.getClassLoader();
                            }

                            return result;
                        }
                    });

            if (t_AnotherClassLoader != null) {
                t_ClassLoader = t_AnotherClassLoader;
            }
        }

        if (t_FirstBundle == null) {
            t_FirstBundle = retrieveSystemPropertyBundle(systemProperty, locale, t_ClassLoader);

            if (t_FirstBundle != null) {
                setFirstBundle(t_FirstBundle);
            }
        }

        if (t_SecondBundle == null) {
            t_SecondBundle = retrieveBundle(bundleName, locale, t_ClassLoader);

            if (t_SecondBundle != null) {
                setSecondBundle(t_SecondBundle);
            }
        }

        setRetryBundles(false);
    }

    return buildMessage(key, params, t_FirstBundle, t_SecondBundle);
}

From source file:org.apache.tuscany.sca.binding.ws.axis2.provider.Axis2ReferenceBindingProvider.java

public Invoker createInvoker(Operation operation) {
    Options options = new Options();
    org.apache.axis2.addressing.EndpointReference epTo = getWSATOEPR(wsBinding);
    if (epTo != null) {
        options.setTo(epTo);//from w w w .  j a va  2 s  .c  o  m
    }
    options.setProperty(HTTPConstants.CHUNKED, Boolean.FALSE);

    String operationName = operation.getName();

    String soapAction = getSOAPAction(operationName);
    if (soapAction != null && soapAction.length() > 1) {
        options.setAction(soapAction);
    }

    options.setTimeOutInMilliSeconds(30 * 1000); // 30 seconds

    // Allow privileged access to read properties. Requires PropertiesPermission read in
    // security policy.
    SOAPFactory soapFactory = AccessController.doPrivileged(new PrivilegedAction<SOAPFactory>() {
        public SOAPFactory run() {
            if (isSOAP12Required)
                return OMAbstractFactory.getSOAP12Factory();
            else
                return OMAbstractFactory.getSOAP11Factory();

        }
    });
    QName wsdlOperationQName = new QName(operationName);
    if (isMTOMRequired) {
        options.setProperty(org.apache.axis2.Constants.Configuration.ENABLE_MTOM,
                org.apache.axis2.Constants.VALUE_TRUE);
    }

    return new Axis2ReferenceBindingInvoker(endpointReference, serviceClient, wsdlOperationQName, options,
            soapFactory, wsBinding);

    /*        
            if (operation.isNonBlocking()) {
    invoker = new Axis2OneWayBindingInvoker(this, wsdlOperationQName, options, soapFactory, wsBinding);
            } else {
    invoker = new Axis2BindingInvoker(endpointReference, serviceClient, wsdlOperationQName, options, soapFactory, wsBinding);
            }
                    
            return invoker;
    */
}

From source file:com.mirth.connect.client.core.Client.java

@SuppressWarnings("unchecked")
public <T> T getServlet(final Class<T> servletInterface, final ExecuteType executeType) {
    return (T) Proxy.newProxyInstance(
            AccessController.doPrivileged(ReflectionHelper.getClassLoaderPA(servletInterface)),
            new Class[] { servletInterface }, new InvocationHandler() {
                @Override//www.j a  va  2s.c om
                public Object invoke(Object proxy, Method method, Object[] args) throws ClientException {
                    try {
                        WebTarget target = client.target(api);

                        Operation operation = OperationUtil.getOperation(servletInterface, method);
                        if (operation != null) {
                            target.property(ServerConnection.OPERATION_PROPERTY, operation);
                        }

                        if (executeType != null) {
                            target.property(ServerConnection.EXECUTE_TYPE_PROPERTY, executeType);
                        }

                        if (args == null && method.getName().equals("toString")) {
                            return target.toString();
                        }

                        T resource = WebResourceFactory.newResource(servletInterface, target);
                        Object result = method.invoke(resource, args);

                        // Make sure to return the right type
                        if (result == null && method.getReturnType().isPrimitive()) {
                            return method.getReturnType() == boolean.class ? false : (byte) 0x00;
                        }
                        return result;
                    } catch (Throwable t) {
                        Throwable cause = t;
                        if (cause instanceof InvocationTargetException && cause.getCause() != null) {
                            cause = cause.getCause();
                        }
                        if (cause instanceof ProcessingException && cause.getCause() != null) {
                            cause = cause.getCause();
                        }
                        if (cause instanceof ClientException) {
                            throw (ClientException) cause;
                        } else {
                            throw new ClientException(cause);
                        }
                    }
                }
            });
}

From source file:com.fitbur.testify.junit.system.SpringBootSystemTest.java

@Override
protected Statement methodBlock(FrameworkMethod method) {
    TestClass testClass = getTestClass();
    Class<?> javaClass = testClass.getJavaClass();

    Object testInstance;//from  w ww .jav  a 2  s.  co m

    try {
        testInstance = createTest();
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    TestContext testContext = getTestContext(javaClass);
    testContext.setTestInstance(testInstance);

    Optional<App> appOptional = testContext.getAnnotation(App.class);
    checkState(appOptional.isPresent(), "Test class '%s' is not annotated with @App annotation.",
            testClass.getName());

    App app = appOptional.get();
    Set<Class<?>> modules = testContext.getAnnotations(Module.class).parallelStream().map(p -> p.value())
            .collect(toSet());

    Set<Object> sources = new LinkedHashSet<>();
    sources.add(app.value());
    sources.addAll(modules);

    application = new SpringApplicationBuilder(sources.toArray()).bannerMode(Banner.Mode.OFF).build();

    APPLICATION_TEST_CONTEXTS.computeIfAbsent(application, p -> testContext);

    application.run();

    SpringBootDescriptor descriptor = APPLICATION_DESCRIPTORS.get(application);

    ServiceLocator serviceLocator = descriptor.getServiceLocator();
    serviceLocator.addConstant(descriptor.getClass().getSimpleName(), descriptor);

    try {
        URI baseURI = new URI("http", null, "0.0.0.0", descriptor.getServletContainer().getPort(),
                descriptor.getServletContext().getContextPath(), null, null);

        SpringBootClientDescriptor clientDescriptor = new SpringBootClientDescriptor(app, testContext, baseURI);
        ServiceLoader<ClientProvider> clientProviderLoader = ServiceLoader.load(ClientProvider.class);
        ArrayList<ClientProvider> clientProviders = Lists.newArrayList(clientProviderLoader);

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

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

        testContext.getConfigMethod(context.getClass()).map(m -> m.getMethod()).ifPresent(m -> {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                try {
                    m.setAccessible(true);
                    m.invoke(testInstance, context);
                } catch (Exception e) {
                    checkState(false, "Call to config method '%s' in test class '%s' failed due to: ",
                            m.getName(), clientDescriptor.getTestClassName(), e.getMessage());
                }

                return null;
            });
        });

        serverInstance = new SpringBootServerInstance(descriptor.getServletContainer(), baseURI);
        serviceLocator.addConstant(serverInstance.getClass().getSimpleName(), serverInstance);

        clientInstance = clientProvider.init(clientDescriptor, context);
        serviceLocator.addConstant(clientInstance.getClass().getSimpleName(), clientInstance);

        TestCaseInstance testCaseInstance = new TestCaseInstance(method.getName(), testInstance);
        serviceLocator.addConstant(testCaseInstance.getTestName(), testCaseInstance);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    SystemTestReifier reifier = new SystemTestReifier(testContext, serviceLocator, testInstance);
    SystemTestCreator creator = new SystemTestCreator(testContext, reifier, serviceLocator);

    if (testContext.getCutDescriptor() != null) {
        creator.cut();
    }

    Set<FieldDescriptor> real = testContext.getFieldDescriptors().values().parallelStream()
            .filter(p -> !p.getInstance().isPresent())
            .filter(p -> p.hasAnnotations(descriptor.getServiceAnnotations().getInjectors())).collect(toSet());

    creator.real(real);

    SystemTestVerifier verifier = new SystemTestVerifier(testContext, LOGGER);
    verifier.wiring();

    Statement statement = methodInvoker(method, testInstance);
    statement = possiblyExpectingExceptions(method, testInstance, statement);
    statement = withBefores(method, testInstance, statement);
    statement = withAfters(method, testInstance, statement);
    statement = withRules(method, testInstance, statement);

    return statement;
}

From source file:org.apache.openjpa.enhance.PCEnhancer.java

/**
 * Constructor. Supply configuration and type to enhance. This will look
 * up the metadata for <code>type</code> from <code>conf</code>'s
 * repository./*w  ww  . j a  v  a 2 s  .co m*/
 */
public PCEnhancer(OpenJPAConfiguration conf, Class type) {
    this(conf, AccessController.doPrivileged(J2DoPrivHelper.loadProjectClassAction(new Project(), type)),
            (MetaDataRepository) null);
}

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

public Object findAttribute(final String name) {
    if (SecurityUtil.isPackageProtectionEnabled()) {
        return AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                if (name == null) {
                    throw new NullPointerException(Localizer.getMessage("jsp.error.attribute.null_name"));
                }//from  ww  w . j a va2s  .  c  o  m

                return doFindAttribute(name);
            }
        });
    } else {
        if (name == null) {
            throw new NullPointerException(Localizer.getMessage("jsp.error.attribute.null_name"));
        }

        return doFindAttribute(name);
    }
}

From source file:org.apache.bsf.BSFManager.java

/**
 * Compile the given script of the given language into the given
 * <tt>CodeBuffer</tt>./*from  w  w w  . j  a va  2  s.  c  om*/
 *
 * @param lang     language identifier
 * @param source   (context info) the source of this script
 (e.g., filename)
 * @param lineNo   (context info) the line number in source for script
 * @param columnNo (context info) the column number in source for script
 * @param script   the script to compile
 * @param cb       code buffer to compile into
 *
 * @exception BSFException if any error while compiling the script
 */
public void compileScript(String lang, String source, int lineNo, int columnNo, Object script, CodeBuffer cb)
        throws BSFException {
    logger.debug("BSFManager:compileScript");

    final BSFEngine e = loadScriptingEngine(lang);
    final String sourcef = source;
    final int lineNof = lineNo, columnNof = columnNo;
    final Object scriptf = script;
    final CodeBuffer cbf = cb;

    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws Exception {
                e.compileScript(sourcef, lineNof, columnNof, scriptf, cbf);
                return null;
            }
        });
    } catch (PrivilegedActionException prive) {

        logger.error("Exception :", prive);
        throw (BSFException) prive.getException();
    }
}