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.struts2.jasper.runtime.PageContextImpl.java

public void include(final String relativeUrlPath, final boolean flush) throws ServletException, IOException {
    if (SecurityUtil.isPackageProtectionEnabled()) {
        try {/*w ww.  j  ava 2s .co  m*/
            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.hadoop.mapred.pipes.Submitter.java

@Override
public int run(String[] args) throws Exception {
    CommandLineParser cli = new CommandLineParser();
    if (args.length == 0) {
        cli.printUsage();//from   w  w  w . ja va2s.c o 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");
    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, (String) results.getOptionValue("input"));
        }
        if (results.hasOption("output")) {
            FileOutputFormat.setOutputPath(job, new Path((String) results.getOptionValue("output")));
        }
        if (results.hasOption("jar")) {
            job.setJar((String) 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((String) results.getOptionValue("reduces")));
        }
        if (results.hasOption("writer")) {
            setIsJavaRecordWriter(job, true);
            job.setOutputFormat(getClass(results, "writer", job, OutputFormat.class));
        }
        if (results.hasOption("program")) {
            setExecutable(job, (String) results.getOptionValue("program"));
        }
        if (results.hasOption("jobconf")) {
            LOG.warn("-jobconf option is deprecated, please use -D instead.");
            String options = (String) results.getOptionValue("jobconf");
            StringTokenizer tokenizer = new StringTokenizer(options, ",");
            while (tokenizer.hasMoreTokens()) {
                String keyVal = tokenizer.nextToken().trim();
                String[] keyValSplit = keyVal.split("=", 2);
                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.openjpa.persistence.PersistenceMetaDataDefaults.java

/**
 * Gets the methods that are possible candidate for being persisted. The  
 * result depends on the current access style of the given class. 
 *//* ww w .  j  ava  2 s.co m*/
List<Method> getPersistentMethods(ClassMetaData meta, boolean ignoreTransient) {
    boolean explicit = meta.isExplicitAccess();
    boolean unknown = AccessCode.isUnknown(meta.getAccessType());
    boolean isProperty = AccessCode.isProperty(meta.getAccessType());

    if (explicit || unknown || isProperty) {
        Method[] publicMethods = AccessController
                .doPrivileged(J2DoPrivHelper.getDeclaredMethodsAction(meta.getDescribedType()));

        /*
         * OpenJPA 1.x permitted private accessor properties to be persistent.  This is
         * contrary to the JPA 1.0 specification, which states that persistent
         * properties must be public or protected. OpenJPA 2.0+ will adhere
         * to the specification by default, but provides a compatibility
         * option to provide pre-2.0 behavior.
         */
        getterFilter.setIncludePrivate(meta.getRepository().getConfiguration().getCompatibilityInstance()
                .getPrivatePersistentProperties());

        List<Method> getters = filter(publicMethods, methodFilter, getterFilter,
                ignoreTransient ? null : nonTransientFilter, unknown || isProperty ? null : annotatedFilter,
                explicit ? (isProperty ? null : propertyAccessFilter) : null);

        List<Method> setters = filter(publicMethods, setterFilter);
        return getters = matchGetterAndSetter(getters, setters);
    }

    return Collections.EMPTY_LIST;
}

From source file:org.apache.hama.pipes.Submitter.java

@Override
public int run(String[] args) throws Exception {
    CommandLineParser cli = new CommandLineParser();
    if (args.length == 0) {
        cli.printUsage();//from  w w  w.  j  a va  2 s .c om
        return 1;
    }

    LOG.debug("Hama pipes Submitter started!");

    cli.addOption("input", false, "input path for bsp", "path");
    cli.addOption("output", false, "output path from bsp", "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("partitioner", false, "java classname of Partitioner", "class");
    cli.addOption("outputformat", false, "java classname of OutputFormat", "class");

    cli.addOption("cachefiles", false, "additional cache files to add", "space delimited paths");

    cli.addOption("interpreter", false, "interpreter, like python or bash", "executable");

    cli.addOption("jobname", false, "the jobname", "name");

    cli.addOption("programArgs", false, "program arguments", "arguments");
    cli.addOption("bspTasks", false, "how many bsp tasks to launch", "number");
    cli.addOption("streaming", false, "if supplied, streaming is used instead of pipes", "");

    cli.addOption("jobconf", false,
            "\"n1=v1,n2=v2,..\" (Deprecated) Optional. Add or override a JobConf property.", "key=val");

    cli.addOption("program", false, "URI to application executable", "class");
    Parser parser = cli.createParser();
    try {

        // check generic arguments -conf
        GenericOptionsParser genericParser = new GenericOptionsParser(getConf(), args);
        // get other arguments
        CommandLine results = parser.parse(cli.options, genericParser.getRemainingArgs());

        BSPJob job = new BSPJob(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("jobname")) {
            job.setJobName(results.getOptionValue("jobname"));
        }

        if (results.hasOption("inputformat")) {
            job.setInputFormat(getClass(results, "inputformat", conf, InputFormat.class));
        }

        if (results.hasOption("partitioner")) {
            job.setPartitioner(getClass(results, "partitioner", conf, Partitioner.class));
        }

        if (results.hasOption("outputformat")) {
            job.setOutputFormat(getClass(results, "outputformat", conf, OutputFormat.class));
        }

        if (results.hasOption("streaming")) {
            LOG.info("Streaming enabled!");
            job.set("hama.streaming.enabled", "true");
        }

        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("=", 2);
                job.set(keyValSplit[0], keyValSplit[1]);
            }
        }

        if (results.hasOption("bspTasks")) {
            int optionValue = Integer.parseInt(results.getOptionValue("bspTasks"));
            conf.setInt("bsp.local.tasks.maximum", optionValue);
            conf.setInt("bsp.peers.num", optionValue);
        }

        if (results.hasOption("program")) {
            String executablePath = results.getOptionValue("program");
            setExecutable(job.getConfiguration(), executablePath);
            DistributedCache.addCacheFile(new Path(executablePath).toUri(), conf);
        }

        if (results.hasOption("interpreter")) {
            job.getConfiguration().set("hama.pipes.executable.interpretor",
                    results.getOptionValue("interpreter"));
        }

        if (results.hasOption("programArgs")) {
            job.getConfiguration().set("hama.pipes.executable.args",
                    Joiner.on(" ").join(results.getOptionValues("programArgs")));
            // job.getConfiguration().set("hama.pipes.resolve.executable.args",
            // "true");
        }

        if (results.hasOption("cachefiles")) {
            FileSystem fs = FileSystem.get(getConf());
            String[] optionValues = results.getOptionValues("cachefiles");
            for (String s : optionValues) {
                Path path = new Path(s);
                FileStatus[] globStatus = fs.globStatus(path);
                for (FileStatus f : globStatus) {
                    if (!f.isDir()) {
                        DistributedCache.addCacheFile(f.getPath().toUri(), job.getConfiguration());
                    } else {
                        LOG.info("Ignoring directory " + f.getPath() + " while globbing.");
                    }
                }
            }
        }

        // if they gave us a jar file, include it into the class path
        String jarFile = job.getJar();
        if (jarFile != null) {
            @SuppressWarnings("deprecation")
            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>() {
                @Override
                public ClassLoader run() {
                    return new URLClassLoader(urls);
                }
            });
            conf.setClassLoader(loader);
        }

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

}

From source file:at.irian.myfaces.wscope.renderkit.html.WsServerSideStateCacheImpl.java

protected Object deserializeView(Object state) {
    if (log.isLoggable(Level.FINEST)) {
        log.finest("Entering deserializeView");
    }//ww w. j a  v  a 2  s. c o m

    if (state instanceof byte[]) {
        if (log.isLoggable(Level.FINEST)) {
            log.finest("Processing deserializeView - deserializing serialized state. Bytes : "
                    + ((byte[]) state).length);
        }

        try {
            ByteArrayInputStream bais = new ByteArrayInputStream((byte[]) state);
            InputStream is = bais;
            if (is.read() == COMPRESSED_FLAG) {
                is = new GZIPInputStream(is);
            }
            ObjectInputStream ois = null;
            try {
                final ObjectInputStream in = new MyFacesObjectInputStream(is);
                ois = in;
                Object object = null;
                if (System.getSecurityManager() != null) {
                    object = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                        public Object run()
                                throws PrivilegedActionException, IOException, ClassNotFoundException {
                            //return new Object[] {in.readObject(), in.readObject()};
                            return in.readObject();
                        }
                    });
                } else {
                    //object = new Object[] {in.readObject(), in.readObject()};
                    object = in.readObject();
                }
                return object;
            } finally {
                if (ois != null) {
                    ois.close();
                    ois = null;
                }
            }
        } catch (PrivilegedActionException e) {
            log.log(Level.SEVERE, "Exiting deserializeView - Could not deserialize state: " + e.getMessage(),
                    e);
            return null;
        } catch (IOException e) {
            log.log(Level.SEVERE, "Exiting deserializeView - Could not deserialize state: " + e.getMessage(),
                    e);
            return null;
        } catch (ClassNotFoundException e) {
            log.log(Level.SEVERE, "Exiting deserializeView - Could not deserialize state: " + e.getMessage(),
                    e);
            return null;
        }
    } else if (state instanceof Object[]) {
        if (log.isLoggable(Level.FINEST)) {
            log.finest("Exiting deserializeView - state not serialized.");
        }

        return state;
    } else if (state == null) {
        log.severe("Exiting deserializeView - this method should not be called with a null-state.");
        return null;
    } else {
        log.severe("Exiting deserializeView - this method should not be called with a state of type : "
                + state.getClass());
        return null;
    }
}

From source file:Tcpbw100.java

public void run_test() {
    // The Java security model considers calling a method that opens a socket
    // from JavaScript to be a privileged action.  By using 
    // java.security.privilegedAction here, we can grant JavaScript the 
    // same expanded privileges as the signed applet to open a socket.
    AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            pub_errmsg = "Test in progress.";
            runtest();/*  w  w  w  .  j  a v  a  2s . c om*/
            return null;
        }
    });
}

