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:com.cisco.dvbu.ps.deploytool.dao.wsapi.VCSWSDAOImpl.java

public void vcsExportCommand(String prefix, String arguments, String vcsIgnoreMessages, String propertyFile)
        throws CompositeException {

    String identifier = "VCSWSDAOImpl.vcsExportCommand"; // some unique identifier that characterizes this invocation.
    String actionName = "EXPORT";

    try {//from  w  ww .  ja v  a  2s.co  m
        boolean preserveQuotes = false;
        boolean initArgsList = true;
        List<String> argsList = new ArrayList<String>();
        argsList = CommonUtils.parseArguments(argsList, initArgsList, arguments, preserveQuotes, propertyFile);
        String[] args = argsList.toArray(new String[0]);

        /*
         * 2014-02-14 (mtinius): Removed the PDTool Archive capability
         */
        //         ExportCommand.startCommand(null, null, args);
        /*
         * 2014-02-14 (mtinius): Added security manager around the Composite native Archive code because
         *                    it has System.out.println and System.exit commands.  Need to trap both.
         */
        String maskedargsList = CommonUtils.getArgumentListMasked(argsList);
        if (logger.isDebugEnabled()) {
            logger.debug(identifier + "(prefix, arguments, vcsIgnoreMessages, propertyFile).  prefix=" + prefix
                    + "  arguments=[" + maskedargsList + "]" + "  vcsIgnoreMessages=" + vcsIgnoreMessages
                    + "  propertyFile=" + propertyFile);
        }

        // Get the existing security manager
        SecurityManager sm = System.getSecurityManager();
        PrintStream originalOut = System.out;
        PrintStream originalErr = System.err;
        String command = "ExportCommand.startCommand";
        try {
            // Get the offset location of the java.policy file [offset from PDTool home].
            String javaPolicyOffset = CommonConstants.javaPolicy;
            String javaPolicyLocation = CommonUtils.extractVariable(prefix,
                    CommonUtils.getFileOrSystemPropertyValue(propertyFile, "PROJECT_HOME_PHYSICAL"),
                    propertyFile, true) + javaPolicyOffset;
            // Set the java security policy
            System.getProperties().setProperty("java.security.policy", javaPolicyLocation);

            // Create a new System.out Logger
            Logger exportLogger = Logger.getLogger(ExportCommand.class);
            System.setOut(new PrintStream(new LogOutputStream(exportLogger, Level.INFO)));
            System.setErr(new PrintStream(new LogOutputStream(exportLogger, Level.ERROR)));
            // Create a new security manager
            System.setSecurityManager(new NoExitSecurityManager());

            // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation.
            if (CommonUtils.isExecOperation()) {
                // Invoke the Composite native export command.
                ExportCommand.startCommand(null, null, args);
            } else {
                logger.info("\n\nWARNING - NO_OPERATION: COMMAND [" + command + "], ACTION [" + actionName
                        + "] WAS NOT PERFORMED.\n");
            }
        } catch (NoExitSecurityExceptionStatusNonZero nesesnz) {
            String error = identifier + ":: Exited with exception from System.exit(): " + command
                    + "(null, null, " + maskedargsList + ")";
            logger.error(error);
            throw new CompositeException(error);
        } catch (NoExitSecurityExceptionStatusZero nesezero) {
            if (logger.isDebugEnabled()) {
                logger.debug(identifier + ":: Exited successfully from System.exit(): " + command
                        + "(null, null, " + maskedargsList + ")");
            }
        } finally {
            System.setSecurityManager(sm);
            System.setOut(originalOut);
            System.setErr(originalErr);
        }

    } catch (Exception e) {
        if (resolveExecCommandLineError(prefix, e.getMessage().toString(), vcsIgnoreMessages)) {
            ApplicationException applicationException = new ApplicationException(
                    "ExportCommand execution returned an error=" + e.getMessage().toString());
            if (logger.isErrorEnabled()) {
                logger.error(applicationException);
            }
            throw applicationException;
        }
    }
}

From source file:org.springframework.beans.factory.support.DisposableBeanAdapter.java

@Nullable
private Method determineDestroyMethod(String name) {
    try {/*from w  w w .  j a  v a2  s .co  m*/
        if (System.getSecurityManager() != null) {
            return AccessController.doPrivileged((PrivilegedAction<Method>) () -> findDestroyMethod(name));
        } else {
            return findDestroyMethod(name);
        }
    } catch (IllegalArgumentException ex) {
        throw new BeanDefinitionValidationException("Could not find unique destroy method on bean with name '"
                + this.beanName + ": " + ex.getMessage());
    }
}

