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:org.rhq.bundle.ant.AntMain.java

private void initProject(Project project, ClassLoader coreLoader, DeploymentPhase phase) {
    if (coreLoader == null) {
        coreLoader = getClass().getClassLoader();
    }/*  w w  w .  j ava  2s .com*/

    project.setCoreLoader(coreLoader);
    project.setProperty(DeployPropertyNames.DEPLOY_PHASE, phase.name());

    addBuildListeners(project);
    addInputHandler(project);

    PrintStream savedErr = System.err;
    PrintStream savedOut = System.out;
    InputStream savedIn = System.in;

    // use a system manager that prevents from System.exit()
    SecurityManager oldsm = null;
    oldsm = System.getSecurityManager();

    //SecurityManager can not be installed here for backwards
    //compatibility reasons (PD). Needs to be loaded prior to
    //ant class if we are going to implement it.
    //System.setSecurityManager(new NoExitSecurityManager());
    try {
        if (allowInput) {
            project.setDefaultInputStream(System.in);
        }
        System.setIn(new DemuxInputStream(project));
        System.setOut(new PrintStream(new DemuxOutputStream(project, false)));
        System.setErr(new PrintStream(new DemuxOutputStream(project, true)));

        if (!projectHelp) {
            project.fireBuildStarted();
        }

        // set the thread priorities
        if (threadPriority != null) {
            try {
                project.log("Setting Ant's thread priority to " + threadPriority, Project.MSG_VERBOSE);
                Thread.currentThread().setPriority(threadPriority.intValue());
            } catch (SecurityException swallowed) {
                //we cannot set the priority here.
                project.log("A security manager refused to set the -nice value");
            }
        }

        project.init();

        // set user-define properties
        Enumeration e = definedProps.keys();
        while (e.hasMoreElements()) {
            String arg = (String) e.nextElement();
            String value = (String) definedProps.get(arg);
            project.setProperty(arg, value);
        }

        try {
            addTaskDefsForBundledTasks(project);
        } catch (IOException ie) {
            throw new RuntimeException(ie);
        } catch (ClassNotFoundException ce) {
            throw new RuntimeException(ce);
        }

        project.setProperty(MagicNames.ANT_FILE, buildFile.getAbsolutePath());
        project.setProperty(MagicNames.ANT_FILE_TYPE, MagicNames.ANT_FILE_TYPE_FILE);

        project.setKeepGoingMode(keepGoingMode);
        if (proxy) {
            //proxy setup if enabled
            ProxySetup proxySetup = new ProxySetup(project);
            proxySetup.enableProxies();
        }

        // RHQ NOTE: Besides parsing the build file, this will also execute the implicit ("") target.
        ProjectHelper.configureProject(project, buildFile);
    } finally {
        // put back the original security manager
        //The following will never eval to true. (PD)
        if (oldsm != null) {
            System.setSecurityManager(oldsm);
        }

        System.setOut(savedOut);
        System.setErr(savedErr);
        System.setIn(savedIn);
    }
}

From source file:org.rioproject.impl.util.DownloadManager.java

public static void main(String args[]) {
    try {/* w  ww .j  a v a  2 s  . co  m*/
        if (args.length < 2) {
            System.out
                    .println("Usage: org.rioproject.impl.util.DownloadManager " + "download-URL install-root");
            System.exit(-1);
        }
        String downloadFrom = args[0];
        String installPath = args[1];
        System.setSecurityManager(new java.rmi.RMISecurityManager());
        StagedSoftware download = new StagedSoftware();
        download.setLocation(downloadFrom);
        download.setInstallRoot(installPath);
        download.setUnarchive(true);
        DownloadManager slm = new DownloadManager(installPath, download);
        DownloadRecord record = slm.download();
        System.out.println("Details");
        System.out.println("-------");
        System.out.println(record.toString());
        //DownloadManager.remove(record);
    } catch (Throwable throwable) {
        throwable.printStackTrace();
    }
}

From source file:org.rioproject.resources.util.DownloadManager.java

public static void main(String args[]) {
    try {//www  . j  a v  a 2 s .com
        if (args.length < 2) {
            System.out.println(
                    "Usage: org.rioproject.resources.util.DownloadManager " + "download-URL install-root");
            System.exit(-1);
        }
        String downloadFrom = args[0];
        String installPath = args[1];
        System.setSecurityManager(new java.rmi.RMISecurityManager());
        StagedSoftware download = new StagedSoftware();
        download.setLocation(downloadFrom);
        download.setInstallRoot(installPath);
        download.setUnarchive(true);
        DownloadManager slm = new DownloadManager(installPath, download);
        DownloadRecord record = slm.download();
        System.out.println("Details");
        System.out.println("-------");
        System.out.println(record.toString());
        //DownloadManager.remove(record);
    } catch (Throwable throwable) {
        throwable.printStackTrace();
    }
}

