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.axiom.om.util.StAXUtils.java

private static XMLOutputFactory newXMLOutputFactory(final ClassLoader classLoader,
        final StAXWriterConfiguration configuration) {
    return (XMLOutputFactory) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            ClassLoader savedClassLoader;
            if (classLoader == null) {
                savedClassLoader = null;
            } else {
                savedClassLoader = Thread.currentThread().getContextClassLoader();
                Thread.currentThread().setContextClassLoader(classLoader);
            }/*from   w ww.j  a  v a 2  s.co m*/
            try {
                XMLOutputFactory factory = XMLOutputFactory.newInstance();
                factory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.FALSE);
                Map props = loadFactoryProperties("XMLOutputFactory.properties");
                if (props != null) {
                    for (Iterator it = props.entrySet().iterator(); it.hasNext();) {
                        Map.Entry entry = (Map.Entry) it.next();
                        factory.setProperty((String) entry.getKey(), entry.getValue());
                    }
                }
                StAXDialect dialect = StAXDialectDetector.getDialect(factory.getClass());
                if (configuration != null) {
                    factory = configuration.configure(factory, dialect);
                }
                return new ImmutableXMLOutputFactory(dialect.normalize(dialect.makeThreadSafe(factory)));
            } finally {
                if (savedClassLoader != null) {
                    Thread.currentThread().setContextClassLoader(savedClassLoader);
                }
            }
        }
    });
}

From source file:org.apache.openjpa.persistence.PersistenceMetaDataDefaults.java

/**
 * May be used to determine if member is annotated with the specified 
 * access type./* w ww .  j  a  v a 2s  . c o  m*/
 * @param member class member
 * @param type expected access type
 * @return true if access is specified on member and that access
 *         type matches the expected type
 */
private boolean isAnnotatedAccess(Member member, AccessType type) {
    if (member == null)
        return false;
    Access anno = AccessController
            .doPrivileged(J2DoPrivHelper.getAnnotationAction((AnnotatedElement) member, Access.class));
    return anno != null && anno.value() == type;
}

From source file:org.apache.openjpa.util.ProxyManagerImpl.java

/**
 * Generate the bytecode for a bean proxy for the given type.
 *//*from w ww . j  av a  2 s .  c  om*/
protected BCClass generateProxyBeanBytecode(Class type, boolean runtime) {
    if (Modifier.isFinal(type.getModifiers()))
        return null;
    if (ImplHelper.isManagedType(null, type))
        return null;

    // we can only generate a valid proxy if there is a copy constructor
    // or a default constructor
    Constructor cons = findCopyConstructor(type);
    if (cons == null) {
        Constructor[] cs = type.getConstructors();
        for (int i = 0; cons == null && i < cs.length; i++)
            if (cs[i].getParameterTypes().length == 0)
                cons = cs[i];
        if (cons == null)
            return null;
    }

    Project project = new Project();
    BCClass bc = AccessController
            .doPrivileged(J2DoPrivHelper.loadProjectClassAction(project, getProxyClassName(type, runtime)));
    bc.setSuperclass(type);
    bc.declareInterface(ProxyBean.class);

    delegateConstructors(bc, type);
    addProxyMethods(bc, true);
    addProxyBeanMethods(bc, type, cons);
    if (!proxySetters(bc, type))
        return null;
    addWriteReplaceMethod(bc, runtime);
    return bc;
}

From source file:org.elasticsearch.xpack.core.ssl.SSLConfigurationReloaderTests.java

private static void privilegedConnect(CheckedRunnable<Exception> runnable) throws Exception {
    try {/*from w  ww.  j  a  v  a2  s  .  com*/
        AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
            runnable.run();
            return null;
        });
    } catch (PrivilegedActionException e) {
        throw (Exception) e.getCause();
    }
}

From source file:org.apache.catalina.core.ContainerBase.java

/**
 * Add a new child Container to those associated with this Container,
 * if supported.  Prior to adding this Container to the set of children,
 * the child's <code>setParent()</code> method must be called, with this
 * Container as an argument.  This method may thrown an
 * <code>IllegalArgumentException</code> if this Container chooses not
 * to be attached to the specified Container, in which case it is not added
 *
 * @param child New child Container to be added
 *
 * @exception IllegalArgumentException if this exception is thrown by
 *  the <code>setParent()</code> method of the child Container
 * @exception IllegalArgumentException if the new child does not have
 *  a name unique from that of existing children of this Container
 * @exception IllegalStateException if this Container does not support
 *  child Containers/*from w w w.  ja va2s .  c om*/
 */
public void addChild(Container child) {
    if (System.getSecurityManager() != null) {
        PrivilegedAction dp = new PrivilegedAddChild(child);
        AccessController.doPrivileged(dp);
    } else {
        addChildInternal(child);
    }
}

From source file:org.apache.catalina.session.PersistentManagerBase.java

/**
 * Write the provided session to the Store without modifying
 * the copy in memory or triggering passivation events. Does
 * nothing if the session is invalid or past its expiration.
 */// www.ja  v  a 2  s .c  om
