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.stanbol.commons.opennlp.OpenNLP.java

/**
 * Lookup an openNLP data file via the {@link #dataFileProvider}
 * @param modelName the name of the model
 * @return the stream or <code>null</code> if not found
 * @throws IOException an any error while opening the model file
 *//*  w  ww .ja  v  a 2s .c  o m*/
protected InputStream lookupModelStream(final String modelName, final Map<String, String> properties)
        throws IOException {
    try {
        return AccessController.doPrivileged(new PrivilegedExceptionAction<InputStream>() {
            public InputStream run() throws IOException {
                return dataFileProvider.getInputStream(null, modelName, properties);
            }
        });
    } catch (PrivilegedActionException pae) {
        Exception e = pae.getException();
        if (e instanceof IOException) {
            throw (IOException) e;
        } else {
            throw RuntimeException.class.cast(e);
        }
    }
}

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

/**
 * Load and initialize an instance of this servlet, if there is not already
 * at least one initialized instance.  This can be used, for example, to
 * load servlets that are marked in the deployment descriptor to be loaded
 * at server startup time.//w  w w  .  j av a 2 s .c o  m
 */
public synchronized Servlet loadServlet() throws ServletException {

    // Nothing to do if we already have an instance or an instance pool
    if (!singleThreadModel && (instance != null))
        return instance;

    PrintStream out = System.out;
    if (swallowOutput) {
        SystemLogHandler.startCapture();
    }

    Servlet servlet;
    try {
        long t1 = System.currentTimeMillis();
        // If this "servlet" is really a JSP file, get the right class.
        // HOLD YOUR NOSE - this is a kludge that avoids having to do special
        // case Catalina-specific code in Jasper - it also requires that the
        // servlet path be replaced by the <jsp-file> element content in
        // order to be completely effective
        String actualClass = servletClass;
        if ((actualClass == null) && (jspFile != null)) {
            Wrapper jspWrapper = (Wrapper) ((Context) getParent()).findChild(Constants.JSP_SERVLET_NAME);
            if (jspWrapper != null)
                actualClass = jspWrapper.getServletClass();
        }

        // Complain if no servlet class has been specified
        if (actualClass == null) {
            unavailable(null);
            throw new ServletException(sm.getString("standardWrapper.notClass", getName()));
        }

        // Acquire an instance of the class loader to be used
        Loader loader = getLoader();
        if (loader == null) {
            unavailable(null);
            throw new ServletException(sm.getString("standardWrapper.missingLoader", getName()));
        }

        ClassLoader classLoader = loader.getClassLoader();

        // Special case class loader for a container provided servlet
        //  
        if (isContainerProvidedServlet(actualClass) && !((Context) getParent()).getPrivileged()) {
            // If it is a priviledged context - using its own
            // class loader will work, since it's a child of the container
            // loader
            classLoader = this.getClass().getClassLoader();
        }

        // Load the specified servlet class from the appropriate class loader
        Class classClass = null;
        try {
            if (System.getSecurityManager() != null) {
                final ClassLoader fclassLoader = classLoader;
                final String factualClass = actualClass;
                try {
                    classClass = (Class) AccessController.doPrivileged(new PrivilegedExceptionAction() {
                        public Object run() throws Exception {
                            if (fclassLoader != null) {
                                return fclassLoader.loadClass(factualClass);
                            } else {
                                return Class.forName(factualClass);
                            }
                        }
                    });
                } catch (PrivilegedActionException pax) {
                    Exception ex = pax.getException();
                    if (ex instanceof ClassNotFoundException) {
                        throw (ClassNotFoundException) ex;
                    } else {
                        getServletContext().log("Error loading " + fclassLoader + " " + factualClass, ex);
                    }
                }
            } else {
                if (classLoader != null) {
                    classClass = classLoader.loadClass(actualClass);
                } else {
                    classClass = Class.forName(actualClass);
                }
            }
        } catch (ClassNotFoundException e) {
            unavailable(null);

            getServletContext().log("Error loading " + classLoader + " " + actualClass, e);
            throw new ServletException(sm.getString("standardWrapper.missingClass", actualClass), e);
        }

        if (classClass == null) {
            unavailable(null);
            throw new ServletException(sm.getString("standardWrapper.missingClass", actualClass));
        }

        // Instantiate and initialize an instance of the servlet class itself
        try {
            servlet = (Servlet) classClass.newInstance();
        } catch (ClassCastException e) {
            unavailable(null);
            // Restore the context ClassLoader
            throw new ServletException(sm.getString("standardWrapper.notServlet", actualClass), e);
        } catch (Throwable e) {
            unavailable(null);
            // Restore the context ClassLoader
            throw new ServletException(sm.getString("standardWrapper.instantiate", actualClass), e);
        }

        // Check if loading the servlet in this web application should be
        // allowed
        if (!isServletAllowed(servlet)) {
            throw new SecurityException(sm.getString("standardWrapper.privilegedServlet", actualClass));
        }

        // Special handling for ContainerServlet instances
        if ((servlet instanceof ContainerServlet)
                && (isContainerProvidedServlet(actualClass) || ((Context) getParent()).getPrivileged())) {
            ((ContainerServlet) servlet).setWrapper(this);
        }

        classLoadTime = (int) (System.currentTimeMillis() - t1);
        // Call the initialization method of this servlet
        try {
            instanceSupport.fireInstanceEvent(InstanceEvent.BEFORE_INIT_EVENT, servlet);

            if (System.getSecurityManager() != null) {
                Class[] classType = new Class[] { ServletConfig.class };
                Object[] args = new Object[] { ((ServletConfig) facade) };
                SecurityUtil.doAsPrivilege("init", servlet, classType, args);
            } else {
                servlet.init(facade);
            }

            // Invoke jspInit on JSP pages
            if ((loadOnStartup >= 0) && (jspFile != null)) {
                // Invoking jspInit
                DummyRequest req = new DummyRequest();
                req.setServletPath(jspFile);
                req.setQueryString("jsp_precompile=true");
                DummyResponse res = new DummyResponse();

                if (System.getSecurityManager() != null) {
                    Class[] classType = new Class[] { ServletRequest.class, ServletResponse.class };
                    Object[] args = new Object[] { req, res };
                    SecurityUtil.doAsPrivilege("service", servlet, classType, args);
                } else {
                    servlet.service(req, res);
                }
            }
            instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet);
        } catch (UnavailableException f) {
            instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f);
            unavailable(f);
            throw f;
        } catch (ServletException f) {
            instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f);
            // If the servlet wanted to be unavailable it would have
            // said so, so do not call unavailable(null).
            throw f;
        } catch (Throwable f) {
            getServletContext().log("StandardWrapper.Throwable", f);
            instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f);
            // If the servlet wanted to be unavailable it would have
            // said so, so do not call unavailable(null).
            throw new ServletException(sm.getString("standardWrapper.initException", getName()), f);
        }

        // Register our newly initialized instance
        singleThreadModel = servlet instanceof SingleThreadModel;
        if (singleThreadModel) {
            if (instancePool == null)
                instancePool = new Stack();
        }
        fireContainerEvent("load", this);

        loadTime = System.currentTimeMillis() - t1;
    } finally {
        if (swallowOutput) {
            String log = SystemLogHandler.stopCapture();
            if (log != null && log.length() > 0) {
                if (getServletContext() != null) {
                    getServletContext().log(log);
                } else {
                    out.println(log);
                }
            }
        }
    }
    return servlet;

}

