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.beangle.model.persist.hibernate.internal.ClassUtils.java

public static ClassLoader getFwkClassLoader() {
    if (System.getSecurityManager() != null) {
        return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
            public ClassLoader run() {
                return Bundle.class.getClassLoader();
            }/*from  ww  w.  j a v  a 2 s . com*/
        });
    } else {
        return Bundle.class.getClassLoader();
    }
}

From source file:edu.ku.brc.af.ui.forms.formatters.UIFieldFormatterMgr.java

/**
 * Returns the instance to the singleton
 * //from w  w w  .ja  va2 s .  c  o  m
 * @return the instance to the singleton
 */
public static UIFieldFormatterMgr getInstance() {
    if (instance != null) {
        return instance;
    }

    if (StringUtils.isEmpty(factoryName)) {
        return instance = new UIFieldFormatterMgr();
    }

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

    if (StringUtils.isNotEmpty(factoryNameStr)) {
        try {
            instance = (UIFieldFormatterMgr) Class.forName(factoryNameStr).newInstance();
            instance.load();
            return instance;

        } catch (Exception e) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(UIFieldFormatterMgr.class, e);
            InternalError error = new InternalError(
                    "Can't instantiate UIFieldFormatterMgr factory " + factoryNameStr);
            error.initCause(e);
            throw error;
        }
    }
    // should not happen
    throw new RuntimeException("Can't instantiate UIFieldFormatterMgr factory [" + factoryNameStr + "]");
}

From source file:org.eclipse.gemini.blueprint.test.AbstractDependencyManagerTests.java

private String readProperty(final String name) {
    if (System.getSecurityManager() != null) {
        return (String) AccessController.doPrivileged(new PrivilegedAction() {

            public Object run() {
                return System.getProperty(name);
            }// w  w  w.ja va  2 s  . co m
        });
    } else
        return System.getProperty(name);
}

From source file:io.siddhi.doc.gen.core.utils.DocumentationUtils.java

/**
 * Returns the extension extension meta data
 * Gets the meta data from the siddhi manager
 *
 * @param targetDirectoryPath The path of the target directory of the maven module containing extensions
 * @param logger              The maven plugin logger
 * @return NamespaceMetaData namespace meta data list
 * @throws MojoFailureException   If this fails to access project dependencies
 * @throws MojoExecutionException If the classes directory from which classes are loaded is invalid
 *//*w  w w  .ja va2  s . c  o m*/
public static List<NamespaceMetaData> getExtensionMetaData(String targetDirectoryPath,
        List<String> runtimeClasspathElements, Log logger) throws MojoFailureException, MojoExecutionException {
    List<NamespaceMetaData> namespaceMetaDataList = new ArrayList<NamespaceMetaData>();
    int urlCount = runtimeClasspathElements.size() + 1; // +1 to include the module's target/classes folder

    // Creating a list of URLs with all project dependencies
    URL[] urls = new URL[urlCount];
    for (int i = 0; i < runtimeClasspathElements.size(); i++) {
        try {
            urls[i] = new File(runtimeClasspathElements.get(i)).toURI().toURL();
        } catch (MalformedURLException e) {
            throw new MojoFailureException(
                    "Unable to access project dependency: " + runtimeClasspathElements.get(i), e);
        }
    }

    File classesDirectory = new File(targetDirectoryPath + File.separator + Constants.CLASSES_DIRECTORY);
    try {
        // Adding the generated classes to the class loader
        urls[urlCount - 1] = classesDirectory.toURI().toURL();
        ClassLoader urlClassLoader = AccessController
                .doPrivileged((PrivilegedAction<ClassLoader>) () -> new URLClassLoader(urls,
                        Thread.currentThread().getContextClassLoader()));
        // Getting extensions from all the class files in the classes directory
        addExtensionInDirectory(classesDirectory, classesDirectory.getAbsolutePath(), urlClassLoader,
                namespaceMetaDataList, logger);
    } catch (MalformedURLException e) {
        throw new MojoExecutionException("Invalid classes directory: " + classesDirectory.getAbsolutePath(), e);
    }
    for (NamespaceMetaData aNamespaceMetaData : namespaceMetaDataList) {
        for (List<ExtensionMetaData> extensionMetaData : aNamespaceMetaData.getExtensionMap().values()) {
            Collections.sort(extensionMetaData);
        }
    }
    Collections.sort(namespaceMetaDataList);
    return namespaceMetaDataList;
}

From source file:com.reelfx.model.ScreenRecorder.java

