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.codice.solr.factory.impl.HttpClientBuilder.java

private CredentialsProvider getCredentialsProvider() {
    CredentialsProvider provider = new BasicCredentialsProvider();

    org.apache.http.auth.UsernamePasswordCredentials credentials = new org.apache.http.auth.UsernamePasswordCredentials(
            AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getProperty("solr.username")),
            getPlainTextSolrPassword());
    provider.setCredentials(AuthScope.ANY, credentials);
    return provider;
}

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

public void releasePageContext(PageContext pc) {
    if (pc == null)
        return;//  ww  w  . ja  v a 2 s  .  c om
    if (System.getSecurityManager() != null) {
        PrivilegedReleasePageContext dp = new PrivilegedReleasePageContext((JspFactoryImpl) this, pc);
        AccessController.doPrivileged(dp);
    } else {
        internalReleasePageContext(pc);
    }
}

From source file:com.fitbur.jestify.junit.spring.IntegrationTestReifier.java

@Override
public Object reifyCut(CutDescriptor cutDescriptor, Object[] arguments) {
    return AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
        try {// w  w w.  jav  a  2 s.  co  m
            Cut cut = cutDescriptor.getCut();
            Field field = cutDescriptor.getField();
            Type fieldType = field.getGenericType();
            String fieldName = field.getName();

            field.setAccessible(true);

            Constructor<?> constructor = cutDescriptor.getConstructor();
            constructor.setAccessible(true);

            ResolvableType resolver = ResolvableType.forType(fieldType);

            Class rawType;

            if (resolver.hasGenerics()) {
                if (resolver.isAssignableFrom(Provider.class) || resolver.isAssignableFrom(Optional.class)) {
                    rawType = resolver.getRawClass();
                } else {
                    rawType = resolver.resolve();
                }
            } else {
                rawType = resolver.resolve();
            }

            Module module = testInstance.getClass().getDeclaredAnnotation(Module.class);

            GenericBeanDefinition bean = new GenericBeanDefinition();
            bean.setBeanClass(rawType);
            bean.setAutowireCandidate(false);
            bean.setScope(SCOPE_PROTOTYPE);
            bean.setPrimary(true);
            bean.setLazyInit(true);
            bean.setRole(RootBeanDefinition.ROLE_APPLICATION);
            bean.setAutowireMode(RootBeanDefinition.AUTOWIRE_NO);
            appContext.registerBeanDefinition(fieldName, bean);
            if (module != null) {
                appContext.register(module.value());
            }
            appContext.refresh();

            Object instance = appContext.getBean(fieldName, arguments);

            if (cut.value()) {
                instance = spy(instance);
            }

            field.set(testInstance, instance);

            return instance;
        } catch (SecurityException | IllegalAccessException | IllegalArgumentException e) {
            throw new RuntimeException(e);
        }
    });
}

From source file:com.asakusafw.runtime.stage.launcher.ApplicationLauncher.java

/**
 * Sets the context class loader and returns the current one.
 * @param classLoader the new context class loader
 * @return the current context class loader
 * @since 0.7.1/*  ww  w .  j  ava2  s  .  c  o m*/
 */
public static ClassLoader switchContextClassLoader(ClassLoader classLoader) {
    return AccessController.doPrivileged((PrivilegedAction<ClassLoader>) () -> {
        ClassLoader old = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(classLoader);
        return old;
    });
}

From source file:org.apache.openjpa.jdbc.sql.DBDictionaryFactory.java

/**
 * Create the dictionary using the given class name and properties; the
 * connection may be null if not supplied to the factory.
 *///from  w  w  w. j a  va 2s  .co  m