protected void writeSession(Session session) throws IOException {

    if (store == null || !session.isValid()) {
        return;
    }

    try {
        if (System.getSecurityManager() != null) {
            try {
                AccessController.doPrivileged(new PrivilegedStoreSave(session));
            } catch (PrivilegedActionException ex) {
                Exception exception = ex.getException();
                log.error("Exception clearing the Store: " + exception);
                exception.printStackTrace();
            }
        } else {
            store.save(session);
        }
    } catch (IOException e) {
        log.error(sm.getString("persistentManager.serializeError", session.getId(), e));
        throw e;
    }

}

From source file:org.elasticsearch.xpack.security.authc.saml.SamlRealm.java

private static Tuple<AbstractReloadingMetadataResolver, Supplier<EntityDescriptor>> parseHttpMetadata(
        String metadataUrl, RealmConfig config, SSLService sslService)
        throws ResolverException, ComponentInitializationException, PrivilegedActionException {
    final String entityId = require(config, IDP_ENTITY_ID);

    HttpClientBuilder builder = HttpClientBuilder.create();
    // ssl setup/*from  w  ww. j  av a 2 s . c  om*/
    Settings sslSettings = config.settings().getByPrefix(SamlRealmSettings.SSL_PREFIX);
    boolean isHostnameVerificationEnabled = sslService.getVerificationMode(sslSettings, Settings.EMPTY)
            .isHostnameVerificationEnabled();
    HostnameVerifier verifier = isHostnameVerificationEnabled ? new DefaultHostnameVerifier()
            : NoopHostnameVerifier.INSTANCE;
    SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(
            sslService.sslSocketFactory(sslSettings), verifier);
    builder.setSSLSocketFactory(factory);

    HTTPMetadataResolver resolver = new PrivilegedHTTPMetadataResolver(builder.build(), metadataUrl);
    TimeValue refresh = IDP_METADATA_HTTP_REFRESH.get(config.settings());
    resolver.setMinRefreshDelay(refresh.millis());
    resolver.setMaxRefreshDelay(refresh.millis());
    initialiseResolver(resolver, config);

    return new Tuple<>(resolver, () -> {
        // for some reason the resolver supports its own trust engine and custom socket factories.
        // we do not use these as we'd rather rely on the JDK versions for TLS security!
        SpecialPermission.check();
        try {
            return AccessController.doPrivileged(
                    (PrivilegedExceptionAction<EntityDescriptor>) () -> resolveEntityDescriptor(resolver,
                            entityId, metadataUrl));
        } catch (PrivilegedActionException e) {
            throw ExceptionsHelper.convertToRuntime((Exception) ExceptionsHelper.unwrapCause(e));
        }
    });
}

From source file:org.cruxframework.crux.tools.compile.AbstractCruxCompiler.java

/**
 * //from  w  w  w.j  a  v a2 s.  com
 */
private void restoreSecurityManager() {
    AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
        public Boolean run() {
            System.setSecurityManager(originalSecurityManager);
            return true;
        }
    });
}

From source file:org.cruxframework.crux.tools.compile.AbstractCruxCompiler.java

/**
 * //  w w  w .j  a  va 2 s .  c o  m
 */
private void setSecurityManagerToAvoidSystemExit() {
    AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
        public Boolean run() {
            originalSecurityManager = System.getSecurityManager();
            System.setSecurityManager(new SecurityManager() {

                @Override
                public void checkExit(int status) {
                    if (status == 0) {
                        throw new DoNotExitException();
                    }
                    super.checkExit(status);
                }

                @Override
                public void checkPermission(Permission perm) {
                }

                @Override
                public void checkPermission(Permission perm, Object context) {
                }
            });
            return true;
        }
    });
}

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

/**
 * Proprietary method to evaluate EL expressions.
 * XXX - This method should go away once the EL interpreter moves
 * out of JSTL and into its own project.  For now, this is necessary
 * because the standard machinery is too slow.
 *
 * @param expression   The expression to be evaluated
 * @param expectedType The expected resulting type
 * @param pageContext  The page context//  w  w  w  .j  a  v  a2  s  .c om
 * @param functionMap  Maps prefix and name to Method
 * @return The result of the evaluation
 */
public static Object proprietaryEvaluate(final String expression, final Class expectedType,
        final PageContext pageContext, final ProtectedFunctionMapper functionMap, final boolean escape)
        throws ELException {
    Object retValue;
    if (SecurityUtil.isPackageProtectionEnabled()) {
        try {
            retValue = AccessController.doPrivileged(new PrivilegedExceptionAction() {

                public Object run() throws Exception {
                    return elExprEval.evaluate(expression, expectedType, pageContext.getVariableResolver(),
                            functionMap);
                }
            });
        } catch (PrivilegedActionException ex) {
            Exception realEx = ex.getException();
            if (realEx instanceof ELException) {
                throw (ELException) realEx;
            } else {
                throw new ELException(realEx);
            }
        }
    } else {
        retValue = elExprEval.evaluate(expression, expectedType, pageContext.getVariableResolver(),
                functionMap);
    }
    if (escape) {
        retValue = XmlEscape(retValue.toString());
    }

    return retValue;
}