public void run() {
    try {/*from   w  ww . j av  a2 s. c om*/
        if (Applet.IS_MAC) {
            List<String> macArgs = new ArrayList<String>();
            macArgs.add(MAC_EXEC.getAbsolutePath());
            macArgs.add(OUTPUT_FILE.getAbsolutePath());

            ProcessBuilder pb = new ProcessBuilder(macArgs);
            recordingProcess = pb.start();
            fireProcessUpdate(RECORDING_STARTED);

            errorGobbler = new StreamGobbler(recordingProcess.getErrorStream(), false, "mac E");
            inputGobbler = new StreamGobbler(recordingProcess.getInputStream(), false, "mac O");

            logger.info("Starting listener threads...");
            errorGobbler.start();
            inputGobbler.start();

            recordingProcess.waitFor();
            fireProcessUpdate(RECORDING_COMPLETE);
        }

        else if (Applet.IS_LINUX) {
            // can have problem with file permissions when methods are invoked via Javascript even if applet is signed, 
            // thus some code needs to wrapped in a privledged block
            AccessController.doPrivileged(new PrivilegedAction<Object>() {

                @Override
                public Object run() {

                    try {
                        int width = Applet.CAPTURE_VIEWPORT.width;
                        if (width % 2 != 0)
                            width--;
                        int height = Applet.CAPTURE_VIEWPORT.height;
                        if (height % 2 != 0)
                            height--;

                        List<String> ffmpegArgs = new ArrayList<String>();
                        //ffmpegArgs.add("/usr/bin/ffmpeg");
                        ffmpegArgs.add(Applet.BIN_FOLDER.getAbsoluteFile() + File.separator + "ffmpeg");
                        // screen capture settings
                        ffmpegArgs.addAll(
                                parseParameters("-y -f x11grab -s " + width + "x" + height + " -r 20 -i :0.0+"
                                        + Applet.CAPTURE_VIEWPORT.x + "," + Applet.CAPTURE_VIEWPORT.y));
                        // microphone settings (good resource: http://www.oreilly.de/catalog/multilinux/excerpt/ch14-05.htm)
                        /* 04/29/2010 - ffmpeg gets much better framerate when not recording microphone (let Java do this)
                         * if(audioSource != null) { 
                           String driver = audioIndex > 0 ? "/dev/dsp"+audioIndex : "/dev/dsp";
                           ffmpegArgs.addAll(parseParameters("-f oss -ac 1 -ar "+AudioRecorder.FREQ+" -i "+driver));
                        }*/
                        // output file settings
                        ffmpegArgs.addAll(parseParameters("-vcodec mpeg4 -r 20 -b 5000k")); // -s "+Math.round(width*SCALE)+"x"+Math.round(height*SCALE))
                        ffmpegArgs.add(OUTPUT_FILE.getAbsolutePath());

                        logger.info("Executing this command: " + prettyCommand(ffmpegArgs));

                        ProcessBuilder pb = new ProcessBuilder(ffmpegArgs);
                        recordingProcess = pb.start();
                        // fireProcessUpdate(RECORDING_STARTED); // moved to action listener method

                        errorGobbler = new StreamGobbler(recordingProcess.getErrorStream(), false, "ffmpeg E");
                        inputGobbler = new StreamGobbler(recordingProcess.getInputStream(), false, "ffmpeg O");

                        logger.info("Starting listener threads...");
                        errorGobbler.start();
                        errorGobbler.addActionListener("Stream mapping:", self);
                        inputGobbler.start();

                        recordingProcess.waitFor();

                        fireProcessUpdate(RECORDING_COMPLETE);

                    } catch (Exception e) {
                        logger.error("Error running Linux screen recorder!", e);
                    }
                    return null;
                }
            });
        }

        else if (Applet.IS_WINDOWS) {
            // can have problem with file permissions when methods are invoked via Javascript even if applet is signed, 
            // thus some code needs to wrapped in a privileged block
            AccessController.doPrivileged(new PrivilegedAction<Object>() {

                @Override
                public Object run() {

                    try {
                        List<String> ffmpegArgs = new ArrayList<String>();
                        ffmpegArgs.add(FFMPEG_EXEC.getAbsolutePath());
                        // for full screen, use simply "cursor:desktop"
                        int width = Applet.CAPTURE_VIEWPORT.width % 2 == 0 ? Applet.CAPTURE_VIEWPORT.width
                                : Applet.CAPTURE_VIEWPORT.width - 1;
                        int height = Applet.CAPTURE_VIEWPORT.height % 2 == 0 ? Applet.CAPTURE_VIEWPORT.height
                                : Applet.CAPTURE_VIEWPORT.height - 1;
                        String viewport = ":offset=" + Applet.CAPTURE_VIEWPORT.x + ","
                                + Applet.CAPTURE_VIEWPORT.y;
                        viewport += ":size=" + width + "," + height;
                        ffmpegArgs.addAll(parseParameters("-y -f gdigrab -r 20 -i cursor:desktop" + viewport
                                + " -vcodec mpeg4 -b 5000k " + OUTPUT_FILE));

                        logger.info("Executing this command: " + prettyCommand(ffmpegArgs));
                        ProcessBuilder pb = new ProcessBuilder(ffmpegArgs);
                        recordingProcess = pb.start();
                        //fireProcessUpdate(RECORDING_STARTED); // moved to action listener method

                        // ffmpeg doesn't get the microphone on Windows, but this allows it to record a better frame rate anyway

                        errorGobbler = new StreamGobbler(recordingProcess.getErrorStream(), false, "ffmpeg E");
                        inputGobbler = new StreamGobbler(recordingProcess.getInputStream(), false, "ffmpeg O");

                        logger.info("Starting listener threads...");
                        errorGobbler.start();
                        errorGobbler.addActionListener("Stream mapping:", self);
                        inputGobbler.start();

                        recordingProcess.waitFor();

                        fireProcessUpdate(RECORDING_COMPLETE);

                    } catch (Exception e) {
                        logger.error("Error while running Windows screen recorder!", e);
                    }
                    return null;
                }
            });

        }

    } catch (Exception ie) {
        logger.error("Exception while running ScreenRecorder!", ie);
    }
}

