Example usage for java.lang System setSecurityManager

List of usage examples for java.lang System setSecurityManager

Introduction

In this page you can find the example usage for java.lang System setSecurityManager.

Prototype

public static void setSecurityManager(SecurityManager sm) 

Source Link

Document

Sets the system-wide security manager.

Usage

From source file:com.thoughtworks.acceptance.SecurityManagerTest.java

protected void tearDown() throws Exception {
    System.setSecurityManager(null);
    super.tearDown();
}

From source file:com.github.sakserv.minicluster.yarn.InJvmContainerExecutor.java

/**
 * Will construct the instance of this {@link ContainerExecutor} and will
 * install a {@link SystemExitDisallowingSecurityManager} which will help with
 * managing the life-cycle of the containers that contain System.exit calls.
 *//*from   w  w w . j  a  v a2s  .c o  m*/
public InJvmContainerExecutor() {
    logger.info("Adding SystemExitDisallowingSecurityManager");
    System.setSecurityManager(new SystemExitDisallowingSecurityManager());
}

From source file:net.sf.mpaxs.spi.computeHost.StartUp.java

/**
 *
 * @param cfg//from w  ww  .j a  va  2  s.co m
 */
public StartUp(Configuration cfg) {
    Settings settings = new Settings(cfg);
    try {
        System.setProperty("java.rmi.server.codebase", settings.getCodebase().toString());
        Logger.getLogger(StartUp.class.getName()).log(Level.INFO, "RMI Codebase at {0}",
                settings.getCodebase().toString());
    } catch (MalformedURLException ex) {
        Logger.getLogger(StartUp.class.getName()).log(Level.SEVERE, null, ex);
    }
    File policyFile;
    policyFile = new File(new File(settings.getOption(ConfigurationKeys.KEY_COMPUTE_HOST_WORKING_DIR)),
            settings.getPolicyName());
    if (!policyFile.exists()) {
        System.out.println("Did not find security policy, will create default one!");
        policyFile.getParentFile().mkdirs();
        BufferedReader br = new BufferedReader(new InputStreamReader(
                StartUp.class.getResourceAsStream("/net/sf/mpaxs/spi/computeHost/wideopen.policy")));
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(policyFile));
            String s = null;
            while ((s = br.readLine()) != null) {
                bw.write(s + "\n");
            }
            bw.flush();
            bw.close();
            br.close();
            Logger.getLogger(StartUp.class.getName()).log(Level.INFO,
                    "Using security policy at " + policyFile.getAbsolutePath());
        } catch (IOException ex) {
            Logger.getLogger(StartUp.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        Logger.getLogger(StartUp.class.getName()).log(Level.INFO,
                "Found existing policy file at " + policyFile.getAbsolutePath());
    }
    System.setProperty("java.security.policy", policyFile.getAbsolutePath());

    System.setProperty("java.net.preferIPv4Stack", "true");

    if (System.getSecurityManager() == null) {
        System.setSecurityManager(new SecurityManager());
    }

    Logger.getLogger(StartUp.class.getName()).log(Level.FINE, "Creating host");
    Host h = new Host();
    Logger.getLogger(StartUp.class.getName()).log(Level.FINE, "Configuring host");
    h.configure(cfg);
    Logger.getLogger(StartUp.class.getName()).log(Level.FINE,
            "Setting auth token " + settings.getOption(ConfigurationKeys.KEY_AUTH_TOKEN));
    String at = settings.getOption(ConfigurationKeys.KEY_AUTH_TOKEN);
    h.setAuthenticationToken(UUID.fromString(at));
    Logger.getLogger(StartUp.class.getName()).log(Level.INFO, "Starting host {0}", settings.getHostID());
    h.startComputeHost();
}

From source file:com.symbian.driver.remoting.master.TDIWrapper.java

/**
 * Standard Constructor/*from ww  w. j a  va 2 s .c  o  m*/
 * 
 * @param aTestPackage
 *            A test pacakage path.
 * @param aResultsPath
 *            A path where to collect the results.
 * @throws ArrayIndexOutOfBoundsException
 * @throws ParseException
 * @throws IOException
 * @throws TimeLimitExceededException
 */
