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.izforge.izpack.event.AntAction.java

/**
 * Performs all defined actions./*from w ww .ja va 2s .  c  om*/
 *
 * @param uninstall An install/uninstall switch. If this is <tt>true</tt> only the uninstall
 *                  actions, otherwise only the install actions are being performed.
 * @throws IzPackException for any error
 * @see #performInstallAction() for calling all install actions.
 * @see #performUninstallAction() for calling all uninstall actions.
 */
public void performAction(boolean uninstall) throws IzPackException {
    if (verbose) {
        System.out.print("Calling ANT with buildfile: " + buildFile);
        System.out.print(buildDir != null ? " in directory " + buildDir : " in default base directory");
        System.out.println();
    }
    SecurityManager oldsm = null;
    if (!JavaEnvUtils.isJavaVersion("1.0") && !JavaEnvUtils.isJavaVersion("1.1")) {
        oldsm = System.getSecurityManager();
    }
    PrintStream err = System.err;
    PrintStream out = System.out;
    Project antProj = new Project();
    try {
        antProj.setInputHandler(new AntActionInputHandler());
        antProj.setName("antcallproject");
        if (verbose) {
            logLevel = AntLogLevel.VERBOSE;
        } else if (quiet) {
            logLevel = AntLogLevel.WARNING;
        }
        final int antLogLevel = logLevel.getLevel();
        antProj.addBuildListener(new AntSystemLogBuildListener(antLogLevel));
        if (logFile != null) {
            antProj.addBuildListener(new AntActionLogBuildListener(logFile, logFileAppend, antLogLevel));
        }
        antProj.setSystemProperties();
        addProperties(antProj, getProperties());
        addPropertiesFromPropertyFiles(antProj);
        // TODO: propertyfiles, logFile
        antProj.fireBuildStarted();
        antProj.init();
        List<Ant> antcalls = new ArrayList<Ant>();
        List<String> choosenTargets = (uninstall) ? uninstallTargets : targets;
        if (choosenTargets.size() > 0) {
            Ant antcall;
            for (String choosenTarget : choosenTargets) {
                antcall = (Ant) antProj.createTask("ant");
                if (buildDir != null) {
                    antcall.setDir(buildDir);
                }
                antcall.setAntfile(buildFile.getAbsolutePath());
                antcall.setTarget(choosenTarget);
                antcalls.add(antcall);
            }
        }
        Target target = new Target();
        target.setName("calltarget");

        for (Ant antcall : antcalls) {
            target.addTask(antcall);
        }
        antProj.addTarget(target);
        System.setOut(new PrintStream(new DemuxOutputStream(antProj, false)));
        System.setErr(new PrintStream(new DemuxOutputStream(antProj, true)));
        antProj.executeTarget("calltarget");
        antProj.fireBuildFinished(null);
    } catch (BuildException exception) {
        antProj.fireBuildFinished(exception);
        throw new IzPackException("Ant build failed", exception, getSeverity());
    } finally {
        if (oldsm != null) {
            System.setSecurityManager(oldsm);
        }
        System.setOut(out);
        System.setErr(err);
    }
}

From source file:org.firstopen.singularity.admin.view.ECSpecBean.java

public ECSpecBean(String name) {

    try {/*from  ww w.  ja  v  a2 s  .c o m*/
        if (System.getSecurityManager() == null) {

            System.setSecurityManager(new SecurityManager());
        }

        InitialContext jndiContext = JNDIUtil.getInitialContext();
        Object objref = jndiContext.lookup("jnp://localhost:1099/ejb/ale/AleSLSB");
        AleSLSBHome aleSLSBHome = (AleSLSBHome) PortableRemoteObject.narrow(objref, AleSLSBHome.class);

        aSLSB = aleSLSBHome.create();

        createLogicalDeviceSelectList();

        createECSpecSelectList();

    } catch (Exception e) {
        log.error("can't create ECSpecBean");
        /*
         * can't recover wrap in RuntimeException
         */
        throw new InfrastructureException(e);
    }
}

From source file:org.beangle.model.persist.hibernate.internal.ClassUtils.java