From source file:org.apache.openjpa.lib.util.Files.java

/**
 * Return the file for the given package. If the given base directory
 * matches the given package structure, it will be used as-is. If not,
 * the package structure will be added beneath the base directory. If
 * the base directory is null, the current working directory will be
 * used as the base.// ww  w  .  j a va2  s .c o  m
 */
public static File getPackageFile(File base, String pkg, boolean mkdirs) {
    if (base == null)
        base = new File(AccessController.doPrivileged(J2DoPrivHelper.getPropertyAction("user.dir")));
    if (StringUtils.isEmpty(pkg)) {
        if (mkdirs && !(AccessController.doPrivileged(J2DoPrivHelper.existsAction(base))).booleanValue())
            AccessController.doPrivileged(J2DoPrivHelper.mkdirsAction(base));
        return base;
    }

    pkg = pkg.replace('.', File.separatorChar);
    File file = null;
    try {
        if ((AccessController.doPrivileged(J2DoPrivHelper.getCanonicalPathAction(base))).endsWith(pkg))
            file = base;
        else
            file = new File(base, pkg);
    } catch (PrivilegedActionException pae) {
        throw new NestableRuntimeException((IOException) pae.getException());
    } catch (IOException ioe) {
        throw new NestableRuntimeException(ioe);
    }

    if (mkdirs && !(AccessController.doPrivileged(J2DoPrivHelper.existsAction(file))).booleanValue())
        AccessController.doPrivileged(J2DoPrivHelper.mkdirsAction(file));
    return file;
}

From source file:org.codice.ddf.configuration.migration.AccessUtils.java

/**
 * Performs the specified action with privileges enabled. The action is performed with <i>all</i>
 * of the permissions possessed by this class' (or by the migration framework's) protection
 * domain./*from  w w w  . ja v a 2s .c o m*/
 *
 * <p>If the action's {@link ThrowingSupplier#get} method throws an <i>unchecked</i> exception, it
 * will propagate through this method.
 *
 * <p><i>Note:</i> Any DomainCombiner associated with the current AccessControlContext will be
 * ignored while the action is performed.
 *
 * @param <E> the type of exceptions thrown by the action
 * @param action the action to be performed
 * @throws E if the specified action's threw the exception
 * @throws IllegalArgumentException if <code>action</code> is <code>null</code>
 */
public static <E extends Exception> void doPrivileged(ThrowingRunnable<E> action) throws E {
    Validate.notNull(action, AccessUtils.INVALID_NULL_ACTION);
    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws Exception {
                action.run();
                return null;
            }
        });
    } catch (PrivilegedActionException pe) {
        final Exception e = pe.getException();

        if (e instanceof RuntimeException) { // should never happen but just to be safe!
            throw (RuntimeException) e;
        } else { // by design, the action is declared to only throw E
            throw (E) e;
        }
    }
}

From source file:org.elasticsearch.hadoop.script.GroovyScriptEngineService.java

public GroovyScriptEngineService(Settings settings) {
    super(settings);

    deprecationLogger.deprecated("[groovy] scripts are deprecated, use [painless] scripts instead");

    // Creates the classloader here in order to isolate Groovy-land code
    final SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new SpecialPermission());
    }/*  w  w  w.  j  av  a 2  s.co m*/
    this.loader = AccessController.doPrivileged((PrivilegedAction<ClassLoader>) () -> {
        // snapshot our context (which has permissions for classes), since the script has none
        AccessControlContext context = AccessController.getContext();
        return new ClassLoader(getClass().getClassLoader()) {
            @Override
            protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
                if (sm != null) {
                    try {
                        context.checkPermission(new ClassPermission(name));
                    } catch (SecurityException e) {
                        throw new ClassNotFoundException(name, e);
                    }
                }
                return super.loadClass(name, resolve);
            }
        };
    });
}