public TDIWrapper(final File aTestPackage, final File aResultsPath)
        throws ArrayIndexOutOfBoundsException, ParseException, IOException, TimeLimitExceededException {

    // Setup Autmation Folder
    URL lSource = TDIWrapper.class.getProtectionDomain().getCodeSource().getLocation();
    File lInstallationFolder = new File(lSource.getPath()).getParentFile().getParentFile();

    iAutomationFolder = new File(lInstallationFolder, "automation");

    LOGGER.info("Automation folder has been set as: " + iAutomationFolder);

    // Initialise Package
    final Task lStartTask = initialize(aTestPackage, aResultsPath);

    //  for timeout set the root node of SymbianVisitor to xxyy
    //  do some kind of stopping!
    lSymbianThread = new Thread(new Runnable() {
        public void run() {
            Thread lCurrentThread = Thread.currentThread();
            if (lSymbianThread == lCurrentThread) {
                SymbianVisitor lSymbianVisitor = new SymbianVisitor();
                try {
                    TDConfig.getInstance().printConfig(true);
                } catch (IOException lE) {
                    LOGGER.log(Level.WARNING, "Could not print the config..." + lE.getMessage(), lE);
                }
                // execute the test
                SecurityManager lSec = null;
                try {
                    lSec = System.getSecurityManager();
                    //set security manager to disable system.exit() called by Test Driver
                    System.setSecurityManager(new NoExitSecurityManager());
                    lSymbianVisitor.start(lStartTask);
                } catch (SecurityException lSecurityException) {
                    // ignore
                } finally {
                    // reset security manager so that the server can exit in case of problems.
                    try {
                        System.setSecurityManager(lSec);
                    } catch (SecurityException lSecurityException) {
                        // ignore
                    }
                }
                //  cleanup all data except testresults

            }
        }
    });
}

From source file:org.nebulaframework.grid.Grid.java

/**
 * Starts {@link ClusterManager} instance with default settings,
 * read from default properties file.//from w w w .  j a  v a  2s .c o  m
 * 
 * @return ClusterManager
 * 
 * @throws IllegalStateException if a Grid Member (Cluster / Node) has
 * already started with in the current VM. Nebula supports only one Grid
 * Member per VM.
 */
public synchronized static ClusterManager startClusterManager() throws IllegalStateException {

    if (isInitialized()) {
        // A Grid Member has already started in this VM
        throw new IllegalStateException("A Grid Memeber Already Started in VM");
    }

    initializeDefaultExceptionHandler();

    StopWatch sw = new StopWatch();

    try {
        sw.start();
        log.info("ClusterManager Starting...");

        // Set Security Manager
        System.setSecurityManager(new SecurityManager());

        // Detect Configuration
        Properties config = ConfigurationSupport.detectClusterConfiguration();

        // Register with any Colombus Servers
        ClusterDiscoverySupport.registerColombus(config);

        clusterManager = true;

        log.debug("Starting up Spring Container...");

        applicationContext = new NebulaApplicationContext(CLUSTER_SPRING_CONTEXT, config);

        log.debug("Spring Container Started");

        return (ClusterManager) applicationContext.getBean("clusterManager");
    } finally {
        sw.stop();
        log.info("ClusterManager Started Up. " + sw.getLastTaskTimeMillis() + " ms");
    }

}

From source file:com.liferay.maven.arquillian.internal.tasks.ExecuteDeployerTask.java

protected void executeTool(String deployerClassName, ClassLoader classLoader, String[] args) throws Exception {

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    currentThread.setContextClassLoader(classLoader);

    SecurityManager currentSecurityManager = System.getSecurityManager();

    // Required to prevent premature exit by DBBuilder. See LPS-7524.
    SecurityManager securityManager = new SecurityManager() {

        @Override//from   w ww.  java  2  s. com
        public void checkPermission(Permission permission) {
        }

        @Override
        public void checkExit(int status) {
            throw new SecurityException();
        }
    };

    System.setSecurityManager(securityManager);

    try {
        System.setProperty("external-properties",
                "com/liferay/portal/tools/dependencies" + "/portal-tools.properties");
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

        Class<?> clazz = classLoader.loadClass(deployerClassName);

        Method method = clazz.getMethod("main", String[].class);

        method.invoke(null, (Object) args);
    } catch (InvocationTargetException ite) {
        if (!(ite.getCause() instanceof SecurityException)) {
            throw ite;
        }
    } finally {
        currentThread.setContextClassLoader(contextClassLoader);

        System.setSecurityManager(currentSecurityManager);
    }
}

From source file:com.haulmont.cuba.desktop.App.java