public static ClassLoader getFwkClassLoader() {
    if (System.getSecurityManager() != null) {
        return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
            public ClassLoader run() {
                return Bundle.class.getClassLoader();
            }/*from w  ww . jav  a 2  s.c o m*/
        });
    } else {
        return Bundle.class.getClassLoader();
    }
}

From source file:com.liferay.arquillian.maven.internal.tasks.ExecuteDeployerTask.java

protected void executeTool(String deployerClassName, 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() {

        @Override/*  www .j  ava  2 s  . c om*/
        public void checkPermission(Permission permission) {
            //It is not needed to check permissions
        }

        @Override
        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(deployerClassName);

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

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

        System.setSecurityManager(currentSecurityManager);
    }
}

From source file:org.eclipse.gemini.blueprint.test.AbstractDependencyManagerTests.java

private String readProperty(final String name) {
    if (System.getSecurityManager() != null) {
        return (String) AccessController.doPrivileged(new PrivilegedAction() {

            public Object run() {
                return System.getProperty(name);
            }/*www .ja v a2  s .  c  o  m*/
        });
    } else
        return System.getProperty(name);
}

From source file:org.elasticsearch.hadoop.script.GroovyScriptEngineService.java

public GroovyScriptEngineService(Settings settings) {
    super(settings);

    deprecationLogger.deprecated("[groovy] scripts are deprecated, use [painless] scripts instead");

    // Creates the classloader here in order to isolate Groovy-land code
    final SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new SpecialPermission());
    }/*from w  w w .  ja  v  a  2  s  .  c  om*/
    this.loader = AccessController.doPrivileged((PrivilegedAction<ClassLoader>) () -> {
        // snapshot our context (which has permissions for classes), since the script has none
        AccessControlContext context = AccessController.getContext();
        return new ClassLoader(getClass().getClassLoader()) {
            @Override
            protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
                if (sm != null) {
                    try {
                        context.checkPermission(new ClassPermission(name));
                    } catch (SecurityException e) {
                        throw new ClassNotFoundException(name, e);
                    }
                }
                return super.loadClass(name, resolve);
            }
        };
    });
}

From source file:com.petalmd.armor.service.ArmorService.java

