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.bsf.BSFManager.java

/**
 * Execute the given script of the given language, attempting to
 * emulate an interactive session w/ the language.
 *
 * @param lang     language identifier//from   ww  w.j av a  2 s.c o  m
 * @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 script   the script to execute
 *
 * @exception BSFException if anything goes wrong while running the script
 */
public void iexec(String lang, String source, int lineNo, int columnNo, Object script) throws BSFException {
    logger.debug("BSFManager:iexec");

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

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

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

From source file:it.crs4.pydoop.pipes.Submitter.java

@Override
public int run(String[] args) throws Exception {
    CommandLineParser cli = new CommandLineParser();
    if (args.length == 0) {
        cli.printUsage();/* w w w . j  av  a 2s.  co m*/
        return 1;
    }
    cli.addOption("input", false, "input path to the maps", "path");
    cli.addOption("output", false, "output path from the reduces", "path");

    cli.addOption("jar", false, "job jar file", "path");
    cli.addOption("inputformat", false, "java classname of InputFormat", "class");
    //cli.addArgument("javareader", false, "is the RecordReader in Java");
    cli.addOption("map", false, "java classname of Mapper", "class");
    cli.addOption("partitioner", false, "java classname of Partitioner", "class");
    cli.addOption("reduce", false, "java classname of Reducer", "class");
    cli.addOption("writer", false, "java classname of OutputFormat", "class");
    cli.addOption("program", false, "URI to application executable", "class");
    cli.addOption("reduces", false, "number of reduces", "num");
    cli.addOption("jobconf", false,
            "\"n1=v1,n2=v2,..\" (Deprecated) Optional. Add or override a JobConf property.", "key=val");
    cli.addOption("lazyOutput", false, "Optional. Create output lazily", "boolean");
    Parser parser = cli.createParser();
    try {

        GenericOptionsParser genericParser = new GenericOptionsParser(getConf(), args);
        CommandLine results = parser.parse(cli.options, genericParser.getRemainingArgs());

        JobConf job = new JobConf(getConf());

        if (results.hasOption("input")) {
            FileInputFormat.setInputPaths(job, results.getOptionValue("input"));
        }
        if (results.hasOption("output")) {
            FileOutputFormat.setOutputPath(job, new Path(results.getOptionValue("output")));
        }
        if (results.hasOption("jar")) {
            job.setJar(results.getOptionValue("jar"));
        }
        if (results.hasOption("inputformat")) {
            setIsJavaRecordReader(job, true);
            job.setInputFormat(getClass(results, "inputformat", job, InputFormat.class));
        }
        if (results.hasOption("javareader")) {
            setIsJavaRecordReader(job, true);
        }
        if (results.hasOption("map")) {
            setIsJavaMapper(job, true);
            job.setMapperClass(getClass(results, "map", job, Mapper.class));
        }
        if (results.hasOption("partitioner")) {
            job.setPartitionerClass(getClass(results, "partitioner", job, Partitioner.class));
        }
        if (results.hasOption("reduce")) {
            setIsJavaReducer(job, true);
            job.setReducerClass(getClass(results, "reduce", job, Reducer.class));
        }
        if (results.hasOption("reduces")) {
            job.setNumReduceTasks(Integer.parseInt(results.getOptionValue("reduces")));
        }
        if (results.hasOption("writer")) {
            setIsJavaRecordWriter(job, true);
            job.setOutputFormat(getClass(results, "writer", job, OutputFormat.class));
        }

        if (results.hasOption("lazyOutput")) {
            if (Boolean.parseBoolean(results.getOptionValue("lazyOutput"))) {
                LazyOutputFormat.setOutputFormatClass(job, job.getOutputFormat().getClass());
            }
        }

        if (results.hasOption("program")) {
            setExecutable(job, results.getOptionValue("program"));
        }
        if (results.hasOption("jobconf")) {
            LOG.warn("-jobconf option is deprecated, please use -D instead.");
            String options = results.getOptionValue("jobconf");
            StringTokenizer tokenizer = new StringTokenizer(options, ",");
            while (tokenizer.hasMoreTokens()) {
                String keyVal = tokenizer.nextToken().trim();
                String[] keyValSplit = keyVal.split("=");
                job.set(keyValSplit[0], keyValSplit[1]);
            }
        }
        // if they gave us a jar file, include it into the class path
        String jarFile = job.getJar();
        if (jarFile != null) {
            final URL[] urls = new URL[] { FileSystem.getLocal(job).pathToFile(new Path(jarFile)).toURL() };
            //FindBugs complains that creating a URLClassLoader should be
            //in a doPrivileged() block. 
            ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
                public ClassLoader run() {
                    return new URLClassLoader(urls);
                }
            });
            job.setClassLoader(loader);
        }

        runJob(job);
        return 0;
    } catch (ParseException pe) {
        LOG.info("Error : " + pe);
        cli.printUsage();
        return 1;
    }

}

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