public void init(String[] args) {
    try {//  w ww . j  a  v  a  2 s.c  o  m
        System.setSecurityManager(null);
        initHomeDir();
        initLogging();
    } catch (Throwable t) {
        //noinspection CallToPrintStackTrace
        t.printStackTrace();
        System.exit(-1);
    }

    try {
        log.debug("Program arguments: " + Arrays.toString(args));

        initConnection();

        DesktopAppContextLoader contextLoader = new DesktopAppContextLoader(getDefaultAppComponents(),
                getDefaultAppPropertiesConfig(), args);
        contextLoader.load();

        messages = AppBeans.get(Messages.NAME);
        configuration = AppBeans.get(Configuration.NAME);
        uiEventsMulticaster = AppBeans.get(UiEventsMulticaster.class);

        initTheme();
        initLookAndFeelDefaults();
        initTestMode();
        initUI();
        initExceptionHandling();
        AppBeans.get(ExternalUIComponentsSource.class).checkInitialized();
    } catch (Throwable t) {
        log.error("Error initializing application", t);
        System.exit(-1);
    }
}

From source file:com.linkedin.pinot.common.utils.KafkaStarterUtils.java

private static void invokeTopicCommand(String[] args) {
    // jfim: Use Java security to trap System.exit in Kafka 0.9's TopicCommand
    System.setSecurityManager(new SecurityManager() {
        @Override/*from www  .  j a v a  2s.  c om*/
        public void checkPermission(Permission perm) {
            if (perm.getName().startsWith("exitVM")) {
                throw new SecurityException("System.exit is disabled");
            }
        }

        @Override
        public void checkPermission(Permission perm, Object context) {
            checkPermission(perm);
        }
    });

    try {
        TopicCommand.main(args);
    } catch (SecurityException ex) {
        // Do nothing, this is caused by our security manager that disables System.exit
    }

    System.setSecurityManager(null);
}

From source file:com.liferay.arquillian.maven.internal.tasks.ExecuteDeployerTask.java

protected void executeTool(String deployerClassName, ClassLoader classLoader, String[] args) throws Exception {

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    currentThread.setContextClassLoader(classLoader);

    SecurityManager currentSecurityManager = System.getSecurityManager();

    // Required to prevent premature exit by DBBuilder. See LPS-7524.

    SecurityManager securityManager = new SecurityManager() {

        @Override//from   www.  j a v a2s  .c o m
        public void checkPermission(Permission permission) {
            //It is not needed to check permissions
        }

        @Override
        public void checkExit(int status) {
            throw new SecurityException();
        }
    };

    System.setSecurityManager(securityManager);

    try {
        System.setProperty("external-properties",
                "com/liferay/portal/tools/dependencies" + "/portal-tools.properties");
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

        Class<?> clazz = classLoader.loadClass(deployerClassName);

        Method method = clazz.getMethod("main", String[].class);

        method.invoke(null, (Object) args);
    } catch (InvocationTargetException ite) {
        if (!(ite.getCause() instanceof SecurityException)) {
            throw ite;
        }
    } finally {
        currentThread.setContextClassLoader(contextClassLoader);

        System.setSecurityManager(currentSecurityManager);
    }
}

From source file:SwingUtil.java

/**
 * Get a file selection using the FileChooser dialog.
 *
 * @param owner/*from w  ww. j  a  v a2  s . c o m*/
 * The parent of this modal dialog.
 * @param defaultSelection
 * The default file selection as a file.
 * @param filter
 * An extension filter
 * @param title
 * The caption for the dialog.
 *
 * @return
 * A selected file or null if no selection is made.
 */
public static File getFileChoice(Component owner, File defaultSelection, FileFilter filter, String title) {
    //
    // There is apparently a bug in the native Windows FileSystem class that
    // occurs when you use a file chooser and there is a security manager
    // active. An error dialog is displayed indicating there is no disk in
    // Drive A:. To avoid this, the security manager is temporarily set to
    // null and then reset after the file chooser is closed.
    //
    SecurityManager sm = null;
    File choice = null;
    JFileChooser chooser = null;

    sm = System.getSecurityManager();
    System.setSecurityManager(null);

    chooser = new JFileChooser();
    if (defaultSelection.isDirectory()) {
        chooser.setCurrentDirectory(defaultSelection);
    } else {
        chooser.setSelectedFile(defaultSelection);
    }
    chooser.setFileFilter(filter);
    chooser.setDialogTitle(title);
    chooser.setApproveButtonText("OK");
    int v = chooser.showOpenDialog(owner);

    owner.requestFocus();
    switch (v) {
    case JFileChooser.APPROVE_OPTION:
        if (chooser.getSelectedFile() != null) {
            choice = chooser.getSelectedFile();
        }
        break;
    case JFileChooser.CANCEL_OPTION:
    case JFileChooser.ERROR_OPTION:
    }
    chooser.removeAll();
    chooser = null;
    System.setSecurityManager(sm);
    return choice;
}