private static DBDictionary newDBDictionary(JDBCConfiguration conf, String dclass, String props,
        Connection conn) {
    DBDictionary dict = null;
    try {
        Class<?> c = Class.forName(dclass, true,
                AccessController.doPrivileged(J2DoPrivHelper.getClassLoaderAction(DBDictionary.class)));
        dict = (DBDictionary) AccessController.doPrivileged(J2DoPrivHelper.newInstanceAction(c));
    } catch (ClassNotFoundException cnfe) {
        // if the dictionary was not found, make another attempt
        // at loading the dictionary using the current thread.
        try {
            Class<?> c = Thread.currentThread().getContextClassLoader().loadClass(dclass);
            dict = (DBDictionary) AccessController.doPrivileged(J2DoPrivHelper.newInstanceAction(c));
        } catch (Exception e) {
            if (e instanceof PrivilegedActionException)
                e = ((PrivilegedActionException) e).getException();
            throw new UserException(e).setFatal(true);
        }
    } catch (Exception e) {
        if (e instanceof PrivilegedActionException)
            e = ((PrivilegedActionException) e).getException();
        throw new UserException(e).setFatal(true);
    }

    // warn if we could not locate the appropriate dictionary
    Log log = conf.getLog(JDBCConfiguration.LOG_JDBC);
    if (log.isWarnEnabled() && dict.getClass() == DBDictionary.class)
        log.warn(_loc.get("warn-generic"));

    if (log.isInfoEnabled()) {
        String infoString = "";
        if (conn != null) {
            try {
                DatabaseMetaData meta = conn.getMetaData();
                infoString = " (" + meta.getDatabaseProductName() + " " + meta.getDatabaseProductVersion()
                        + " ," + meta.getDriverName() + " " + meta.getDriverVersion() + ")";
            } catch (SQLException se) {
                if (log.isTraceEnabled())
                    log.trace(se.toString(), se);
            }
        }

        log.info(_loc.get("using-dict", dclass, infoString));
    }

    // set the dictionary's metadata
    Configurations.configureInstance(dict, conf, props, "DBDictionary");
    if (conn != null) {
        try {
            dict.connectedConfiguration(conn);
        } catch (SQLException se) {
            throw new StoreException(se).setFatal(true);
        }
    }
    return dict;
}

From source file:org.eclipse.gemini.blueprint.config.internal.adapter.OsgiServiceLifecycleListenerAdapter.java

/**
 * Initialise adapter. Determine custom methods and do validation.
 *///from w  ww  .j  a va2  s.co  m
private void initialize() {

    Class<?> clazz = (target == null ? beanFactory.getType(targetBeanName) : target.getClass());

    Assert.notNull(clazz, "listener " + targetBeanName + " class type cannot be determined");

    isLifecycleListener = OsgiServiceLifecycleListener.class.isAssignableFrom(clazz);
    if (isLifecycleListener)
        if (log.isDebugEnabled())
            log.debug(clazz.getName() + " is a lifecycle listener");

    bindMethods = CustomListenerAdapterUtils.determineCustomMethods(clazz, bindMethod, isBlueprintCompliant);

    boolean isSecurityEnabled = System.getSecurityManager() != null;
    final Class<?> clz = clazz;

    // determine methods using ServiceReference signature
    if (StringUtils.hasText(bindMethod)) {
        if (isSecurityEnabled) {
            bindReference = AccessController.doPrivileged(new PrivilegedAction<Method>() {
                public Method run() {
                    return findServiceReferenceMethod(clz, bindMethod);
                }
            });
        } else {
            bindReference = findServiceReferenceMethod(clz, bindMethod);
        }

        if (bindMethods.isEmpty()) {
            String beanName = (target == null ? "" : " bean [" + targetBeanName + "] ;");
            throw new IllegalArgumentException(
                    "Custom bind method [" + bindMethod + "] not found on " + beanName + "class " + clazz);
        }
    }

    unbindMethods = CustomListenerAdapterUtils.determineCustomMethods(clazz, unbindMethod,
            isBlueprintCompliant);

    if (StringUtils.hasText(unbindMethod)) {
        if (isSecurityEnabled) {
            unbindReference = AccessController.doPrivileged(new PrivilegedAction<Method>() {
                public Method run() {
                    return findServiceReferenceMethod(clz, unbindMethod);
                }
            });
        } else {
            unbindReference = findServiceReferenceMethod(clz, unbindMethod);
        }

        if (unbindMethods.isEmpty()) {
            String beanName = (target == null ? "" : " bean [" + targetBeanName + "] ;");
            throw new IllegalArgumentException(
                    "Custom unbind method [" + unbindMethod + "] not found on " + beanName + "class " + clazz);
        }
    }

    if (!isLifecycleListener && (bindMethods.isEmpty() && unbindMethods.isEmpty() && bindReference == null
            && unbindReference == null))
        throw new IllegalArgumentException(
                "target object needs to implement " + OsgiServiceLifecycleListener.class.getName()
                        + " or custom bind/unbind methods have to be specified");

    if (log.isTraceEnabled()) {
        StringBuilder builder = new StringBuilder();
        builder.append("Discovered bind methods=");
        builder.append(bindMethods.values());
        builder.append(", bind ServiceReference=");
        builder.append(bindReference);
        builder.append("\nunbind methods=");
        builder.append(unbindMethods.values());
        builder.append(", unbind ServiceReference=");
        builder.append(unbindReference);
        log.trace(builder.toString());
    }
}

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

/**
 * Set of semicolon-separated {@link File}s of metadata files or
 * directories supplied by user via auto-configuration.
 *//*ww  w. ja va2s  . c o m*/
