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.ngrinder.sm.SecurityManagerTest.java

@After
public void disableSecurity() {
    System.setSecurityManager(preSecurityManager);
}

From source file:org.openanzo.test.client.cli.TestCommandLineInterface.java

/**
 * Isolates a java method call to the command line interface's main method. Mock System in, out and error are put around the method call and System.exit's
 * are managed and their status captured.
 * /*from   ww  w  .ja v  a  2  s . c  om*/
 * The System out, error and exit status are returned.
 * 
 */
private TestCommandResult runCommandTest(String command, InputStream input) throws Exception {
    InputStream defaultInput = System.in;
    PrintStream defaultOutput = System.out;
    PrintStream defaultError = System.err;
    SecurityManager defaultSecurityManager = System.getSecurityManager();

    int status = -1;
    String output = null;
    String error = null;
    try {
        System.setIn(input);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        System.setOut(new PrintStream(new PrintStream(out)));

        ByteArrayOutputStream err = new ByteArrayOutputStream();
        System.setErr(new PrintStream(new PrintStream(err)));

        System.setSecurityManager(new ExitStatusManager());
        try {
            CommandLineInterface.main(command.split("\\s+"));

        } catch (ExitStatusException e) {
            status = e.getStatus();
        }

        output = out.toString("UTF-8");
        error = err.toString("UTF-8");
    } finally {
        System.setIn(defaultInput);
        System.setOut(defaultOutput);
        System.setErr(defaultError);
        System.setSecurityManager(defaultSecurityManager);
    }

    return new TestCommandResult(output, error, status);
}

From source file:org.openscience.jmol.app.JmolApp.java

/**
 * standard Jmol application entry point
 * @param args//from  w  ww .  j  a  va2  s  . co  m
 */
public JmolApp(String[] args) {

    if (System.getProperty("javawebstart.version") != null) {

        // If the property is found, Jmol is running with Java Web Start. To fix
        // bug 4621090, the security manager is set to null.
        System.setSecurityManager(null);
    }
    if (System.getProperty("user.home") == null) {
        System.err.println(GT._("Error starting Jmol: the property 'user.home' is not defined."));
        System.exit(1);
    }
    File ujmoldir = new File(new File(System.getProperty("user.home")), ".jmol");
    ujmoldir.mkdirs();
    userPropsFile = new File(ujmoldir, "properties");
    historyFile = new HistoryFile(new File(ujmoldir, "history"), "Jmol's persistent values");

    parseCommandLine(args);
}

From source file:org.pentaho.di.kitchen.KitchenIT.java

@Before
public void setUp() {
    oldSecurityManager = System.getSecurityManager();
    System.setSecurityManager(new MySecurityManager(oldSecurityManager));
}

From source file:org.pentaho.di.kitchen.KitchenIT.java

@After
public void tearDown() {
    System.setSecurityManager(oldSecurityManager);
}

From source file:org.pentaho.di.pan.PanIT.java

@Before
public void setUp() throws KettleException {
    KettleEnvironment.init();//from   w ww .j  av a 2 s. c om
    oldSecurityManager = System.getSecurityManager();
    System.setSecurityManager(new PanIT.MySecurityManager(oldSecurityManager));
}

From source file:org.pepstock.jem.ant.tasks.StepListener.java

/**
 * Called by ANT engine when job is started.<br>
 * Notifies to JEM the job is starting, passing process id and receiving the
 * authorizations of job user instance.//from   ww w  .j a  v  a2 s  .c o m
 * 
 * @param event ANT event
 */
