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:CalendarController.java

public void init() {
    log("Applet init, applet is " + this.hashCode());
    try {/*from  ww  w  . ja  v a  2 s.com*/
        AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
            public Object run() throws Exception {
                String userdir = System.getProperty("user.home");
                String dbname = userdir + "/" + DBNAME;

                startConsole(userdir);

                DatabaseManager.initDatabase(dbname, "user", "secret", false);
                log("Database initialized, " + "database directory is " + dbname);

                return null;
            }
        });
    } catch (PrivilegedActionException e) {
        e.getException().printStackTrace();
    }
}

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

/**
 * Make the given member accessible if it isn't already.
 *//*w w  w  . java  2 s. c om*/
private static void makeAccessible(AccessibleObject ao, int mods) {
    try {
        if (!Modifier.isPublic(mods) && !ao.isAccessible())
            AccessController.doPrivileged(setAccessibleAction(ao, true));
    } catch (SecurityException se) {
        throw new RuntimeException("Reflection security " + ao);
    }
}

From source file:org.codehaus.wadi.core.manager.TomcatSessionIdFactory.java

/** Use /dev/random-type special device. This is new code, but may reduce the
 *  big delay in generating the random.//from   www .j a v a2 s . c om
 *
 *  You must specify a path to a random generator file. Use /dev/urandom
 *  for linux ( or similar ) systems. Use /dev/random for maximum security
 *  ( it may block if not enough "random" exist ). You can also use
 *  a pipe that generates random.
 *
 *  The code will check if the file exists, and default to java Random
 *  if not found. There is a significant performance difference, very
 *  visible on the first call to getSession ( like in the first JSP )
 *  - so use it if available.
 */
public void setRandomFile(String s) {
    // as a hack, you can use a static file - and genarate the same
    // session ids ( good for strange traceging )
    if (System.getSecurityManager() != null) {
        randomIS = (DataInputStream) AccessController.doPrivileged(new PrivilegedSetRandomFile());
    } else {
        try {
            devRandomSource = s;
            File f = new File(devRandomSource);
            if (!f.exists())
                return;
            randomIS = new DataInputStream(new FileInputStream(f));
            randomIS.readLong();
            //   if( log.isTraceEnabled() )
            //     log.trace( "Opening " + devRandomSource );
        } catch (IOException ex) {
            randomIS = null;
        }
    }
}

From source file:org.codice.ddf.security.crl.generator.CrlGenerator.java

/**
 * Removes the org.apache.ws.security.crypto.merlin.x509crl.file property in the
 * signature.properties and encryption.properties files.
 *///from  w  w w.j av a 2  s .  co  m
@VisibleForTesting
void removeCrlFileLocationInPropertiesFile() {
    try {
        AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
            removeProperty(issuerSignaturePropertiesLocation);
            removeProperty(issuerEncryptionPropertiesLocation);
            removeProperty(serverSignaturePropertiesLocation);
            removeProperty(serverEncryptionPropertiesLocation);
            SecurityLogger.audit("Removing the {} property from signature and encryption properties.",
                    CRL_PROPERTY_KEY);
            return null;
        });
    } catch (PrivilegedActionException e) {
        LOGGER.warn(
                "Unable to remove the CRL property from the signature.properties and encryption.properties files.");
        LOGGER.debug(
                "Unable to remove the CRL property from the signature.properties and encryption.properties files. {}",
                e.getCause());
        postErrorEvent(
                "Unable to remove the CRL property from the signature.properties and encryption.properties files.");
    }
}

From source file:org.apache.cxf.common.logging.LogUtils.java

private static ClassLoader getContextClassLoader() {
    final SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
            public ClassLoader run() {
                return Thread.currentThread().getContextClassLoader();
            }//www.j a va 2s.co  m
        });
    }
    return Thread.currentThread().getContextClassLoader();
}

From source file:org.apache.ddlutils.task.DatabaseTaskBase.java

/**
 * {@inheritDoc}//from  ww w .j  a  va 2  s  .c  o  m
 */
public void execute() throws BuildException {
    initLogging();

    if (!hasCommands()) {
        _log.info("No sub tasks specified, so there is nothing to do.");
        return;
    }

    ClassLoader sysClassLoader = (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            try {
                ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
                AntClassLoader newClassLoader = new AntClassLoader(getClass().getClassLoader(), true);

                // we're changing the thread classloader so that we can access resources
                // from the classpath used to load this task's class
                Thread.currentThread().setContextClassLoader(newClassLoader);
                return contextClassLoader;
            } catch (SecurityException ex) {
                throw new BuildException("Could not change the context clas loader", ex);
            }
        }
    });

    try {
        executeCommands(readModel());
    } finally {
        if ((getDataSource() != null) && isShutdownDatabase()) {
            getPlatform().shutdownDatabase();
        }
        // rollback of our classloader change
        Thread.currentThread().setContextClassLoader(sysClassLoader);
    }
}

From source file:org.apache.openjpa.lib.conf.ProductDerivations.java

/**
 * Load a built-in resource location.//from   w ww . j  a v  a2s .co m
 */
private static ConfigurationProvider load(ClassLoader loader, boolean globals) {
    if (loader == null)
        loader = AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction());

    ConfigurationProvider provider = null;
    StringBuilder errs = null;
    String type = (globals) ? "globals" : "defaults";
    Throwable err = null;
    // most specific to least
    for (int i = _derivations.length - 1; i >= 0; i--) {
        try {
            provider = (globals) ? _derivations[i].loadGlobals(loader) : _derivations[i].loadDefaults(loader);
            if (provider != null)
                return provider;
        } catch (Throwable t) {
            err = t;
            errs = (errs == null) ? new StringBuilder() : errs.append("\n");
            errs.append(_derivations[i].getClass().getName() + ":" + t);
        }
    }
    reportErrors(errs, type, err);
    return null;
}

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

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

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

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

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

From source file:org.codehaus.groovy.grails.web.pages.ext.jsp.GroovyPagesPageContext.java

@Override
public ExpressionEvaluator getExpressionEvaluator() {
    try {/*from   w w  w.j  a  v a2  s. com*/
        Class<?> type = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
            public ClassLoader 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:SocketFetcher.java

/**
 * Convenience method to get our context class loader. Assert any privileges
 * we might have and then call the Thread.getContextClassLoader method.
 *///from w  w  w  .  j a  v  a 2  s .c  om
private static ClassLoader getContextClassLoader() {
    return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            ClassLoader cl = null;
            try {
                cl = Thread.currentThread().getContextClassLoader();
            } catch (SecurityException ex) {
            }
            return cl;
        }
    });
}