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:com.baidu.cc.Constants.java

/**
 * get system property by specified key name. or return defaultValue if 
 * key not exist./*from w ww  . ja  va2  s. c o  m*/
 * 
 * @param key property key to read
 * @param defaultValue default value to return if key not exist.
 * @return property value by the key
 */
private static String getSystemProp(String key, String defaultValue) {

    String value = AccessController.doPrivileged(new SystemGetPropertyAction(key));
    if (StringUtils.isBlank(value)) {
        return defaultValue;
    }
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Read value from JDK property key: " + key);
    }
    return value;
}

From source file:tools.xor.util.ClassUtil.java

/**
 * Invoke the given method as a privileged action, if necessary.
 * @param target the object on which the method needs to be invoked
 * @param method to invoke//from ww  w.  ja  va2  s  .  c om
 * @param args to the method
 * @return result of the invocation
 * @throws InvocationTargetException while invoking the method
 * @throws IllegalAccessException when accessing the meta data
 */
//public static Object invokeMethodAsPrivileged(final Object target, final Method method, final Object[] args) 
public static Object invokeMethodAsPrivileged(final Object target, final Method method, final Object... args)
        throws InvocationTargetException, IllegalAccessException {
    if (Modifier.isPublic(method.getModifiers()))
        if (args == null)
            return method.invoke(target);
        else
            return method.invoke(target, args);
    return AccessController.doPrivileged(new PrivilegedAction<Object>() {
        public Object run() {
            method.setAccessible(true);
            Object result = null;
            try {
                if (args == null)
                    result = method.invoke(target);
                else
                    result = method.invoke(target, args);
            } catch (Exception e) {
                throw wrapRun(e);
            }
            return result;
        }
    });
}

From source file:de.fuberlin.wiwiss.r2r.FunctionFactoryLoader.java

/**
 * tries to instantiate an FunctionFactory object.
 * It tries to load the class referenced by the TransformationFunction URI from the class path first.
 * The it tries to load it from the code location.
 * @param URI The URI of the TransformationFunction
 * @return the FunctionFactory object described by the information found at the given URI or null.
 * @throws MalformedURLException/*from   w  ww . j  av  a2s  .  c  om*/
 */
public FunctionFactory getFunctionFactory(String URI) throws MalformedURLException {
    boolean loadFromURLs = Config.getProperty("r2r.FunctionManager.loadFromURLs", "false")
            .equalsIgnoreCase("true");
    FunctionFactory functionFactory = null;
    String codeLocation = null;
    String qualifiedClassName = null;
    String error = null;
    String query = "DESCRIBE <" + URI + ">";
    Model model = repository.executeDescribeQuery(query);
    if (model.isEmpty()) {
        if (log.isDebugEnabled())
            log.debug("External Function <" + URI + "> not found in repository.");
        return null;
    }
    Resource funcRes = model.getResource(URI);
    StmtIterator it = funcRes.listProperties(model.getProperty(R2R.qualifiedClassName));
    if (it.hasNext())
        qualifiedClassName = it.next().getString();
    else {
        if (log.isDebugEnabled())
            log.debug("External Function <" + URI + "> did not specify a qualified class name for loading!");
        return null;
    }
    try {
        // First try to load from class path
        functionFactory = loadFunctionFactory(qualifiedClassName, ClassLoader.getSystemClassLoader());
        // If FunctionFactory has been loaded, return it
        if (functionFactory != null)
            return functionFactory;

        if (!loadFromURLs) {
            if (log.isDebugEnabled())
                log.debug("External Function <" + URI
                        + "> could not be loaded from class path and loading by URL is disabled!");
            return null;
        }

        // Now try the original code location
        it = funcRes.listProperties(model.getProperty(R2R.codeLocation));
        if (it.hasNext())
            codeLocation = it.next().getString();
        else {
            if (log.isDebugEnabled())
                log.debug("External Function <" + URI
                        + "> could not be loaded from class path and did not specify any further code location!");
            return null;
        }

        final String cl = codeLocation;
        URLClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {
            public URLClassLoader run() {
                try {
                    return new URLClassLoader(new URL[] { new URL(cl) });
                } catch (MalformedURLException e) {
                    if (log.isDebugEnabled())
                        log.debug("Malformed URL for code location: " + cl);
                    return null;
                }
            }
        });
        functionFactory = loadFunctionFactory(qualifiedClassName, loader);
        if (functionFactory != null)
            return functionFactory;
        else {
            if (log.isDebugEnabled())
                log.debug("External Function <" + URI + "> could not be loaded: class " + qualifiedClassName
                        + " could not be loaded from " + codeLocation + ".");
            return null;
        }
    } catch (InstantiationException e) {
        error = e.toString();
    } catch (IllegalAccessException e) {
        error = e.toString();
    } catch (ClassCastException e) {
        error = e.toString();
    }
    if (error != null && log.isDebugEnabled())
        log.debug("External Function <" + URI + "> could not be loaded: " + error);
    return functionFactory;
}

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

public PageContext getPageContext(Servlet servlet, ServletRequest request, ServletResponse response,
        String errorPageURL, boolean needsSession, int bufferSize, boolean autoflush) {

    if (System.getSecurityManager() != null) {
        PrivilegedGetPageContext dp = new PrivilegedGetPageContext((JspFactoryImpl) this, servlet, request,
                response, errorPageURL, needsSession, bufferSize, autoflush);
        return (PageContext) AccessController.doPrivileged(dp);
    } else {/* w w w . ja v a2s.c  om*/
        return internalGetPageContext(servlet, request, response, errorPageURL, needsSession, bufferSize,
                autoflush);
    }
}

