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.apache.catalina.core.ApplicationContextFacade.java

public String getMimeType(String file) {
    if (System.getSecurityManager() != null) {
        return (String) doPrivileged("getMimeType", new Object[] { file });
    } else {// ww w .  j a v a2s .c om
        return context.getMimeType(file);
    }
}

From source file:org.apache.hadoop.hbase.mapreduce.TestRowCounter.java

/**
 * test main method. Import should print help and call System.exit
 *///  w w w  .  j a  v  a 2 s. c  o  m
@Test
public void testImportMain() throws Exception {
    PrintStream oldPrintStream = System.err;
    SecurityManager SECURITY_MANAGER = System.getSecurityManager();
    LauncherSecurityManager newSecurityManager = new LauncherSecurityManager();
    System.setSecurityManager(newSecurityManager);
    ByteArrayOutputStream data = new ByteArrayOutputStream();
    String[] args = {};
    System.setErr(new PrintStream(data));
    try {
        System.setErr(new PrintStream(data));

        try {
            RowCounter.main(args);
            fail("should be SecurityException");
        } catch (SecurityException e) {
            assertEquals(-1, newSecurityManager.getExitCode());
            assertTrue(data.toString().contains("Wrong number of parameters:"));
            assertTrue(data.toString()
                    .contains("Usage: RowCounter [options] <tablename> [--range=[startKey],[endKey]] "
                            + "[<column1> <column2>...]"));
            assertTrue(data.toString().contains("-Dhbase.client.scanner.caching=100"));
            assertTrue(data.toString().contains("-Dmapreduce.map.speculative=false"));
        }
        data.reset();
        try {
            args = new String[2];
            args[0] = "table";
            args[1] = "--range=1";
            RowCounter.main(args);
            fail("should be SecurityException");
        } catch (SecurityException e) {
            assertEquals(-1, newSecurityManager.getExitCode());
            assertTrue(data.toString().contains(
                    "Please specify range in such format as \"--range=a,b\" or, with only one boundary,"
                            + " \"--range=,b\" or \"--range=a,\""));
            assertTrue(data.toString()
                    .contains("Usage: RowCounter [options] <tablename> [--range=[startKey],[endKey]] "
                            + "[<column1> <column2>...]"));
        }

    } finally {
        System.setErr(oldPrintStream);
        System.setSecurityManager(SECURITY_MANAGER);
    }

}

From source file:sorcer.launcher.SorcerLauncher.java

public static void installSecurityManager() {
    if (System.getSecurityManager() == null)
        System.setSecurityManager(new SecurityManager()/*{
                                                       @Override
                                                       public void checkPermission(Permission perm) {
                                                       String name = perm.getName();
                                                       if (name.startsWith("exitVM") && !(hasCaller(ExitingCallback.class) || hasCaller("sorcer.launcher.Sorcer")))
                                                       throw new SecurityException("Exit forbidden");
                                                       }
                                                               
                                                       private boolean hasCaller(Class type){
                                                       return hasCaller(type.getName());
                                                       }
                                                               
                                                       private boolean hasCaller(String type){
                                                       for (Class caller : getClassContext()) {
                                                       if(type.equals(caller.getName()))
                                                       return true;
                                                       }
                                                       return false;
                                                       }
                                                       }*/);
}

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

public Set getResourcePaths(String path) {
    if (System.getSecurityManager() != null) {
        return (Set) doPrivileged("getResourcePaths", new Object[] { path });
    } else {/*from   ww w .j  a  va2 s .co  m*/
        return context.getResourcePaths(path);
    }
}

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

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

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

/**
 * This method is a copy of the implementation of
 * {@link WrapperManagerMBean#getWrapperPID()} 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 Wrapper process.
 * @see <a href="http://www.mulesoft.org/jira/browse/MULE-5106">MULE-5106</a>
 *//*  w  ww  . j a  v  a2s. c om*/
public static int getWrapperPID() {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new WrapperPermission("getWrapperPID"));
    }

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

From source file:catalina.startup.CatalinaService.java

/**
 * Start a new server instance./*from  ww w  .  j a va2  s . c  o  m*/
 */
public void load() {

    // Create and execute our Digester
    Digester digester = createStartDigester();
    File file = configFile();
    try {
        digester.push(this);
        digester.parse(file);
    } catch (Exception e) {
        System.out.println("Catalina.start: " + e);
        e.printStackTrace(System.out);
        System.exit(1);
    }

    // Setting additional variables
    if (!useNaming) {
        System.setProperty("catalina.useNaming", "false");
    } else {
        System.setProperty("catalina.useNaming", "true");
        String value = "org.apache.naming";
        String oldValue = System.getProperty(javax.naming.Context.URL_PKG_PREFIXES);
        if (oldValue != null) {
            value = value + ":" + oldValue;
        }
        System.setProperty(javax.naming.Context.URL_PKG_PREFIXES, value);
        System.setProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY,
                "org.apache.naming.java.javaURLContextFactory");
    }

    // If a SecurityManager is being used, set properties for
    // checkPackageAccess() and checkPackageDefinition
    if (System.getSecurityManager() != null) {
        String access = Security.getProperty("package.access");
        if (access != null && access.length() > 0)
            access += ",";
        else
            access = "sun.,";
        Security.setProperty("package.access", access + "org.apache.catalina.,org.apache.jasper.");
        String definition = Security.getProperty("package.definition");
        if (definition != null && definition.length() > 0)
            definition += ",";
        else
            definition = "sun.,";
        Security.setProperty("package.definition",
                // FIX ME package "javax." was removed to prevent HotSpot
                // fatal internal errors
                definition + "java.,org.apache.catalina.,org.apache.jasper.");
    }

    // Start the new server
    if (server instanceof Lifecycle) {
        try {
            server.initialize();
        } catch (LifecycleException e) {
            System.out.println("Catalina.start: " + e);
            e.printStackTrace(System.out);
            if (e.getThrowable() != null) {
                System.out.println("----- Root Cause -----");
                e.getThrowable().printStackTrace(System.out);
            }
        }
    }

}

