Example usage for java.lang SecurityManager SecurityManager

List of usage examples for java.lang SecurityManager SecurityManager

Introduction

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

Prototype

public SecurityManager() 

Source Link

Document

Constructs a new SecurityManager.

Usage

From source file:com.linkedin.pinot.common.utils.KafkaStarterUtils.java

private static void invokeTopicCommand(String[] args) {
    // jfim: Use Java security to trap System.exit in Kafka 0.9's TopicCommand
    System.setSecurityManager(new SecurityManager() {
        @Override//  ww  w  .  ja v  a2s.co  m
        public void checkPermission(Permission perm) {
            if (perm.getName().startsWith("exitVM")) {
                throw new SecurityException("System.exit is disabled");
            }
        }

        @Override
        public void checkPermission(Permission perm, Object context) {
            checkPermission(perm);
        }
    });

    try {
        TopicCommand.main(args);
    } catch (SecurityException ex) {
        // Do nothing, this is caused by our security manager that disables System.exit
    }

    System.setSecurityManager(null);
}

From source file:com.ideabase.repository.core.service.UserServiceImpl.java

/**
 * {@inheritDoc}//from ww  w .  ja  va2s  .c  o m
 */
public boolean isAllowed(final Subject pSubject, final Permission pPermission) {
    final SecurityManager securityManager;
    if (System.getSecurityManager() == null) {
        mLog.debug("No predefined security manager found.");
        securityManager = new SecurityManager();
    } else {
        securityManager = System.getSecurityManager();
    }

    try {
        mLog.debug("Do as privileged action.");
        Subject.doAsPrivileged(pSubject, new PrivilegedAction() {
            public Object run() {
                securityManager.checkPermission(pPermission);
                return null;
            }
        }, null);
        mLog.debug("user action is previleged.");
        return true;
    } catch (RuntimeException e) {
        // No logging here, because, if exception raised it refers to permission
        // failure.
        mLog.warn("Exception raised during verifying the authorization", e);
        return false;
    }
}

From source file:sernet.gs.ui.rcp.main.logging.LoggerInitializer.java

private SecurityManager getSecurityManager() {
    SecurityManager security = System.getSecurityManager();
    new SecurityManager();
    if (security == null) {
        security = new SecurityManager();
    }/* w ww .j  a  v a2  s.  co  m*/

    return security;
}

From source file:com.liferay.maven.plugins.AbstractLiferayMojo.java

protected void executeTool(String toolClassName, ClassLoader classLoader, String[] args) throws Exception {

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    currentThread.setContextClassLoader(classLoader);

    SecurityManager currentSecurityManager = System.getSecurityManager();

    // Required to prevent premature exit by DBBuilder. See LPS-7524.

    SecurityManager securityManager = new SecurityManager() {

        public void checkPermission(Permission permission) {
        }/*from   w  w w.  j ava 2 s .  c  om*/

        public void checkExit(int status) {
            throw new SecurityException();
        }

    };

    System.setSecurityManager(securityManager);

    try {
        System.setProperty("external-properties",
                "com/liferay/portal/tools/dependencies" + "/portal-tools.properties");
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

        Class<?> clazz = classLoader.loadClass(toolClassName);

        Method method = clazz.getMethod("main", String[].class);

        method.invoke(null, (Object) args);
    } catch (InvocationTargetException ite) {
        if (ite.getCause() instanceof SecurityException) {
        } else {
            throw ite;
        }
    } finally {
        currentThread.setContextClassLoader(contextClassLoader);

        System.clearProperty("org.apache.commons.logging.Log");

        System.setSecurityManager(currentSecurityManager);
    }
}

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.nebulaframework.grid.Grid.java

/**
 * Starts a {@link GridNode} with default settings, read from
 * default properties file./*from   w  w w.  j  a  v  a 2 s .  co m*/
 * 
 * @param useConfigDiscovery indicates whether to use information
 * from configuration to discover
 * 
 * @return GridNode
 * 
 * @throws IllegalStateException if a Grid Member (Cluster / Node) has
 * already started with in the current VM. Nebula supports only one Grid
 * Member per VM.
 */
public synchronized static GridNode startGridNode(boolean useConfigDiscovery) throws IllegalStateException {

    if (isInitialized()) {
        // A Grid Member has already started in this VM
        throw new IllegalStateException("A Grid Memeber Already Started in VM");
    }

    initializeDefaultExceptionHandler();

    StopWatch sw = new StopWatch();

    try {

        sw.start();

        // Set Security Manager
        System.setSecurityManager(new SecurityManager());

        // Detect Configuration
        Properties config = ConfigurationSupport.detectNodeConfiguration();

        log.info("GridNode Attempting Discovery...");

        // Discover Cluster If Needed
        GridNodeDiscoverySupport.discover(config, useConfigDiscovery);

        checkJMSBroker(config.getProperty(ConfigurationKeys.CLUSTER_SERVICE.value()));

        log.debug("Starting up Spring Container...");

        applicationContext = new NebulaApplicationContext(GRIDNODE_CONTEXT, config);

        log.debug("Spring Container Started");

        node = true;

        sw.stop();

        log.info("GridNode Started Up. " + sw.getLastTaskTimeMillis() + " ms");

        return (GridNode) applicationContext.getBean("localNode");
    } finally {
        if (sw.isRunning()) {
            sw.stop();
        }
    }
}

From source file:org.eclipse.wb.internal.core.DesignerPlugin.java

