Example usage for java.lang System getSecurityManager

List of usage examples for java.lang System getSecurityManager

Introduction

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

Prototype

public static SecurityManager getSecurityManager() 

Source Link

Document

Gets the system-wide security manager.

Usage

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

/**
 * Prepares the files required by ANT file using the data description, locks
 * them, and prepares the right file name for GDG. Afterwards calls the
 * executable command defined in the task.
 * /* w  w w .j a  va  2  s  . co  m*/
 * @throws BuildException occurs if an error occurs
 */
@Override
public void execute() throws BuildException {
    int returnCode = Result.SUCCESS;
    // this boolean is necessary to understand if I have an exception
    // before calling the main class
    boolean isExecutionStarted = false;

    AntBatchSecurityManager batchSM = (AntBatchSecurityManager) System.getSecurityManager();
    batchSM.setInternalAction(true);
    // creates a list with all data description impl
    List<DataDescriptionImpl> ddList = null;

    try {
        // gets all data description requested by this task
        ddList = ImplementationsContainer.getInstance().getDataDescriptionsByItem(this);
        // if list of data description is empty, go to execute the command
        if (!ddList.isEmpty()) {

            // after locking, checks for GDG
            // is sure here the root (is a properties file) of GDG is locked
            // (doesn't matter if in READ or WRITE)
            // so can read a consistent data from root and gets the right
            // generation
            // starting from relative position
            for (DataDescriptionImpl ddImpl : ddList) {
                // loads GDG generation!! it meeans the real file name of
                // generation
                GDGManager.load(ddImpl);
                log(AntMessage.JEMA034I.toMessage().getFormattedMessage(ddImpl));
                // scans all datasets of datadescription adding new
                // environment variable
                for (DataSetImpl dataset : ddImpl.getDatasets()) {
                    addEnvVariable(ddImpl.getName(), dataset.getRealFile());
                }
            }

        }

        // calls super-method to execute the command configured into JCL
        batchSM.setInternalAction(false);
        // executes the program defined in JCL
        // setting the boolean to TRUE
        isExecutionStarted = true;
        super.execute();
    } catch (BuildException e1) {
        returnCode = Result.ERROR;
        throw e1;
    } catch (RemoteException e) {
        returnCode = Result.ERROR;
        throw new BuildException(e);
    } catch (IOException e) {
        returnCode = Result.ERROR;
        throw new BuildException(e);
    } finally {
        batchSM.setInternalAction(true);

        Object rcObject = PropertyHelper.getPropertyHelper(getProject()).getProperty(RESULT_KEY);
        if (rcObject != null) {
            returnCode = Parser.parseInt(rcObject.toString(), Result.SUCCESS);
        }
        ReturnCodesContainer.getInstance().setReturnCode(getProject(), this, returnCode);

        // finally and always must release the locks previously asked
        // checks datasets list
        if (ddList != null && !ddList.isEmpty()) {
            StringBuilder exceptions = new StringBuilder();
            // scans data descriptions
            for (DataDescriptionImpl ddImpl : ddList) {
                try {
                    // consolidates the GDG situation
                    // changing the root (is a properties file)
                    // only if execution started
                    if (isExecutionStarted) {
                        GDGManager.store(ddImpl);
                    }
                } catch (IOException e) {
                    // ignore
                    LogAppl.getInstance().ignore(e.getMessage(), e);
                    log(AntMessage.JEMA036E.toMessage().getFormattedMessage(e.getMessage()));
                    if (exceptions.length() == 0) {
                        exceptions.append(AntMessage.JEMA036E.toMessage().getFormattedMessage(e.getMessage()));
                    } else {
                        exceptions.append(AntMessage.JEMA036E.toMessage().getFormattedMessage(e.getMessage()))
                                .append("\n");
                    }
                }
            }
            if (exceptions.length() > 0) {
                log(StringUtils.center("ATTENTION", 40, "-"));
                log(exceptions.toString());
            }
        }
        batchSM.setInternalAction(false);
    }
}

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  www . j a va  2  s  . com*/
 * 
 * @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.eclipse.ecr.runtime.api.login.LoginComponent.java