@Override
public void buildStarted(BuildEvent event) {
    if (door == null) {
        // get port number from env var
        // AntTask has passed and set this information (MUST)
        String port = System.getProperty(RmiKeys.JEM_RMI_PORT);
        try {
            // creates RMI connection with localhost (default) and using
            // port number.
            // if port is null or not a number, -1 is return and a RMI
            // Exception will occur
            RegistryLocator locator = new RegistryLocator(Parser.parseInt(port, -1));
            // check the taskdoor object is binded, if not, a exception
            // occurs
            if (locator.hasRmiObject(TasksDoor.NAME)) {
                // gets remote object
                door = (TasksDoor) locator.getRmiObject(TasksDoor.NAME);
                // send to JEM node the current process id.
                // uses JMX implementation of JDK.
                // BE CAREFUL! Not all JVM returns the value in same format
                // receives all roles for job user and stores in a static
                // reference
                // of realm
                JobStartedObjects objects = door.setJobStarted(JobId.VALUE,
                        ManagementFactory.getRuntimeMXBean().getName());

                // PAY attention: after creating data paths container
                // calls a getabsolutepath method to load all necessary classes in classloader.
                // This is MANDATORY to avoid StackOverFlow in the SecurityManager 
                // during the CheckRead on files.
                DataPathsContainer.createInstance(objects.getStorageGroupsManager());
                DataPathsContainer.getInstance().getAbsoluteDataPath(JobId.VALUE);

                // loads data paths as properties
                int index = 0;
                for (String dataName : DataPathsContainer.getInstance().getDataPathsNames()) {
                    String path = DataPathsContainer.getInstance().getDataPaths().get(index);
                    String property = ConfigKeys.JEM_DATA_PATH_NAME + "." + dataName;
                    System.setProperty(property, path);
                    index++;
                }

                Collection<Role> myroles = objects.getRoles();
                // check if is already instantiated. If yes, does nothing
                if (System.getSecurityManager() == null) {
                    System.setSecurityManager(new AntBatchSecurityManager(myroles));
                } else {
                    throw new BuildException(AntMessage.JEMA039E.toMessage().getMessage());
                }
            } else {
                throw new BuildException(AntMessage.JEMA038E.toMessage().getFormattedMessage(TasksDoor.NAME));
            }
            // sets the SM for internal actions
            AntBatchSecurityManager batchSM = (AntBatchSecurityManager) System.getSecurityManager();
            // sets internal action to true so it can perform same authorized action
            batchSM.setInternalAction(true);
            // creates the locker to lock resources
            locker = new Locker();
            // sets internal action to false 
            batchSM.setInternalAction(false);

        } catch (AntException e) {
            throw new BuildException(AntMessage.JEMA040E.toMessage().getFormattedMessage(e.getMessage()), e);
        } catch (RemoteException e) {
            throw new BuildException(AntMessage.JEMA040E.toMessage().getFormattedMessage(e.getMessage()), e);
        } catch (UnknownHostException e) {
            throw new BuildException(AntMessage.JEMA040E.toMessage().getFormattedMessage(e.getMessage()), e);
        }
    }

}

From source file:org.pepstock.jem.junit.test.antutils.java.TrySecurity.java

/**
 * /*from  w  w  w . j  av a2 s .  co  m*/
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {

    String what = null;
    try {
        what = "CHANGE SECURITY MANAGER!";
        // gry to change security manager
        System.setSecurityManager(null);
    } catch (Exception e) {
        e.printStackTrace();
        try {
            what = "CHANGE FIELD OF SECURITY MANAGER!";
            SecurityManager sm = System.getSecurityManager();
            Field f = sm.getClass().getField("isAdministrator");
            System.err.println(FieldUtils.readField(f, sm, true));
        } catch (Exception e1) {
            e1.printStackTrace();
            return;
        }
    }
    throw new SecurityException("Securitymanager is not secure: " + what);
}

From source file:org.pepstock.jem.junit.test.springbatch.java.TrySecurityRunnable.java

@Override
public void run() {

    String what = null;// w  ww .ja  v  a2  s.c  om
    try {
        what = "CHANGE SECURITY MANAGER!";
        // gry to change security manager
        System.setSecurityManager(null);
    } catch (Exception e) {
        e.printStackTrace();
        try {
            what = "CHANGE FIELD OF SECURITY MANAGER!";
            SecurityManager sm = System.getSecurityManager();
            Field f = sm.getClass().getField("isAdministrator");
            System.err.println(FieldUtils.readField(f, sm, true));
        } catch (Exception e1) {
            e1.printStackTrace();
            return;
        }
    }
    throw new SecurityException("Securitymanager is not secure: " + what);
}