From source file:org.apache.catalina.core.ApplicationContextFacade.java

public void setAttribute(String name, Object object) {
    if (System.getSecurityManager() != null) {
        doPrivileged("setAttribute", new Object[] { name, object });
    } else {/*from   w  w w. j a  v  a 2  s.  c  o  m*/
        context.setAttribute(name, object);
    }
}

From source file:org.apache.catalina.core.ApplicationDispatcher.java

/**
 * Forward this request and response to another resource for processing.
 * Any runtime exception, IOException, or ServletException thrown by the
 * called servlet will be propogated to the caller.
 *
 * @param request The servlet request to be forwarded
 * @param response The servlet response to be forwarded
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet exception occurs
 *//*from w w w .  ja v  a 2 s.com*/
public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    if (System.getSecurityManager() != null) {
        try {
            PrivilegedForward dp = new PrivilegedForward(request, response);
            AccessController.doPrivileged(dp);
        } catch (PrivilegedActionException pe) {
            Exception e = pe.getException();
            if (e instanceof ServletException)
                throw (ServletException) e;
            throw (IOException) e;
        }
    } else {
        doForward(request, response);
    }
}

From source file:com.alertlogic.aws.kinesis.test1.kcl.CountingRecordProcessorTest.java

/**
 * A test helper to prevent calls to System.exit() from existing our JVM. We need to test failure behavior and want
 * to know if System.exit() was called.//from   w w w. ja  v a 2  s. c o  m
 *
 * @param testBlock A code block that is expected to call System.exit().
 */
private void expectSystemExitWhenExecuting(Callable<Void> testBlock) throws Exception {
    final SecurityException expectedPreventionOfSystemExit = new SecurityException(
            "System.exit not allowed for this test.");
    // Disable System.exit() for this test
    final SecurityManager sm = new SecurityManager() {
        @Override
        public void checkExit(int status) {
            throw expectedPreventionOfSystemExit;
        }

        @Override
        public void checkPermission(Permission perm) {
            // Do nothing, allowing this security manager to be replaced
        }
    };
    SecurityManager oldSm = System.getSecurityManager();
    System.setSecurityManager(sm);
    boolean systemExitCalled = false;
    try {
        testBlock.call();
        fail("Expected System.exit to be called and throw a SecurityException by our test SecurityManager");
    } catch (SecurityException ex) {
        assertEquals("Expected SecurityException to be thrown when System.exit called",
                expectedPreventionOfSystemExit, ex);
        systemExitCalled = true;
    } finally {
        System.setSecurityManager(oldSm);
    }
    assertTrue("Expected test to call System.exit", systemExitCalled);
}

From source file:org.apache.jk.server.JkCoyoteHandler.java