public void include(final String relativeUrlPath, final boolean flush) throws ServletException, IOException {
    if (System.getSecurityManager() != null) {
        try {/*from   w  ww.j  a v a 2 s  .c  om*/
            AccessController.doPrivileged(new PrivilegedExceptionAction() {
                public Object run() throws Exception {
                    doInclude(relativeUrlPath, flush);
                    return null;
                }
            });
        } catch (PrivilegedActionException e) {
            Exception ex = e.getException();
            if (ex instanceof IOException) {
                throw (IOException) ex;
            } else {
                throw (ServletException) ex;
            }
        }
    } else {
        doInclude(relativeUrlPath, flush);
    }
}

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

/**
 * Load all sessions found in the persistence mechanism, assuming
 * they are marked as valid and have not passed their expiration
 * limit. If persistence is not supported, this method returns
 * without doing anything./*from  w ww  .  j  a  v a2s. c o  m*/
 * <p>
 * Note that by default, this method is not called by the MiddleManager
 * class. In order to use it, a subclass must specifically call it,
 * for example in the start() and/or processPersistenceChecks() methods.
 */
public void load() {

    // Initialize our internal data structures
    sessions.clear();

    if (store == null)
        return;

    String[] ids = null;
    try {
        if (System.getSecurityManager() != null) {
            try {
                ids = (String[]) AccessController.doPrivileged(new PrivilegedStoreKeys());
            } catch (PrivilegedActionException ex) {
                Exception exception = ex.getException();
                log.error("Exception clearing the Store: " + exception);
                exception.printStackTrace();
            }
        } else {
            ids = store.keys();
        }
    } catch (IOException e) {
        log.error("Can't load sessions from store, " + e.getMessage(), e);
        return;
    }

    int n = ids.length;
    if (n == 0)
        return;

    if (log.isDebugEnabled())
        log.debug(sm.getString("persistentManager.loading", String.valueOf(n)));

    for (int i = 0; i < n; i++)
        try {
            swapIn(ids[i]);
        } catch (IOException e) {
            log.error("Failed load session from store, " + e.getMessage(), e);
        }

}

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

/**
 * Instantiate the given proxy class./* www .  ja  va 2 s.  c  om*/
 */
private Proxy instantiateProxy(Class cls, Constructor cons, Object[] args) {
    try {
        if (cons != null)
            return (Proxy) cls.getConstructor(cons.getParameterTypes()).newInstance(args);
        return (Proxy) AccessController.doPrivileged(J2DoPrivHelper.newInstanceAction(cls));
    } catch (InstantiationException ie) {
        throw new UnsupportedException(_loc.get("cant-newinstance", cls.getSuperclass().getName()));
    } catch (PrivilegedActionException pae) {
        Exception e = pae.getException();
        if (e instanceof InstantiationException)
            throw new UnsupportedException(_loc.get("cant-newinstance", cls.getSuperclass().getName()));
        else
            throw new GeneralException(cls.getName()).setCause(e);
    } catch (Throwable t) {
        throw new GeneralException(cls.getName()).setCause(t);
    }
}

From source file:corina.util.SimpleLog.java

private static InputStream getResourceAsStream(final String name) {
    return (InputStream) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            ClassLoader threadCL = getContextClassLoader();

            if (threadCL != null) {
                return threadCL.getResourceAsStream(name);
            } else {
                return ClassLoader.getSystemResourceAsStream(name);
            }//from  w  w  w.  ja  v  a2 s . c  om
        }
    });
}

From source file:it.crs4.pydoop.mapreduce.pipes.CommandLineParser.java