From source file:org.rythmengine.RythmEngine.java

/**
 * Create a {@link Sandbox} instance to render the template
 *
 * @return an new sandbox instance//from  w  ww . java 2 s. co  m
 */
public synchronized Sandbox sandbox() {
    if (null != _secureExecutor) {
        return new Sandbox(this, _secureExecutor);
    }
    int poolSize = (Integer) conf().get(RythmConfigurationKey.SANDBOX_POOL_SIZE);
    SecurityManager csm = conf().get(RythmConfigurationKey.SANDBOX_SECURITY_MANAGER_IMPL);
    int timeout = (Integer) conf().get(RythmConfigurationKey.SANDBOX_TIMEOUT);
    SandboxThreadFactory fact = conf().get(RythmConfigurationKey.SANBOX_THREAD_FACTORY_IMPL);

    SecurityManager ssm = System.getSecurityManager();
    RythmSecurityManager rsm;
    String code;
    if (null == ssm || !(ssm instanceof RythmSecurityManager)) {
        code = conf().get(RythmConfigurationKey.SANDBOX_SECURE_CODE);
        rsm = new RythmSecurityManager(csm, code, this);
    } else {
        rsm = ((RythmSecurityManager) ssm);
        code = rsm.getCode();
    }
    secureCode = code;
    _secureExecutor = new SandboxExecutingService(poolSize, fact, timeout, this, code);
    Sandbox sandbox = new Sandbox(this, _secureExecutor);
    if (ssm != rsm)
        System.setSecurityManager(rsm);
    return sandbox;
}

From source file:org.siyapath.task.TaskProcessor.java

public void run() {
    log.debug("Preparing to start the task: " + task.getTaskID());
    try {//  ww  w.  ja v  a 2s  .  com
        taskInstance = getTaskInstance();
        TaskThread taskThread = new TaskThread("task-thread id:" + task.getTaskID());
        notifier.start();

        // sand-boxing with a custom security manager that denies most permissions
        System.setSecurityManager(siyapathSecurityManager);
        siyapathSecurityManager.disable("secpass");
        taskThread.start();
        try {
            taskThread.join();
        } catch (InterruptedException e) {
            log.warn("Thread was interrupted while waiting for task thread to complete. " + e.getMessage());
        }
        siyapathSecurityManager.disable("secpass");
        System.setSecurityManager(defaultSecurityManager);
        log.info("Task processing is finished. ID: " + task.getTaskID());
        notifier.stopNotifier();
    } catch (Exception e) {
        log.error("Task program instantiation failed. Aborting task: " + task.getTaskID());
        taskResult.setStatus(TaskStatus.ABORTED_ERROR);
        taskResult.setResults("<aborted_error>".getBytes());
    }
    for (int i = 0; i < 3; i++) {
        if (deliverTaskResult(taskResult)) {
            break;
        }
        log.warn("Couldn't send result to distributor. task: " + task.getTaskID());
    }
    context.decreaseProTasksNo(task.getTaskID());
}

From source file:org.springframework.context.expression.ApplicationContextExpressionTests.java

@Test
public void systemPropertiesSecurityManager() {
    GenericApplicationContext ac = new GenericApplicationContext();
    AnnotationConfigUtils.registerAnnotationConfigProcessors(ac);

    GenericBeanDefinition bd = new GenericBeanDefinition();
    bd.setBeanClass(TestBean.class);
    bd.getPropertyValues().add("country", "#{systemProperties.country}");
    ac.registerBeanDefinition("tb", bd);

    SecurityManager oldSecurityManager = System.getSecurityManager();
    try {/*  w w w  .  j  ava2  s.  co m*/
        System.setProperty("country", "NL");

        SecurityManager securityManager = new SecurityManager() {
            @Override
            public void checkPropertiesAccess() {
                throw new AccessControlException("Not Allowed");
            }

            @Override
            public void checkPermission(Permission perm) {
                // allow everything else
            }
        };
        System.setSecurityManager(securityManager);
        ac.refresh();

        TestBean tb = ac.getBean("tb", TestBean.class);
        assertEquals("NL", tb.getCountry());

    } finally {
        System.setSecurityManager(oldSecurityManager);
        System.getProperties().remove("country");
    }
}

From source file:org.springframework.data.hadoop.mapreduce.ExecutionUtils.java

static void disableSystemExitCall() {
    final SecurityManager securityManager = new SecurityManager() {

        @Override//from   www .  jav  a  2  s .  c o  m
        public void checkPermission(Permission permission) {
            String name = permission.getName();
            if (name.startsWith("exitVM")) {
                throw new ExitTrapped(name);
            }
        }
    };

    oldSM = System.getSecurityManager();
    System.setSecurityManager(securityManager);
}