From source file:org.apache.catalina.cluster.session.DeltaSession.java

/**
 * Return the <code>HttpSession</code> for which this object
 * is the facade./*  w  w w.j av a 2  s  .  c  om*/
 */
public HttpSession getSession() {

    if (facade == null) {
        if (System.getSecurityManager() != null) {
            final DeltaSession fsession = this;
            facade = (DeltaSessionFacade) AccessController.doPrivileged(new PrivilegedAction() {
                public Object run() {
                    return new DeltaSessionFacade(fsession);
                }
            });
        } else {
            facade = new DeltaSessionFacade(this);
        }
    }
    return (facade);

}

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

private static XMLInputFactory newXMLInputFactory(final ClassLoader classLoader,
        final StAXParserConfiguration configuration) {

    return (XMLInputFactory) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            ClassLoader savedClassLoader;
            if (classLoader == null) {
                savedClassLoader = null;
            } else {
                savedClassLoader = Thread.currentThread().getContextClassLoader();
                Thread.currentThread().setContextClassLoader(classLoader);
            }//ww w  .j a  v  a  2s .c  om
            try {
                XMLInputFactory factory = XMLInputFactory.newInstance();
                // Woodstox by default creates coalescing parsers. Even if this violates
                // the StAX specs, for compatibility with Woodstox, we always enable the
                // coalescing mode. Note that we need to do that before loading
                // XMLInputFactory.properties so that this setting can be overridden.
                factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
                Map props = loadFactoryProperties("XMLInputFactory.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 ImmutableXMLInputFactory(dialect.normalize(dialect.makeThreadSafe(factory)));
            } finally {
                if (savedClassLoader != null) {
                    Thread.currentThread().setContextClassLoader(savedClassLoader);
                }
            }
        }
    });
}

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

public void forward(final String relativeUrlPath) throws ServletException, IOException {
    if (SecurityUtil.isPackageProtectionEnabled()) {
        try {/*from  w w w .  ja  v  a 2s . c o 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:org.apache.openjpa.meta.AbstractCFMetaDataFactory.java

/**
 * Backup and delete the source files for the given metadatas.
 *//*  w  w  w.java2 s.  c  o  m*/
protected void backupAndDelete(Collection files) {
    File file;
    for (Iterator itr = files.iterator(); itr.hasNext();) {
        file = (File) itr.next();
        if (Files.backup(file, false) != null)
            AccessController.doPrivileged(J2DoPrivHelper.deleteAction(file));
    }
}