From source file:org.quickserver.net.server.QuickServer.java

/**
 * Starts the QuickServer.// w  w w  .  j a  va 2s.  com
 *
 * @exception org.quickserver.net.AppException 
 *  if Server already running or if it could not load the classes
 *  [ClientCommandHandler, ClientAuthenticationHandler, ClientData].
 * @see #startService
 */
public void startServer() throws AppException {
    logger.log(Level.FINE, "Starting {0}", getName());

    if (isClosed() == false) {
        logger.log(Level.WARNING, "Server {0} already running.", getName());
        throw new AppException("Server " + getName() + " already running.");
    }

    blockingMode = getBasicConfig().getServerMode().getBlocking();

    if (getSecure().isEnable() && blockingMode == false) {
        //TODO we need to fix this..
        logger.warning(
                "QuickServer does not support secure servers under non-blocking mode! So will run in blocking mode.");
        blockingMode = true;
        getBasicConfig().getServerMode().setBlocking(blockingMode);
    }

    if (serverBanner == null) {
        serverBanner = "\n-------------------------------" + "\n Name : " + getName() + "\n Port : " + getPort()
                + "\n-------------------------------\n";
        logger.finest("Default Server Banner Generated");
    }
    try {
        loadApplicationClasses();

        //load class from Advanced Settings
        Class clientIdentifierClass = getClass(getBasicConfig().getAdvancedSettings().getClientIdentifier(),
                true);
        clientIdentifier = (ClientIdentifier) clientIdentifierClass.newInstance();
        clientIdentifier.setQuickServer(QuickServer.this);

        //load class from ObjectPoolConfig
        Class poolManagerClass = getClass(getBasicConfig().getObjectPoolConfig().getPoolManager(), true);
        poolManager = (PoolManager) poolManagerClass.newInstance();

        //load class QSObjectPoolMaker
        Class qsObjectPoolMakerClass = getClass(getBasicConfig().getAdvancedSettings().getQsObjectPoolMaker(),
                true);
        qsObjectPoolMaker = (QSObjectPoolMaker) qsObjectPoolMakerClass.newInstance();

        loadServerHooksClasses();
        processServerHooks(ServerHook.PRE_STARTUP);

        if (getSecure().isLoad() == true)
            loadSSLContext(); //v1.4.0

        loadBusinessLogic();
    } catch (ClassNotFoundException e) {
        logger.log(Level.SEVERE, "Could not load class/s: " + e, e);
        throw new AppException("Could not load class/s : " + e);
    } catch (InstantiationException e) {
        logger.log(Level.SEVERE, "Could not instantiate class/s: " + e, e);
        throw new AppException("Could not instantiate class/s: " + e);
    } catch (IllegalAccessException e) {
        logger.log(Level.SEVERE, "Illegal access to class/s: " + e, e);
        throw new AppException("Illegal access to class/s: " + e);
    } catch (IOException e) {
        logger.log(Level.SEVERE, "IOException: " + e, e);
        throw new AppException("IOException: " + e);
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception: " + e, e);
        logger.log(Level.FINE, "StackTrace:\n{0}", MyString.getStackTrace(e));
        throw new AppException("Exception : " + e);
    }

    //v1.3.3
    if (getSecurityManagerClass() != null) {
        System.setSecurityManager(getSecurityManager());
    }

    setServiceState(Service.INIT);
    t = new Thread(this, "QuickServer - " + getName());
    t.start();

    do {
        Thread.yield();
    } while (getServiceState() == Service.INIT);

    if (getServiceState() != Service.RUNNING) {
        if (exceptionInRun != null)
            throw new AppException("Could not start server " + getName() + "! Details: " + exceptionInRun);
        else
            throw new AppException("Could not start server " + getName());
    }
    lastStartTime = new java.util.Date();
    logger.log(Level.FINE, "Started {0}, Date: {1}", new Object[] { getName(), lastStartTime });
}