From source file:org.springframework.data.hadoop.mapreduce.ExecutionUtils.java

static void enableSystemExitCall() {
    System.setSecurityManager(oldSM);
}

From source file:org.ublog.benchmark.social.SocialBenchmark.java

private GraphInterface getRemoteGraphServer(String serverName, int serverPort) {
    if (System.getSecurityManager() == null) {
        System.setSecurityManager(new RMISecurityManager());
    }/*from  ww  w  .jav a  2 s.  co  m*/
    try {
        if (logger.isInfoEnabled()) {
            logger.info("Trying to connect to graph server");
        }
        Registry reg = LocateRegistry.getRegistry(serverName, serverPort);
        System.out.println("reg " + reg.list().toString());
        return (GraphInterface) reg.lookup("Graph");

    } catch (NotBoundException ex) {
        Logger.getLogger("global").log(null, ex);
        return null;
    } catch (RemoteException ex) {
        ex.printStackTrace();
        Logger.getLogger("global").log(null, ex);
        return null;
    }
}

From source file:org.vpac.grix.view.swing.Grix.java

/**
 * @param args// www.  java2  s  .  co m
 */
public static void main(String[] args) {

    DependencyManager.showDownloadDialog = true;

    // Map<Dependency, String> dependencies = new HashMap<Dependency,
    // String>();

    // dependencies.put(Dependency.BOUNCYCASTLE, "jdk15-143");
    // dependencies.put(Dependency.ARCSGSI, "1.1");

    // DependencyManager.addDependencies(dependencies,
    // ArcsEnvironment.getArcsCommonJavaLibDirectory());

    JythonHelpers.setJythonCachedir();
    CoGProperties.getDefault().setProperty(CoGProperties.ENFORCE_SIGNING_POLICY, "false");

    java.security.Security.addProvider(new DefaultGridSecurityProvider());

    java.security.Security.setProperty("ssl.TrustManagerFactory.algorithm", "TrustAllCertificates");

    System.setSecurityManager(null);
    try {
        BouncyCastleTool.initBouncyCastle();
    } catch (ClassNotFoundException e1) {
        e1.printStackTrace();
    }

    final SplashScreen screen = new SplashScreen();
    screen.setVisible(true);

    try {
        CertificateFiles.copyCACerts(false);
    } catch (Exception e) {
        myLogger.error(e);
    }

    try {
        VomsesFiles.copyVomses(null);
    } catch (Exception e) {
        myLogger.error(e);
    }

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {

            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                // UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            } catch (Exception e) {
                // try {
                // UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
                // } catch (Exception e1) {
                // // TODO Auto-generated catch block
                // //e1.printStackTrace();
                // }
            }
            try {
                // try whether the current proxy is a VomsProxy
                if (LocalProxy.getProxyFile().exists()) {

                    try {
                        VomsProxy vomsProxy = new VomsProxy(LocalProxy.getProxyFile());
                        LocalProxy.setDefaultProxy(vomsProxy);
                    } catch (NoVomsProxyException e) {
                        // TODO Auto-generated catch block
                        // e.printStackTrace();
                        myLogger.debug(e);
                        // thats ok, but make sure that there is a
                        // LocalProxy.getDefaultProxy() object
                        LocalProxy.setDefaultProxy(new GlobusProxy(LocalProxy.getProxyFile()));
                    }
                } else {
                    LocalProxy.setDefaultProxy(new GlobusProxy(LocalProxy.getProxyFile()));
                }
            } catch (IOException ioe) {
                myLogger.error(ioe);
                // ioe.printStackTrace();
            }

            try {

                Grix application = new Grix();
                application.initIcons();

                application.getJFrame().setVisible(true);

                screen.dispose();

                if (LocalProxy.getDefaultProxy().getStatus() == GridProxy.INITIALIZED) {
                    LocalVomses.getLocalVomses().getVomses();
                }
                LocalProxy.addStatusListener(LocalVomses.getLocalVomses());

                if (GlobusLocations.defaultLocations().getUserCert().exists()
                        && GlobusLocations.defaultLocations().getUserKey().exists()
                        && !LocalProxy.getDefaultProxy().isValid()
                        && "yes".equals(UserProperty.getProperty("CREATE_PROXY_AT_STARTUP"))) {
                    // display proxy window
                    application.getGridProxyDialog().setVisible(true);
                }

            } catch (Exception e) {

                JOptionPane.showMessageDialog(null, "Could not start Grix: " + e.getLocalizedMessage(),
                        "Startup error", JOptionPane.ERROR_MESSAGE);

                System.exit(1);
            }
        }
    });
}