public void setFiles(String files) {
    if (StringUtils.isEmpty(files))
        this.files = null;
    else {
        String[] strs = Strings.split(files, ";", 0);
        this.files = new HashSet<File>((int) (strs.length * 1.33 + 1));

        File file;
        for (int i = 0; i < strs.length; i++) {
            file = new File(strs[i]);
            if ((AccessController.doPrivileged(J2DoPrivHelper.existsAction(file))).booleanValue())
                this.files.add(file);
        }
    }
}

From source file:io.syndesis.maven.ExtractConnectorDescriptorsMojo.java

private URLClassLoader createClassLoader(File jar) throws MalformedURLException {
    return AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {
        public URLClassLoader run() {
            try {
                return new URLClassLoader(new URL[] { jar.toURI().toURL() });
            } catch (MalformedURLException e) {
                return null;
            }/*from   ww  w  .  j a  v  a 2  s.c  o m*/
        }
    });
}

From source file:Main.java

/**
 * returns canAccessSystemClipboard field from InputEvent
 *
 * @param ie InputEvent to get the field from
 *//*w  w w  .ja  va  2s .c o  m*/
private static synchronized boolean inputEvent_canAccessSystemClipboard(InputEvent ie) {
    if (inputEvent_CanAccessSystemClipboard_Field == null) {
        inputEvent_CanAccessSystemClipboard_Field = AccessController
                .doPrivileged(new java.security.PrivilegedAction<Field>() {
                    public Field run() {
                        try {
                            Field field = InputEvent.class.getDeclaredField("canAccessSystemClipboard");
                            field.setAccessible(true);
                            return field;
                        } catch (SecurityException e) {
                        } catch (NoSuchFieldException e) {
                        }
                        return null;
                    }
                });
    }
    if (inputEvent_CanAccessSystemClipboard_Field == null) {
        return false;
    }
    boolean ret = false;
    try {
        ret = inputEvent_CanAccessSystemClipboard_Field.getBoolean(ie);
    } catch (IllegalAccessException e) {
    }
    return ret;
}

From source file:tech.beshu.ror.httpclient.ApacheHttpCoreClient.java

@Override
public CompletableFuture<RRHttpResponse> send(RRHttpRequest request) {

    CompletableFuture<HttpResponse> promise = new CompletableFuture<>();
    URI uri;/*  w  w w  .  j a v a 2s.  c  o m*/
    HttpRequestBase hcRequest;
    try {
        if (request.getMethod() == HttpMethod.POST) {
            uri = new URIBuilder(request.getUrl().toASCIIString()).build();
            hcRequest = new HttpPost(uri);
            List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
            request.getQueryParams().entrySet()
                    .forEach(x -> urlParameters.add(new BasicNameValuePair(x.getKey(), x.getValue())));
            ((HttpPost) hcRequest).setEntity(new UrlEncodedFormEntity(urlParameters));

        } else {
            uri = new URIBuilder(request.getUrl().toASCIIString()).addParameters(request.getQueryParams()
                    .entrySet().stream().map(e -> new BasicNameValuePair(e.getKey(), e.getValue()))
                    .collect(Collectors.toList())).build();
            hcRequest = new HttpGet(uri);
        }
    } catch (URISyntaxException e) {
        throw context.rorException(e.getClass().getSimpleName() + ": " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        throw context.rorException(e.getClass().getSimpleName() + ": " + e.getMessage());
    }

    request.getHeaders().entrySet().forEach(e -> hcRequest.addHeader(e.getKey(), e.getValue()));

    AccessController.doPrivileged((PrivilegedAction<Void>) () -> {

        hcHttpClient.execute(hcRequest, new FutureCallback<HttpResponse>() {

            public void completed(final HttpResponse hcResponse) {
                int statusCode = hcResponse.getStatusLine().getStatusCode();
                logger.debug("HTTP REQ SUCCESS with status: " + statusCode + " " + request);
                promise.complete(hcResponse);
            }

            public void failed(final Exception ex) {
                logger.debug("HTTP REQ FAILED " + request);
                logger.info("HTTP client failed to connect: " + request + " reason: " + ex.getMessage());
                promise.completeExceptionally(ex);
            }

            public void cancelled() {
                promise.completeExceptionally(new RuntimeException("HTTP REQ CANCELLED: " + request));
            }
        });
        return null;
    });

    return promise.thenApply(hcResp -> new RRHttpResponse(hcResp.getStatusLine().getStatusCode(), () -> {
        try {
            return hcResp.getEntity().getContent();
        } catch (IOException e) {
            throw new RuntimeException("Cannot read content", e);
        }
    }));

}