public int run(String[] args) throws Exception {
    CommandLineParser cli = new CommandLineParser();
    if (args.length == 0) {
        cli.printUsage();//from   w w  w  .j a  va 2s.  c  o m
        return 1;
    }
    try {
        Job job = new Job(new Configuration());
        job.setJobName(getClass().getName());
        Configuration conf = job.getConfiguration();
        CommandLine results = cli.parse(conf, args);
        if (results.hasOption("input")) {
            Path path = new Path(results.getOptionValue("input"));
            FileInputFormat.setInputPaths(job, path);
        }
        if (results.hasOption("output")) {
            Path path = new Path(results.getOptionValue("output"));
            FileOutputFormat.setOutputPath(job, path);
        }
        if (results.hasOption("jar")) {
            job.setJar(results.getOptionValue("jar"));
        }
        if (results.hasOption("inputformat")) {
            explicitInputFormat = true;
            setIsJavaRecordReader(conf, true);
            job.setInputFormatClass(getClass(results, "inputformat", conf, InputFormat.class));
        }
        if (results.hasOption("javareader")) {
            setIsJavaRecordReader(conf, true);
        }
        if (results.hasOption("map")) {
            setIsJavaMapper(conf, true);
            job.setMapperClass(getClass(results, "map", conf, Mapper.class));
        }
        if (results.hasOption("partitioner")) {
            job.setPartitionerClass(getClass(results, "partitioner", conf, Partitioner.class));
        }
        if (results.hasOption("reduce")) {
            setIsJavaReducer(conf, true);
            job.setReducerClass(getClass(results, "reduce", conf, Reducer.class));
        }
        if (results.hasOption("reduces")) {
            job.setNumReduceTasks(Integer.parseInt(results.getOptionValue("reduces")));
        }
        if (results.hasOption("writer")) {
            explicitOutputFormat = true;
            setIsJavaRecordWriter(conf, true);
            job.setOutputFormatClass(getClass(results, "writer", conf, OutputFormat.class));
        }
        if (results.hasOption("lazyOutput")) {
            if (Boolean.parseBoolean(results.getOptionValue("lazyOutput"))) {
                LazyOutputFormat.setOutputFormatClass(job, job.getOutputFormatClass());
            }
        }
        if (results.hasOption("avroInput")) {
            avroInput = AvroIO.valueOf(results.getOptionValue("avroInput").toUpperCase());
        }
        if (results.hasOption("avroOutput")) {
            avroOutput = AvroIO.valueOf(results.getOptionValue("avroOutput").toUpperCase());
        }

        if (results.hasOption("program")) {
            setExecutable(conf, results.getOptionValue("program"));
        }
        // if they gave us a jar file, include it into the class path
        String jarFile = job.getJar();
        if (jarFile != null) {
            final URL[] urls = new URL[] { FileSystem.getLocal(conf).pathToFile(new Path(jarFile)).toURL() };
            // FindBugs complains that creating a URLClassLoader should be
            // in a doPrivileged() block.
            ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
                public ClassLoader run() {
                    return new URLClassLoader(urls);
                }
            });
            conf.setClassLoader(loader);
        }
        setupPipesJob(job);
        return job.waitForCompletion(true) ? 0 : 1;
    } catch (ParseException pe) {
        LOG.info("Error : " + pe);
        cli.printUsage();
        return 1;
    }
}

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

public void forward(final String relativeUrlPath) throws ServletException, IOException {
    if (System.getSecurityManager() != null) {
        try {/*from  w  w w. ja va 2  s.co  m*/
            AccessController.doPrivileged(new PrivilegedExceptionAction() {
                public Object run() throws Exception {
                    doForward(relativeUrlPath);
                    return null;
                }
            });
        } catch (PrivilegedActionException e) {
            Exception ex = e.getException();
            if (ex instanceof IOException) {
                throw (IOException) ex;
            } else {
                throw (ServletException) ex;
            }
        }
    } else {
        doForward(relativeUrlPath);
    }
}

From source file:com.mercer.cpsg.swarm.oidc.deployment.OIDCAuthenticationMechanism.java

protected Session getSession(HttpServerExchange exchange) {
    final ServletRequestContext servletRequestContext = exchange
            .getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    HttpSessionImpl httpSession = servletRequestContext.getCurrentServletContext().getSession(exchange, true);
    Session session;//from   www . j a v  a2 s.  c om
    if (System.getSecurityManager() == null) {
        session = httpSession.getSession();
    } else {
        session = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(httpSession));
    }
    return session;
}

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

/**
 * Generate the bytecode for a collection proxy for the given type.
 *//*from w ww. jav a 2 s . co  m*/
protected BCClass generateProxyCollectionBytecode(Class type, boolean runtime) {
    assertNotFinal(type);
    Project project = new Project();
    BCClass bc = AccessController
            .doPrivileged(J2DoPrivHelper.loadProjectClassAction(project, getProxyClassName(type, runtime)));
    bc.setSuperclass(type);
    bc.declareInterface(ProxyCollection.class);

    delegateConstructors(bc, type);
    addProxyMethods(bc, false);
    addProxyCollectionMethods(bc, type);
    proxyRecognizedMethods(bc, type, ProxyCollections.class, ProxyCollection.class);
    proxySetters(bc, type);
    addWriteReplaceMethod(bc, runtime);
    return bc;
}