From source file:org.codice.solr.factory.impl.HttpClientBuilder.java

private boolean useTls() {
    return StringUtils.startsWithIgnoreCase(
            AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getProperty(SOLR_HTTP_URL)),
            "https");
}

From source file:com.alibaba.otter.shared.common.utils.NioUtilsPerformance.java

public static void mappedTest(File source, File target) throws Exception {
    FileInputStream fis = null;/*from   w w  w  .j  a  v  a  2  s  .  co m*/
    FileOutputStream fos = null;
    MappedByteBuffer mapbuffer = null;

    try {
        long fileSize = source.length();
        final byte[] outputData = new byte[(int) fileSize];
        fis = new FileInputStream(source);
        fos = new FileOutputStream(target);
        FileChannel sChannel = fis.getChannel();

        target.createNewFile();

        mapbuffer = sChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileSize);
        for (int i = 0; i < fileSize; i++) {
            outputData[i] = mapbuffer.get();
        }

        mapbuffer.clear();
        fos.write(outputData);
        fos.flush();
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(fos);

        if (mapbuffer == null) {
            return;
        }

        final Object buffer = mapbuffer;

        AccessController.doPrivileged(new PrivilegedAction() {

            public Object run() {
                try {
                    Method clean = buffer.getClass().getMethod("cleaner", new Class[0]);

                    if (clean == null) {
                        return null;
                    }
                    clean.setAccessible(true);
                    sun.misc.Cleaner cleaner = (sun.misc.Cleaner) clean.invoke(buffer, new Object[0]);
                    cleaner.clean();
                } catch (Throwable ex) {
                }

                return null;
            }
        });
    }
}

From source file:CalendarController.java

private void startConsole(String dir) throws Exception {
    final String path = dir + "/" + CONSOLE_FILENAME;
    AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
        public Object run() throws Exception {
            log("Writing log to " + path);
            console = new PrintStream(new FileOutputStream(path));
            System.setOut(console);
            System.setErr(console);
            return null;
        }//from   w  w w.  j  a  va2 s. c om
    });
}

From source file:com.enioka.jqm.tools.JndiContext.java

/**
 * Create a new Context//from w w  w. j  av a  2  s .com
 * 
 * @throws NamingException
 */
private JndiContext() throws NamingException {
    super();

    // List all jars inside ext directory
    File extDir = new File("ext/");
    List<URL> urls = new ArrayList<URL>();
    if (extDir.isDirectory()) {
        for (File f : extDir.listFiles()) {
            if (!f.canRead()) {
                throw new NamingException("can't access file " + f.getAbsolutePath());
            }
            try {
                urls.add(f.toURI().toURL());
            } catch (MalformedURLException e) {
                jqmlogger.error("Error when parsing the content of ext directory. File will be ignored", e);
            }
        }

        // Create classloader
        final URL[] aUrls = urls.toArray(new URL[0]);
        for (URL u : aUrls) {
            jqmlogger.trace(u.toString());
        }
        extResources = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {
            @Override
            public URLClassLoader run() {
                return new URLClassLoader(aUrls, null);
            }
        });
    } else {
        throw new NamingException("JQM_ROOT/ext directory does not exist or cannot be read");
    }
}

From source file:org.solmix.runtime.support.spring.ContainerXmlBeanDefinitionReader.java

@Override
public int loadBeanDefinitions(final EncodedResource encodedResource) throws BeanDefinitionStoreException {
    if (!noFastinfoset) {
        try {//from  w w  w  .j  a  v  a 2s  . c  o  m
            return fastInfosetLoadBeanDefinitions(encodedResource);
        } catch (BeanDefinitionStoreException bdse) {
            throw bdse;
        } catch (Throwable e) {
            //ignore - just call the super to load them
        }
    }
    try {
        return AccessController.doPrivileged(new PrivilegedExceptionAction<Integer>() {
            @Override
            public Integer run() throws Exception {
                return internalLoadBeanDefinitions(encodedResource);
            }

        });
    } catch (PrivilegedActionException e) {
        if (e.getException() instanceof RuntimeException) {
            throw (RuntimeException) e.getException();
        }
        throw (BeanDefinitionStoreException) e.getException();
    }
}

From source file:com.scoredev.scores.HighScore.java

/**
 * get the high score. return -1 if it hasn't been set.
 *
 */// www.ja v a2  s  .c  om
public int getHighScore() throws IOException, ClassNotFoundException {
    //check permission first
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new HighScorePermission(gameName));
    }

    Integer score = null;

    // need a doPrivileged block to manipulate the file
    try {
        score = (Integer) AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws IOException, ClassNotFoundException {
                Hashtable scores = null;
                // try to open the existing file. Should have a locking
                // protocol (could use File.createNewFile).
                FileInputStream fis = new FileInputStream(highScoreFile);
                ObjectInputStream ois = new ObjectInputStream(fis);
                scores = (Hashtable) ois.readObject();

                // get the high score out
                return scores.get(gameName);
            }
        });
    } catch (PrivilegedActionException pae) {
        Exception e = pae.getException();
        if (e instanceof IOException)
            throw (IOException) e;
        else
            throw (ClassNotFoundException) e;
    }
    if (score == null)
        return -1;
    else
        return score.intValue();
}