private void appendHead(org.apache.coyote.Response res) throws IOException {
    if (log.isDebugEnabled())
        log.debug("COMMIT sending headers " + res + " " + res.getMimeHeaders());

    C2BConverter c2b = (C2BConverter) res.getNote(utfC2bNote);
    if (c2b == null) {
        if (System.getSecurityManager() != null) {
            try {
                c2b = (C2BConverter) AccessController.doPrivileged(new PrivilegedExceptionAction() {
                    public Object run() throws IOException {
                        return new C2BConverter("UTF8");
                    }/*from  ww  w. j  a v  a2s.  c o m*/
                });
            } catch (PrivilegedActionException pae) {
                Exception ex = pae.getException();
                if (ex instanceof IOException)
                    throw (IOException) ex;
            }
        } else {
            c2b = new C2BConverter("UTF8");
        }
        res.setNote(utfC2bNote, c2b);
    }

    MsgContext ep = (MsgContext) res.getNote(epNote);
    MsgAjp msg = (MsgAjp) ep.getNote(headersMsgNote);
    msg.reset();
    msg.appendByte(HandlerRequest.JK_AJP13_SEND_HEADERS);
    msg.appendInt(res.getStatus());

    MessageBytes mb = (MessageBytes) ep.getNote(tmpMessageBytesNote);
    if (mb == null) {
        mb = new MessageBytes();
        ep.setNote(tmpMessageBytesNote, mb);
    }
    String message = res.getMessage();
    if (message == null) {
        if (System.getSecurityManager() != null) {
            message = (String) AccessController.doPrivileged(new StatusLinePrivilegedAction(res.getStatus()));
        } else {
            message = HttpMessages.getMessage(res.getStatus());
        }
    } else {
        message = message.replace('\n', ' ').replace('\r', ' ');
    }
    mb.setString(message);
    c2b.convert(mb);
    msg.appendBytes(mb);

    // XXX add headers

    MimeHeaders headers = res.getMimeHeaders();
    String contentType = res.getContentType();
    if (contentType != null) {
        headers.setValue("Content-Type").setString(contentType);
    }
    String contentLanguage = res.getContentLanguage();
    if (contentLanguage != null) {
        headers.setValue("Content-Language").setString(contentLanguage);
    }
    int contentLength = res.getContentLength();
    if (contentLength >= 0) {
        headers.setValue("Content-Length").setInt(contentLength);
    }
    int numHeaders = headers.size();
    msg.appendInt(numHeaders);
    for (int i = 0; i < numHeaders; i++) {
        MessageBytes hN = headers.getName(i);
        // no header to sc conversion - there's little benefit
        // on this direction
        c2b.convert(hN);
        msg.appendBytes(hN);

        MessageBytes hV = headers.getValue(i);
        c2b.convert(hV);
        msg.appendBytes(hV);
    }
    ep.setType(JkHandler.HANDLE_SEND_PACKET);
    ep.getSource().invoke(msg, ep);
}

From source file:org.codehaus.mojo.antlr.AbstractAntlrMojo.java

protected void performGeneration(GenerationPlan plan, Artifact antlrArtifact) throws MojoExecutionException {
    if (!plan.getGenerationDirectory().getParentFile().exists()) {
        plan.getGenerationDirectory().getParentFile().mkdirs();
    }/*from   w ww  .j  a va  2 s .  c o m*/

    // ----------------------------------------------------------------------
    // Wrap arguments
    // Note: grammar file should be last
    // ----------------------------------------------------------------------

    List arguments = new LinkedList();
    addArgIf(arguments, debug, "-debug");
    addArgIf(arguments, diagnostic, "-diagnostic");
    addArgIf(arguments, trace, "-trace");
    addArgIf(arguments, traceParser, "-traceParser");
    addArgIf(arguments, traceLexer, "-traceLexer");
    addArgIf(arguments, traceTreeParser, "-traceTreeParser");

    addArgs(arguments);

    arguments.add("-o");
    arguments.add(plan.getGenerationDirectory().getPath());

    if (plan.getCollectedSuperGrammarIds().size() > 0) {
        arguments.add("-glib");
        StringBuffer buffer = new StringBuffer();
        Iterator ids = plan.getCollectedSuperGrammarIds().iterator();
        while (ids.hasNext()) {
            buffer.append(new File(sourceDirectory, (String) ids.next()));
            if (ids.hasNext()) {
                buffer.append(';');
            }
        }
        arguments.add(buffer.toString());
    }

    arguments.add(plan.getSource().getPath());

    String[] args = (String[]) arguments.toArray(new String[arguments.size()]);

    if (plan.getImportVocabTokenTypesDirectory() != null
            && !plan.getImportVocabTokenTypesDirectory().equals(plan.getGenerationDirectory())) {
        // we need to spawn a new process to properly set up PWD
        CommandLine commandLine = new CommandLine("java");
        commandLine.addArgument("-classpath", false);
        commandLine.addArgument(generateClasspathForProcessSpawning(antlrArtifact), true);
        commandLine.addArgument("antlr.Tool", false);
        commandLine.addArguments(args, true);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setWorkingDirectory(plan.getImportVocabTokenTypesDirectory());
        try {
            executor.execute(commandLine);
        } catch (IOException e) {
            getLog().warn("Error spawning process to execute antlr tool : " + e.getMessage());
        }

        return;
    }

    // ----------------------------------------------------------------------
    // Call Antlr
    // ----------------------------------------------------------------------

    if (getLog().isDebugEnabled()) {
        getLog().debug("antlr args=\n" + StringUtils.join(args, "\n"));
    }

    boolean failedSetManager = false;
    SecurityManager oldSm = null;
    try {
        oldSm = System.getSecurityManager();
        System.setSecurityManager(NoExitSecurityManager.INSTANCE);
    } catch (SecurityException ex) {
        // ANTLR-12
        oldSm = null;
        failedSetManager = true;
        // ignore, in embedded environment the security manager can already be set.
        // in such a case assume the exit call is handled properly..
        getLog().warn("Cannot set custom SecurityManager. "
                + "Antlr's call to System.exit() can cause application shutdown "
                + "if not handled by the current SecurityManager.");
    }

    String originalUserDir = null;
    if (plan.getImportVocabTokenTypesDirectory() != null) {
        originalUserDir = System.getProperty("user.dir");
        System.setProperty("user.dir", plan.getImportVocabTokenTypesDirectory().getPath());
    }

    PrintStream oldErr = System.err;

    OutputStream errOS = new StringOutputStream();
    PrintStream err = new PrintStream(errOS);
    System.setErr(err);

    try {
        executeAntlrInIsolatedClassLoader((String[]) arguments.toArray(new String[0]), antlrArtifact);
    } catch (SecurityException e) {
        if (e.getMessage().equals("exitVM-0")
                || e.getClass().getName().equals("org.netbeans.core.execution.ExitSecurityException")) // netbeans
                                                                                                                                             // IDE Sec
                                                                                                                                             // Manager.
        {
            // ANTLR-12
            // now basically every secutiry manager could set different message, how to handle in generic way?
            // probably only by external execution
            // / in case of NetBeans SecurityManager, it's not possible to distinguish exit codes, rather swallow
            // than fail.
            getLog().debug(e);
        } else {
            throw new MojoExecutionException(
                    "Antlr execution failed: " + e.getMessage() + "\n Error output:\n" + errOS, e);
        }
    } finally {
        if (originalUserDir != null) {
            System.setProperty("user.dir", originalUserDir);
        }
        if (!failedSetManager) {
            System.setSecurityManager(oldSm);
        }
        System.setErr(oldErr);
        System.err.println(errOS.toString());
    }
}