From source file:org.eclipse.gemini.blueprint.extender.internal.blueprint.event.EventAdminDispatcher.java

public void afterClose(final BlueprintEvent event) {
    if (dispatcher != null) {
        try {//from  ww w  .  j ava 2 s  .  c  om
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged(new PrivilegedAction<Object>() {
                    public Object run() {
                        dispatcher.afterClose(event);
                        return null;
                    }
                });
            } else {
                dispatcher.afterClose(event);
            }
        } catch (Throwable th) {
            log.warn("Cannot dispatch event " + event, th);
        }
    }
}

From source file:com.petalmd.armor.service.ArmorService.java

@Inject
public ArmorService(final Settings settings, final RestController restController, final Client client,
        final Authorizator authorizator, final AuthenticationBackend authenticationBackend,
        final HTTPAuthenticator httpAuthenticator, final SessionStore sessionStore,
        final AuditListener auditListener, final SearchService searchService) {
    super(settings);
    this.restController = restController;
    this.client = client;
    this.settings = settings;
    //securityConfigurationIndex = settings
    //        .get(ConfigConstants.ARMOR_CONFIG_INDEX_NAME, ConfigConstants.DEFAULT_SECURITY_CONFIG_INDEX);
    this.authenticationBackend = authenticationBackend;
    this.authorizator = authorizator;
    this.httpAuthenticator = httpAuthenticator;
    this.sessionStore = sessionStore;

    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new SpecialPermission());
    }//from   ww  w. j a va2s.c om

    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction<Boolean>() {
            @Override
            public Boolean run() throws Exception {
                method = RestController.class.getDeclaredMethod("getHandler", RestRequest.class);
                method.setAccessible(true);

                return true;
            }
        });
    } catch (final Exception e) {
        log.error(e.toString(), e);
        throw new ElasticsearchException(e.toString());
    }

    final String keyPath = settings.get(ConfigConstants.ARMOR_KEY_PATH, ".");
    //        AccessController.checkPermission(new FilePermission(keyPath+File.separator+"armor_node_key.key", "write"));
    SecretKey sc = null;
    try {
        sc = AccessController.doPrivileged(new PrivilegedExceptionAction<SecretKey>() {
            @Override
            public SecretKey run() throws Exception {
                final File keyFile = new File(keyPath, "armor_node_key.key");
                SecretKey sc = null;
                if (keyFile.exists()) {
                    log.debug("Loaded key from {}", keyFile.getAbsolutePath());
                    sc = new SecretKeySpec(FileUtils.readFileToByteArray(keyFile), "AES");
                } else {
                    final SecureRandom secRandom = SecureRandom.getInstance("SHA1PRNG");
                    final KeyGenerator kg = KeyGenerator.getInstance("AES");
                    kg.init(128, secRandom);
                    final SecretKey secretKey = kg.generateKey();
                    final byte[] enckey = secretKey.getEncoded();

                    if (enckey == null || enckey.length != 16) {
                        throw new Exception("invalid key " + (enckey == null ? -1 : enckey.length));
                    }
                    FileUtils.writeByteArrayToFile(keyFile, enckey);
                    sc = secretKey;
                    log.info("New key written to {}, make sure all nodes have this key",
                            keyFile.getAbsolutePath());
                }
                return sc;
            }
        });
    } catch (final Exception e) {
        log.error("Cannot generate or read secrety key", e);
        throw new ElasticsearchException(e.toString());
    }

    this.auditListener = auditListener;
    //TODO FUTURE index change audit trail

    final boolean checkForRoot = settings.getAsBoolean(ConfigConstants.ARMOR_CHECK_FOR_ROOT, true);

    if (SecurityUtil.isRootUser()) {

        if (checkForRoot) {
            throw new ElasticsearchException(
                    "You're trying to run elasticsearch as root or Windows Administrator and thats forbidden.");
        } else {
            log.warn(
                    "You're trying to run elasticsearch as root or Windows Administrator! Thats a potential security issue.");
        }

    }

    /*final String scriptingStatus = settings.get(ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING,
        ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT);
            
    if (scriptingStatus.equalsIgnoreCase(ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT)) {
    log.warn("{} has the default value {}, consider setting it to false if not needed",
            ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING, scriptingStatus);
    }
            
    if (scriptingStatus.equalsIgnoreCase("true")) {
    log.error("{} is configured insecure, consider setting it to false or " + ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT,
            ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING);
    }*/
    if (searchService == null) {
        throw new RuntimeException("ssnull");
    }

    ArmorService.secretKey = sc;
}