/**
 * We should not allow user code to terminate JVM.
 *//*from w ww  . j  a  v a2s.  c o m*/
public static void installSecurityManager() {
    System.setSecurityManager(new SecurityManager() {
        @Override
        public void checkPermission(java.security.Permission perm) {
            if (isExitVM(perm)) {
                StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
                for (StackTraceElement element : stackTrace) {
                    String className = element.getClassName();
                    String methodName = element.getMethodName();
                    // ignore this class, because it has our class name prefix
                    if (className.equals(getClass().getName())) {
                        continue;
                    }
                    // ignore JFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    if (className.equals("javax.swing.JFrame")
                            && methodName.equals("setDefaultCloseOperation")) {
                        return;
                    }
                    // prevent exit() from user invoked by "designer"
                    if (className.startsWith("org.eclipse.wb.")
                            || className.startsWith("com.google.gdt.eclipse.designer.")
                            || className.startsWith("net.rim.ejde.designer.")
                            || className.startsWith("java.awt.EventQueue")) {
                        // we often use test_exit() method as point to stop tests, allow it
                        if (methodName.startsWith("test_") && methodName.endsWith("_exit")) {
                            return;
                        }
                        // prevent exit()
                        throw new SecurityException("Exit from within user-loaded code");
                    }
                }
            }
        }

        private boolean isExitVM(java.security.Permission perm) {
            return perm instanceof RuntimePermission && StringUtils.startsWith(perm.getName(), "exitVM");
        }
    });
}

From source file:it.unifi.rcl.chess.traceanalysis.Trace.java

private static void forbidSystemExitCall() {
    final SecurityManager securityManager = new SecurityManager() {
        public void checkPermission(Permission permission) {
            if (permission.getName().contains("exitVM")) {
                throw new ExitTrappedException();
            }//w ww  . ja v a2  s.  co  m
        }
    };
    System.setSecurityManager(securityManager);
}

From source file:com.centeractive.ws.builder.soap.XmlUtils.java

/**
 * XmlOptions configuration used in preventing XML Bomb
 * //from  w  w w. j  ava  2  s .  c  o  m
 * @return XmlOptions
 */
public static XmlOptions createDefaultXmlOptions() {
    XmlOptions xmlOptions;

    try {
        SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
        SecurityManager securityManager = new SecurityManager();
        // Default seems to be 64000!
        // TODO
        // securityManager.setEntityExpansionLimit( 16 );

        saxParser.setProperty("http://apache.org/xml/properties/security-manager", securityManager);
        XMLReader xmlReader = saxParser.getXMLReader();
        xmlOptions = new XmlOptions().setLoadUseXMLReader(xmlReader);
    } catch (Exception e) {
        xmlOptions = new XmlOptions();
        log.error("Error creating XmlOptions; " + e.getMessage(), e);
    }
    return xmlOptions;
}

From source file:org.nebulaframework.grid.Grid.java

/**
 * Starts a Light-weight {@link GridNode} (a GridNode without
 * Job Execution Support, that is non-worker) with default
 * settings, read from default properties file.
 * /*  ww w.  j a va 2 s  .c  om*/
 * @param useConfigDiscovery indicates whether to use information
 * from configuration to discover
 * 
 * @param isGui indicates that the application is a GUI based
 * application and any disconnection notifications should be
 * done through message boxes.
 * 
 * @return GridNode
 * 
 * @throws IllegalStateException if a Grid Member (Cluster / Node) has
 * already started with in the current VM. Nebula supports only one Grid
 * Member per VM.
 */
public synchronized static GridNode startLightGridNode(boolean useConfigDiscovery, final boolean isGui)
        throws IllegalStateException {

    if (isInitialized()) {
        // A Grid Member has already started in this VM
        throw new IllegalStateException("A Grid Memeber Already Started in VM");
    }

    initializeDefaultExceptionHandler();

    StopWatch sw = new StopWatch();

    try {
        sw.start();

        // Set Security Manager
        System.setSecurityManager(new SecurityManager());

        Properties config = ConfigurationSupport.detectNodeConfiguration();

        log.info("GridNode Attempting Discovery...");

        // Discover Cluster If Needed
        GridNodeDiscoverySupport.discover(config, useConfigDiscovery);

        checkJMSBroker(config.getProperty(ConfigurationKeys.CLUSTER_SERVICE.value()));

        // If we reach here, connection test succeeded

        log.debug("Starting up Spring Container...");

        applicationContext = new NebulaApplicationContext(GRIDNODE_LIGHT_CONTEXT, config);

        log.debug("Spring Container Started");

        node = true;
        lightweight = true;

        sw.stop();
        log.info("GridNode Started Up. " + sw.getLastTaskTimeMillis() + " ms");

        GridNode node = (GridNode) applicationContext.getBean("localNode");
        ServiceEventsSupport.addServiceHook(new ServiceHookCallback() {

            @Override
            public void onServiceEvent(ServiceMessage message) {

                log.warn("[GridNode] Disconnected from Cluster");
                log.warn("[GridNode] Shutting Down");

                if (isGui) {
                    JOptionPane.showMessageDialog(UISupport.activeWindow(),
                            "Disconnected from Cluster, terminating VM");
                }
                System.exit(0);
            }

        }, node.getClusterId().toString(), ServiceMessageType.NODE_DISCONNECTED);

        return node;

    } finally {
        if (sw.isRunning()) {
            sw.stop();
        }
    }
}