From source file:org.apache.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  ww . j  a v a  2  s . c  o m*/
 * @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 (System.getSecurityManager() != null) {
        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;
}

From source file:org.apache.axiom.om.util.StAXUtils.java

/**
 * @return Trhead Context ClassLoader//from  ww  w  .  j a va 2s. c o m
 */
private static ClassLoader getContextClassLoader() {
    ClassLoader cl = (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return Thread.currentThread().getContextClassLoader();
        }
    });

    return cl;
}

From source file:org.acoveo.tools.Reflection.java

/**
 * Retuns a method matching the name which takes the given parameters
 * If one of the objects in param is null, this method does not check
 * the type of this parameter./*w w w.  j  av  a2s .  c  o m*/
 * 
 * @param cls The class to search
 * @param name The name of the method
 * @param params The parameter types
 * @param mustExist Whether the method should throw an exception if no matching method has been found
 * @exception RuntimeException Thrown if mustExist == true and no matching method was found
 * @return The method or null in case none was found and mustExist == false
 */
public static Method findMethodFuzzy(Class cls, String name, Class[] params, boolean mustExist) {
    Method m;
    for (Class c = cls; c != null && c != Object.class; c = c.getSuperclass()) {
        Method[] methods = (Method[]) AccessController.doPrivileged(getDeclaredMethodsAction(cls));
        Method candidate = null;
        for (int i = 0; i < methods.length; i++) {
            if (name.equals(methods[i].getName())) {
                Class[] methodParams = methods[i].getParameterTypes();
                if (methodParams.length != params.length) {
                    continue;
                }
                boolean paramsMatch = true;
                int paramIndex = 0;
                for (Class methodParam : methodParams) {
                    if (methodParam != null && methodParam != params[paramIndex]) {
                        paramsMatch = false;
                        break;
                    }
                    paramIndex++;
                }
                if (paramsMatch) {
                    candidate = mostDerived(methods[i], candidate);
                }
            }
        }
        if (candidate != null)
            return candidate;
    }
    if (mustExist)
        throw new RuntimeException("Could not find method " + name + " in class " + cls.getCanonicalName());
    return null;
}

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