@Override
public LoginContext loginAs(final String username) throws LoginException {
    // login as system user is a privileged action
    try {/*from  w w w .  j  av a  2  s  . c  om*/
        return AccessController.doPrivileged(new PrivilegedExceptionAction<LoginContext>() {
            @Override
            public LoginContext run() throws LoginException {
                SecurityManager sm = System.getSecurityManager();
                if (sm != null) {
                    sm.checkPermission(new SystemLoginPermission());
                }
                return systemLogin(username);
            }
        });
    } catch (PrivilegedActionException e) {
        throw (LoginException) e.getException();
    }
}

From source file:org.mule.module.management.agent.WrapperManagerAgent.java

/**
 * This method is a copy of the implementation of
 * {@link WrapperManagerMBean#getJavaPID()} and it is here because that method is
 * not present in the {@link WrapperManagerMBean} until version 3.2.3.
 * SpringSource's TC Server uses The wrapper version 3.2.0 so having this method
 * here allows us to be compatible with TC Server.
 *
 * @return The PID of the Java process.// w  w  w .j av  a 2 s . c  o  m
 * @see <a href="http://www.mulesoft.org/jira/browse/MULE-5106">MULE-5106</a>
 */
public static int getJavaPID() {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new WrapperPermission("getJavaPID"));
    }

    return WrapperSystemPropertyUtil.getIntProperty("wrapper.java.pid", 0);
}

From source file:com.vmware.identity.idm.server.IdmServer.java

/**
 * Initialize the IDM service.//from www .  jav  a2  s. c o  m
 *
 * @throws Exception when something goes wrong with initialization.
 */
private static void initialize() throws Exception {
    try (IDiagnosticsContextScope diagCtxt = DiagnosticsContextFactory.createContext("IDM Startup", "")) {
        logger.info("Starting IDM Server...");
        logger.debug("Creating RMI registry on port {}", Tenant.RMI_PORT);

        boolean allowRemoteConnections = Boolean
                .parseBoolean(System.getProperty(ALLOW_REMOTE_PROPERTY, "false"));

        if (allowRemoteConnections) {
            logger.warn("RMI registry is allowing remote connections!");
            registry = LocateRegistry.createRegistry(Tenant.RMI_PORT);
        } else {
            logger.debug("RMI registry is restricted to the localhost");
            RMIClientSocketFactory csf = RMISocketFactory.getDefaultSocketFactory();
            RMIServerSocketFactory ssf = new LocalRMIServerSocketFactory();
            registry = LocateRegistry.createRegistry(Tenant.RMI_PORT, csf, ssf);
        }

        // Assign a security manager, in the event that dynamic classes are loaded
        if (System.getSecurityManager() == null) {
            logger.debug("Creating RMI Security Manager...");
            System.setSecurityManager(new RMISecurityManager());
        }

        logger.debug("Creating Config Store factory...");
        IConfigStoreFactory cfgStoreFactory = new ConfigStoreFactory();

        logger.debug("Creating Identity Provider factory...");
        IProviderFactory providerFactory = new ProviderFactory();

        logger.debug("Checking VMware Directory Service...");
        ServerUtils.check_directory_service();

        logger.debug("Setting system properties...");
        System.setProperties(new ThreadLocalProperties(System.getProperties()));

        logger.debug("Creating Identity Manager instance...");
        manager = new IdentityManager(cfgStoreFactory, providerFactory);

        String rmiAddress = String.format("rmi://localhost:%d/%s", Tenant.RMI_PORT, IDENTITY_MANAGER_BIND_NAME);
        logger.debug("Binding to RMI address '{}'", rmiAddress);
        loginManager = new IdmLoginManager(manager);
        ILoginManager stub = (ILoginManager) UnicastRemoteObject.exportObject(loginManager, 0);
        Naming.rebind(rmiAddress, stub);

        startHeartbeat();

        logger.info(VmEvent.SERVER_STARTED, "IDM Server has started");
    } catch (Throwable t) {
        logger.error(VmEvent.SERVER_FAILED_TOSTART, "IDM Server has failed to start", t);
        throw t;
    }
}

From source file:org.wso2.carbon.automation.extensions.jmeter.JMeterTestManager.java