@Inject
public ArmorService(final Settings settings, final RestController restController, final Client client,
        final Authorizator authorizator, final AuthenticationBackend authenticationBackend,
        final HTTPAuthenticator httpAuthenticator, final SessionStore sessionStore,
        final AuditListener auditListener, final SearchService searchService) {
    super(settings);
    this.restController = restController;
    this.client = client;
    this.settings = settings;
    //securityConfigurationIndex = settings
    //        .get(ConfigConstants.ARMOR_CONFIG_INDEX_NAME, ConfigConstants.DEFAULT_SECURITY_CONFIG_INDEX);
    this.authenticationBackend = authenticationBackend;
    this.authorizator = authorizator;
    this.httpAuthenticator = httpAuthenticator;
    this.sessionStore = sessionStore;

    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new SpecialPermission());
    }/*from   w  w w .  jav  a 2s  . c  o m*/

    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction<Boolean>() {
            @Override
            public Boolean run() throws Exception {
                method = RestController.class.getDeclaredMethod("getHandler", RestRequest.class);
                method.setAccessible(true);

                return true;
            }
        });
    } catch (final Exception e) {
        log.error(e.toString(), e);
        throw new ElasticsearchException(e.toString());
    }

    final String keyPath = settings.get(ConfigConstants.ARMOR_KEY_PATH, ".");
    //        AccessController.checkPermission(new FilePermission(keyPath+File.separator+"armor_node_key.key", "write"));
    SecretKey sc = null;
    try {
        sc = AccessController.doPrivileged(new PrivilegedExceptionAction<SecretKey>() {
            @Override
            public SecretKey run() throws Exception {
                final File keyFile = new File(keyPath, "armor_node_key.key");
                SecretKey sc = null;
                if (keyFile.exists()) {
                    log.debug("Loaded key from {}", keyFile.getAbsolutePath());
                    sc = new SecretKeySpec(FileUtils.readFileToByteArray(keyFile), "AES");
                } else {
                    final SecureRandom secRandom = SecureRandom.getInstance("SHA1PRNG");
                    final KeyGenerator kg = KeyGenerator.getInstance("AES");
                    kg.init(128, secRandom);
                    final SecretKey secretKey = kg.generateKey();
                    final byte[] enckey = secretKey.getEncoded();

                    if (enckey == null || enckey.length != 16) {
                        throw new Exception("invalid key " + (enckey == null ? -1 : enckey.length));
                    }
                    FileUtils.writeByteArrayToFile(keyFile, enckey);
                    sc = secretKey;
                    log.info("New key written to {}, make sure all nodes have this key",
                            keyFile.getAbsolutePath());
                }
                return sc;
            }
        });
    } catch (final Exception e) {
        log.error("Cannot generate or read secrety key", e);
        throw new ElasticsearchException(e.toString());
    }

    this.auditListener = auditListener;
    //TODO FUTURE index change audit trail

    final boolean checkForRoot = settings.getAsBoolean(ConfigConstants.ARMOR_CHECK_FOR_ROOT, true);

    if (SecurityUtil.isRootUser()) {

        if (checkForRoot) {
            throw new ElasticsearchException(
                    "You're trying to run elasticsearch as root or Windows Administrator and thats forbidden.");
        } else {
            log.warn(
                    "You're trying to run elasticsearch as root or Windows Administrator! Thats a potential security issue.");
        }

    }

    /*final String scriptingStatus = settings.get(ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING,
        ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT);
            
    if (scriptingStatus.equalsIgnoreCase(ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT)) {
    log.warn("{} has the default value {}, consider setting it to false if not needed",
            ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING, scriptingStatus);
    }
            
    if (scriptingStatus.equalsIgnoreCase("true")) {
    log.error("{} is configured insecure, consider setting it to false or " + ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT,
            ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING);
    }*/
    if (searchService == null) {
        throw new RuntimeException("ssnull");
    }

    ArmorService.secretKey = sc;
}

From source file:org.apache.jasper.runtime.JspFactoryImpl.java

public void releasePageContext(PageContext pc) {
    if (pc == null)
        return;//ww  w.  j a v  a 2 s  .  c  o m
    if (System.getSecurityManager() != null) {
        PrivilegedReleasePageContext dp = new PrivilegedReleasePageContext((JspFactoryImpl) this, pc);
        AccessController.doPrivileged(dp);
    } else {
        internalReleasePageContext(pc);
    }
}

From source file:org.eclipse.gemini.blueprint.blueprint.container.support.BlueprintContainerServicePublisher.java

private void registerService(ApplicationContext applicationContext) {
    final Dictionary<String, Object> serviceProperties = new Hashtable<String, Object>();

    Bundle bundle = bundleContext.getBundle();
    String symName = bundle.getSymbolicName();
    serviceProperties.put(Constants.BUNDLE_SYMBOLICNAME, symName);
    serviceProperties.put(BLUEPRINT_SYMNAME, symName);

    Version version = OsgiBundleUtils.getBundleVersion(bundle);
    serviceProperties.put(Constants.BUNDLE_VERSION, version);
    serviceProperties.put(BLUEPRINT_VERSION, version);

    log.info("Publishing BlueprintContainer as OSGi service with properties " + serviceProperties);

    // export just the interface
    final String[] serviceNames = new String[] { BlueprintContainer.class.getName() };

    if (log.isDebugEnabled())
        log.debug("Publishing service under classes " + ObjectUtils.nullSafeToString(serviceNames));

    AccessControlContext acc = SecurityUtils.getAccFrom(applicationContext);

    // publish service
    if (System.getSecurityManager() != null) {
        registration = AccessController.doPrivileged(new PrivilegedAction<ServiceRegistration>() {
            public ServiceRegistration run() {
                return bundleContext.registerService(serviceNames, blueprintContainer, serviceProperties);
            }//from  ww  w.j av  a2 s. c o  m
        }, acc);
    } else {
        registration = bundleContext.registerService(serviceNames, blueprintContainer, serviceProperties);
    }
}

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

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