/**
 * Gets the explicit access for the class, if any.
 * Explicit access type specification does not affect the access type of
 * other entity classes or mapped super classes in the entity hierarchy.
 *///from   w  w w  .  j  av  a  2s.  co m
private int getAccessCode(Class<?> cls) {
    int accessCode = AccessCode.UNKNOWN;
    Access access = AccessController.doPrivileged(J2DoPrivHelper.getAnnotationAction(cls, Access.class));
    if (access != null) {
        accessCode |= AccessCode.EXPLICIT
                | (access.value() == AccessType.FIELD ? AccessCode.FIELD : AccessCode.PROPERTY);
    }
    return accessCode;
}

From source file:edu.ku.brc.af.auth.UserAndMasterPasswordMgr.java

/**
 * Returns the instance to the singleton
 * @return  the instance to the singleton
 *///from   w  w  w.  j ava2  s  .  c  om
public static UserAndMasterPasswordMgr getInstance() {
    if (instance != null) {
        return instance;
    }

    // else
    String factoryNameStr = AccessController.doPrivileged(new java.security.PrivilegedAction<String>() {
        public String run() {
            return System.getProperty(factoryName);
        }
    });

    if (isNotEmpty(factoryNameStr)) {
        try {
            return instance = (UserAndMasterPasswordMgr) Class.forName(factoryNameStr).newInstance();

        } catch (Exception e) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(UserAndMasterPasswordMgr.class, e);
            InternalError error = new InternalError(
                    "Can't instantiate UserAndMasterPasswordMgr factory " + factoryNameStr); //$NON-NLS-1$
            error.initCause(e);
            throw error;
        }
    }
    return instance = new UserAndMasterPasswordMgr();
}

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

private static void initialiseResolver(AbstractReloadingMetadataResolver resolver, RealmConfig config)
        throws ComponentInitializationException, PrivilegedActionException {
    resolver.setRequireValidMetadata(true);
    BasicParserPool pool = new BasicParserPool();
    pool.initialize();/*  www  .  ja  va 2s . c om*/
    resolver.setParserPool(pool);
    resolver.setId(config.name());
    SpecialPermission.check();
    AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
        resolver.initialize();
        return null;
    });
}

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

/**
 * Determine the source file we're parsing.
 */// w w  w.j  av a 2 s .  co  m
protected File getSourceFile() {
    if (_file != null)
        return _file;

    Class<?> cls = _cls;
    while (cls.getEnclosingClass() != null)
        cls = cls.getEnclosingClass();

    String rsrc = StringUtils.replace(cls.getName(), ".", "/");
    ClassLoader loader = AccessController.doPrivileged(J2DoPrivHelper.getClassLoaderAction(cls));
    if (loader == null)
        loader = AccessController.doPrivileged(J2DoPrivHelper.getSystemClassLoaderAction());
    if (loader == null)
        return null;
    URL url = AccessController.doPrivileged(J2DoPrivHelper.getResourceAction(loader, rsrc + ".java"));
    if (url == null) {
        url = AccessController.doPrivileged(J2DoPrivHelper.getResourceAction(loader, rsrc + ".class"));
        if (url == null)
            return null;
    }
    try {
        _file = new File(url.toURI());
    } catch (URISyntaxException e) {
    } catch (IllegalArgumentException iae) {
        // this is thrown when the URI is non-hierarchical (aka JBoss)
    }
    return _file;
}

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

/**
 * Return the field returned by the given method, or null if none.
 * Package-protected and static for testing.
 *///from  w w  w  .j  ava2  s  .  c o m
static BCField getReturnedField(BCMethod meth) {
    return findField(meth, (AccessController.doPrivileged(J2DoPrivHelper.newCodeAction())).xreturn()
            .setType(meth.getReturnType()), false);
}