private String executeTest(File test) throws Exception {
    String reportFileName;// www  .ja  v a 2 s .  co m
    String reportFileFullPath;
    JMeter jmeterInstance = new JMeter();
    try {
        log.info("Executing test: " + test.getCanonicalPath());
        reportFileName = test.getName().substring(0, test.getName().lastIndexOf(".")) + "-"
                + fmt.format(new Date()) + ".jmeterResult" + ".jtl";

        File reportDir = JMeterInstallationProvider.getInstance().getReportDir();
        reportFileFullPath = reportDir.toString() + File.separator + reportFileName;
        List<String> argsTmp = Arrays.asList("-n", "-t", test.getCanonicalPath(), "-l",
                reportDir.toString() + File.separator + reportFileName, "-p", jmeterProps.toString(), "-d",
                jmeterHome.getCanonicalPath(), "-L", "jorphan=" + jmeterLogLevel, "-L",
                "jmeter.util=" + jmeterLogLevel);

        List<String> args = new ArrayList<String>();

        args.addAll(argsTmp);

        SecurityManager oldManager = System.getSecurityManager();

        UncaughtExceptionHandler oldHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

            public void uncaughtException(Thread t, Throwable e) {
                if (e instanceof ExitException && ((ExitException) e).getCode() == 0) {
                    return; //Ignore
                }
                log.error("Error in thread " + t.getName());
            }
        });

        try {
            logParamsAndProps(args);

            jmeterInstance.start(args.toArray(new String[] {}));

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(new FileInputStream(jmeterLogFile), Charset.defaultCharset()));

            while (!checkForEndOfTest(in)) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    break;
                }
            }

        } catch (ExitException e) {
            if (e.getCode() != 0) {
                throw new Exception("Test failed", e);
            }
        } catch (Exception e) {
            log.error(e);

        } finally {
            System.setSecurityManager(oldManager);
            Thread.setDefaultUncaughtExceptionHandler(oldHandler);
        }
    } catch (IOException e) {
        throw new Exception("Can't execute test", e);
    }
    return reportFileFullPath;
}

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

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

From source file:MailHandlerDemo.java

/**
 * Used debug problems with the logging.properties. The system property
 * java.security.debug=access,stack can be used to trace access to the
 * LogManager reset./*w w  w  .j ava  2s . co m*/
 *
 * @param prefix a string to prefix the output.
 * @param err any PrintStream or null for System.out.
 */