From source file:org.apache.catalina.core.ApplicationContextFacade.java

public void removeAttribute(String name) {
    if (System.getSecurityManager() != null) {
        doPrivileged("removeAttribute", new Object[] { name });
    } else {/*w  ww  .j a  va  2 s  .  co  m*/
        context.removeAttribute(name);
    }
}

From source file:com.sshtools.j2ssh.forwarding.ForwardingClient.java

/**
 *
 *
 * @param uniqueName//w  ww. j a va2 s  .c  o m
 * @param addressToBind
 * @param portToBind
 * @param hostToConnect
 * @param portToConnect
 *
 * @return
 *
 * @throws ForwardingConfigurationException
 */
public ForwardingConfiguration addLocalForwarding(String uniqueName, String addressToBind, int portToBind,
        String hostToConnect, int portToConnect) throws ForwardingConfigurationException {
    // Check that the name does not exist
    if (localForwardings.containsKey(uniqueName)) {
        throw new ForwardingConfigurationException("The configuration name already exists!");
    }

    // Check that the address to bind and port are not already being used
    Iterator it = localForwardings.values().iterator();
    ForwardingConfiguration config;

    while (it.hasNext()) {
        config = (ForwardingConfiguration) it.next();

        if (config.getAddressToBind().equals(addressToBind) && (config.getPortToBind() == portToBind)) {
            throw new ForwardingConfigurationException("The address and port are already in use");
        }
    }

    // Check the security mananger
    SecurityManager manager = System.getSecurityManager();

    if (manager != null) {
        try {
            manager.checkPermission(
                    new SocketPermission(addressToBind + ":" + String.valueOf(portToBind), "accept,listen"));
        } catch (SecurityException e) {
            throw new ForwardingConfigurationException("The security manager has denied listen permision on "
                    + addressToBind + ":" + String.valueOf(portToBind));
        }
    }

    // Create the configuration object
    ForwardingConfiguration cf = new ClientForwardingListener(uniqueName, connection, addressToBind, portToBind,
            hostToConnect, portToConnect);

    localForwardings.put(uniqueName, cf);

    return cf;
}

From source file:org.apache.cxf.common.logging.LogUtils.java

private static ClassLoader getClassLoader(final Class<?> clazz) {
    final SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
            public ClassLoader run() {
                return clazz.getClassLoader();
            }//  www.j  a va  2 s  . c  o  m
        });
    }
    return clazz.getClassLoader();
}