From source file:com.cisco.dvbu.ps.deploytool.dao.wsapi.VCSWSDAOImpl.java

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

    String identifier = "VCSWSDAOImpl.vcsImportCommand"; // some unique identifier that characterizes this invocation.
    String actionName = "IMPORT";

    try {//from ww  w.j  a va2  s . c o  m
        boolean preserveQuotes = false;
        boolean initArgsList = true;
        List<String> argsList = new ArrayList<String>();

        // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation.
        //   If so then force a no operation to happen by performing a -printcontents for pkg_import
        // mtinius-2016-04-14: commented out until a full analysis can be done.
        //if (CommonUtils.isExecOperation() && !arguments.toLowerCase().contains("-printcontents")) 
        //   arguments = arguments + " -printcontents";

        // Parse the arguments
        argsList = CommonUtils.parseArguments(argsList, initArgsList, arguments, preserveQuotes, propertyFile);
        String[] args = argsList.toArray(new String[0]);

        /*
         * 2014-02-14 (mtinius): Removed the PDTool Archive capability
         */
        //         ImportCommand.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, vcsIngoreMessages, 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 = "ImportCommand.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(ImportCommand.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 import command.
                ImportCommand.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(
                    "ImportCommand execution returned an error=" + e.getMessage().toString());
            if (logger.isErrorEnabled()) {
                logger.error(applicationException);
            }
            throw applicationException;
        }
    }
}

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

public URL getResource(String path) throws MalformedURLException {
    if (System.getSecurityManager() != null) {
        try {/*from w ww  .ja  va  2 s .  com*/
            return (URL) invokeMethod(context, "getResource", new Object[] { path });
        } catch (Throwable t) {
            if (t instanceof MalformedURLException) {
                throw (MalformedURLException) t;
            }
            return null;
        }
    } else {
        return context.getResource(path);
    }
}

From source file:net.pms.util.BasicThreadFactory.java

/**
 * Creates a new {@link BasicThreadFactory} using the given arguments.
 * <p>//from www  .  j a  va2  s . c om
 * The {@link Thread} names generated by the new {@link BasicThreadFactory}
 * is created by calling {@link String#format} with {@code namePattern} as
 * the "format" and pool- and thread number as arguments. The formatting
 * rules are those of {@link java.util.Formatter}.
 * <p>
 * No more than two variables of type {@code %d} or {@code %s} is allowed in
 * {@code namePattern}, and they will be substituted as follows:
 * <ul>
 * <li>No variables: All {@link Thread} names generated by this
 * {@link ThreadFactory} will be equal to {@code namePattern}.</li>
 * <li>One variable: Only thread number will be used, pool number isn't
 * used.</li>
 * <li>Two variables: Pool number will be used for the first variable in
 * {@code namePattern}, thread number for the second.
 * </ul>
 *
 * @param namePattern The {@link java.util.Formatter} formatted
 *            {@link String} from which to generate {@link Thread} names.
 * @param threadPriority The {@link Thread} priority.
 * @param group The {@link ThreadGroup}.
 */
public BasicThreadFactory(String namePattern, int threadPriority, ThreadGroup group) {
    if (isBlank(namePattern)) {
        throw new IllegalArgumentException("namePattern cannot be blank");
    }
    if (group == null) {
        SecurityManager securityManager = System.getSecurityManager();
        group = (securityManager != null) ? securityManager.getThreadGroup()
                : Thread.currentThread().getThreadGroup();
    }
    this.group = group;
    this.threadPriority = Math.min(Thread.MAX_PRIORITY, Math.max(Thread.MIN_PRIORITY, threadPriority));
    int pctSes = 0;
    int pctDs = 0;
    int i = 0;
    while (true) {
        i = namePattern.indexOf("%s", i);
        if (i >= 0) {
            pctSes++;
            i++;
        } else {
            break;
        }
    }
    while (true) {
        i = namePattern.indexOf("%d", i);
        if (i >= 0) {
            pctDs++;
            i++;
        } else {
            break;
        }
    }
    if (pctSes + pctDs > 2) {
        throw new IllegalArgumentException("namePattern can't have more than 2 variables");
    }
    this.numVariables = pctSes + pctDs;
    this.namePattern = namePattern;
    if (numVariables == 2) {
        this.instancePoolNumber = POOL_NUMBER.getAndIncrement();
    } else {
        this.instancePoolNumber = 0;
    }
}