@SuppressWarnings("UseOfSystemOutOrSystemErr")
private static void checkConfig(String prefix, PrintStream err) {
    if (prefix == null || prefix.trim().length() == 0) {
        prefix = "DEBUG";
    }

    if (err == null) {
        err = System.out;
    }

    try {
        err.println(prefix + ": java.version=" + System.getProperty("java.version"));
        err.println(prefix + ": LOGGER=" + LOGGER.getLevel());
        err.println(prefix + ": JVM id " + ManagementFactory.getRuntimeMXBean().getName());
        err.println(prefix + ": java.security.debug=" + System.getProperty("java.security.debug"));
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            err.println(prefix + ": SecurityManager.class=" + sm.getClass().getName());
            err.println(prefix + ": SecurityManager classLoader=" + toString(sm.getClass().getClassLoader()));
            err.println(prefix + ": SecurityManager.toString=" + sm);
        } else {
            err.println(prefix + ": SecurityManager.class=null");
            err.println(prefix + ": SecurityManager.toString=null");
            err.println(prefix + ": SecurityManager classLoader=null");
        }

        String policy = System.getProperty("java.security.policy");
        if (policy != null) {
            File f = new File(policy);
            err.println(prefix + ": AbsolutePath=" + f.getAbsolutePath());
            err.println(prefix + ": CanonicalPath=" + f.getCanonicalPath());
            err.println(prefix + ": length=" + f.length());
            err.println(prefix + ": canRead=" + f.canRead());
            err.println(prefix + ": lastModified=" + new java.util.Date(f.lastModified()));
        }

        LogManager manager = LogManager.getLogManager();
        String key = "java.util.logging.config.file";
        String cfg = System.getProperty(key);
        if (cfg != null) {
            err.println(prefix + ": " + cfg);
            File f = new File(cfg);
            err.println(prefix + ": AbsolutePath=" + f.getAbsolutePath());
            err.println(prefix + ": CanonicalPath=" + f.getCanonicalPath());
            err.println(prefix + ": length=" + f.length());
            err.println(prefix + ": canRead=" + f.canRead());
            err.println(prefix + ": lastModified=" + new java.util.Date(f.lastModified()));
        } else {
            err.println(prefix + ": " + key + " is not set as a system property.");
        }
        err.println(prefix + ": LogManager.class=" + manager.getClass().getName());
        err.println(prefix + ": LogManager classLoader=" + toString(manager.getClass().getClassLoader()));
        err.println(prefix + ": LogManager.toString=" + manager);
        err.println(prefix + ": MailHandler classLoader=" + toString(MailHandler.class.getClassLoader()));
        err.println(
                prefix + ": Context ClassLoader=" + toString(Thread.currentThread().getContextClassLoader()));
        err.println(prefix + ": Session ClassLoader=" + toString(Session.class.getClassLoader()));
        err.println(prefix + ": DataHandler ClassLoader=" + toString(DataHandler.class.getClassLoader()));

        final String p = MailHandler.class.getName();
        key = p.concat(".mail.to");
        String to = manager.getProperty(key);
        err.println(prefix + ": TO=" + to);
        if (to != null) {
            err.println(prefix + ": TO=" + Arrays.toString(InternetAddress.parse(to, true)));
        }

        key = p.concat(".mail.from");
        String from = manager.getProperty(key);
        if (from == null || from.length() == 0) {
            Session session = Session.getInstance(new Properties());
            InternetAddress local = InternetAddress.getLocalAddress(session);
            err.println(prefix + ": FROM=" + local);
        } else {
            err.println(prefix + ": FROM=" + Arrays.asList(InternetAddress.parse(from, false)));
            err.println(prefix + ": FROM=" + Arrays.asList(InternetAddress.parse(from, true)));
        }

        synchronized (manager) {
            final Enumeration<String> e = manager.getLoggerNames();
            while (e.hasMoreElements()) {
                final Logger l = manager.getLogger(e.nextElement());
                if (l != null) {
                    final Handler[] handlers = l.getHandlers();
                    if (handlers.length > 0) {
                        err.println(prefix + ": " + l.getClass().getName() + ", " + l.getName());
                        for (Handler h : handlers) {
                            err.println(prefix + ":\t" + toString(prefix, err, h));
                        }
                    }
                }
            }
        }
    } catch (Throwable error) {
        err.print(prefix + ": ");
        error.printStackTrace(err);
    }
    err.flush();
}

From source file:org.eclipse.gemini.blueprint.extender.internal.support.NamespacePlugins.java

public InputSource resolveEntity(final String publicId, final String systemId)
        throws SAXException, IOException {
    if (System.getSecurityManager() != null) {
        try {/* w  w  w. j av  a 2  s  .c  o m*/
            return AccessController.doPrivileged(new PrivilegedExceptionAction<InputSource>() {

                public InputSource run() throws Exception {
                    return doResolveEntity(publicId, systemId);
                }
            });
        } catch (PrivilegedActionException pae) {
            Exception cause = pae.getException();
            handleInputSourceException(cause);
        }
    } else {
        try {
            return doResolveEntity(publicId, systemId);
        } catch (Exception ex) {
            handleInputSourceException(ex);
        }
    }

    return null;
}

From source file:org.elasticsearch.xpack.qa.sql.security.SqlSecurityTestCase.java

@Before
public void setInitialAuditLogOffset() {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new SpecialPermission());
    }/*  w  ww  . ja v a  2  s. c  om*/
    AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
        if (false == Files.exists(AUDIT_LOG_FILE)) {
            auditLogWrittenBeforeTestStart = 0;
            return null;
        }
        if (false == Files.isRegularFile(AUDIT_LOG_FILE)) {
            throw new IllegalStateException(
                    "expected tests.audit.logfile [" + AUDIT_LOG_FILE + "]to be a plain file but wasn't");
        }
        try {
            auditLogWrittenBeforeTestStart = Files.size(AUDIT_LOG_FILE);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    });
}