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.freeplane.plugin.script.GenericScript.java

@Override
public Object execute(final NodeModel node) {
    try {//www . ja  v  a  2  s .c o m
        if (errorsInScript != null && compileTimeStrategy.canUseOldCompiledScript()) {
            throw new ExecuteScriptException(errorsInScript.getMessage(), errorsInScript);
        }
        final ScriptingSecurityManager scriptingSecurityManager = createScriptingSecurityManager();
        final ScriptingPermissions originalScriptingPermissions = new ScriptingPermissions(
                ResourceController.getResourceController().getProperties());
        final FreeplaneSecurityManager securityManager = (FreeplaneSecurityManager) System.getSecurityManager();
        final boolean needToSetFinalSecurityManager = securityManager.needToSetFinalSecurityManager();
        final PrintStream oldOut = System.out;
        try {
            final SimpleScriptContext context = createScriptContext(node);
            if (compilationEnabled && engine instanceof Compilable) {
                compileAndCache((Compilable) engine);
                if (needToSetFinalSecurityManager)
                    securityManager.setFinalSecurityManager(scriptingSecurityManager);
                System.setOut(outStream);
                return compiledScript.eval(context);
            } else {
                if (needToSetFinalSecurityManager)
                    securityManager.setFinalSecurityManager(scriptingSecurityManager);
                System.setOut(outStream);
                return engine.eval(scriptSource.getScript(), context);
            }
        } finally {
            System.setOut(oldOut);
            if (needToSetFinalSecurityManager && securityManager.hasFinalSecurityManager())
                securityManager.removeFinalSecurityManager(scriptingSecurityManager);
            /* restore preferences (and assure that the values are unchanged!). */
            originalScriptingPermissions.restorePermissions();
        }
    } catch (final ScriptException e) {
        handleScriptRuntimeException(e);
        // :fixme: This throw is only reached, if handleScriptRuntimeException
        // does not raise an exception. Should it be here at all?
        // And if: Shouldn't it raise an ExecuteScriptException?
        throw new RuntimeException(e);
    } catch (final Throwable e) {
        if (Controller.getCurrentController().getSelection() != null)
            Controller.getCurrentModeController().getMapController().select(node);
        throw new ExecuteScriptException(e.getMessage(), e);
    }
}

From source file:com.ery.estorm.util.Threads.java

/**
 * Returns a {@link java.util.concurrent.ThreadFactory} that names each created thread uniquely, with a common prefix.
 * /*from www .  j  a va 2s .c  o m*/
 * @param prefix
 *            The prefix of every created Thread's name
 * @return a {@link java.util.concurrent.ThreadFactory} that names threads
 */
public static ThreadFactory getNamedThreadFactory(final String prefix) {
    SecurityManager s = System.getSecurityManager();
    final ThreadGroup threadGroup = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();

    return new ThreadFactory() {
        final AtomicInteger threadNumber = new AtomicInteger(1);
        private final int poolNumber = Threads.poolNumber.getAndIncrement();
        final ThreadGroup group = threadGroup;

        @Override
        public Thread newThread(Runnable r) {
            final String name = prefix + "-pool" + poolNumber + "-t" + threadNumber.getAndIncrement();
            return new Thread(group, r, name);
        }
    };
}

From source file:org.apache.bval.util.reflection.Reflection.java

/**
 * Set the accessibility of {@code o} to {@code accessible}. If running without a {@link SecurityManager}
 * and {@code accessible == false}, this call is ignored (because any code could reflectively make any
 * object accessible at any time).//  w ww  . ja  va  2 s.  co  m
 * @param o
 * @param accessible
 * @return whether a change was made.
 */
public static boolean setAccessible(final AccessibleObject o, boolean accessible) {
    if (o == null || o.isAccessible() == accessible) {
        return false;
    }
    if (!accessible && System.getSecurityManager() == null) {
        return false;
    }
    final Member m = (Member) o;

    // For public members whose declaring classes are public, we need do nothing:
    if (Modifier.isPublic(m.getModifiers()) && Modifier.isPublic(m.getDeclaringClass().getModifiers())) {
        return false;
    }
    o.setAccessible(accessible);
    return true;
}

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

@Override
public Object compile(String scriptName, String scriptSource, Map<String, String> params) {
    // Create the script class name
    String className = MessageDigests
            .toHexString(MessageDigests.sha1().digest(scriptSource.getBytes(StandardCharsets.UTF_8)));

    final SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new SpecialPermission());
    }// www.  j  av a 2  s . c o  m
    return AccessController.doPrivileged(new PrivilegedAction<Object>() {
        @Override
        public Object run() {
            try {
                GroovyCodeSource codeSource = new GroovyCodeSource(scriptSource, className,
                        BootstrapInfo.UNTRUSTED_CODEBASE);
                codeSource.setCachable(false);

                CompilerConfiguration configuration = new CompilerConfiguration()
                        .addCompilationCustomizers(new ImportCustomizer().addStarImports("org.joda.time")
                                .addStaticStars("java.lang.Math"))
                        .addCompilationCustomizers(new GroovyBigDecimalTransformer(CompilePhase.CONVERSION));

                // always enable invokeDynamic, not the crazy softreference-based stuff
                configuration.getOptimizationOptions().put(GROOVY_INDY_SETTING_NAME, true);

                GroovyClassLoader groovyClassLoader = new GroovyClassLoader(loader, configuration);
                return groovyClassLoader.parseClass(codeSource);
            } catch (Exception e) {
                if (log.isTraceEnabled()) {
                    log.trace("Exception compiling Groovy script:", e);
                }
                throw convertToScriptException("Error compiling script " + className, scriptSource, e);
            }
        }
    });
}

From source file:org.wso2.carbon.registry.core.internal.RegistryCoreServiceComponent.java

/**
 * Activates the Registry Kernel bundle.
 *
 * @param context the OSGi component context.
 *///from ww  w .j  av a  2s.  c om
@SuppressWarnings("unused")
protected void activate(ComponentContext context) {
    // for new cahing, every thread should has its own populated CC. During the deployment time we assume super tenant
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    carbonContext.setTenantDomain(org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    carbonContext.setTenantId(org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_ID);

    // Need permissions in order activate Registry
    SecurityManager securityManager = System.getSecurityManager();
    if (securityManager != null) {
        securityManager.checkPermission(new ManagementPermission("control"));
    }
    try {
        bundleContext = context.getBundleContext();
        registryService = buildRegistryService();

        log.debug("Completed initializing the Registry Kernel");
        registrations
                .push(bundleContext.registerService(
                        new String[] { RegistryService.class.getName(),
                                org.wso2.carbon.registry.api.RegistryService.class.getName() },
                        registryService, null));
        registrations.push(bundleContext.registerService(SimulationService.class.getName(),
                new DefaultSimulationService(), null));
        TenantDeploymentListenerImpl listener = new TenantDeploymentListenerImpl(registryService);
        registrations.push(bundleContext.registerService(Axis2ConfigurationContextObserver.class.getName(),
                listener, null));
        registrations
                .push(bundleContext.registerService(AuthenticationObserver.class.getName(), listener, null));
        registrations.push(bundleContext.registerService(TenantRegistryLoader.class.getName(), listener, null));

        log.debug("Registry Core bundle is activated ");
    } catch (Throwable e) {
        log.error("Failed to activate Registry Core bundle ", e);
    }
}

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

public NamespaceHandler resolve(final String namespaceUri) {
    if (System.getSecurityManager() != null) {
        return AccessController.doPrivileged(new PrivilegedAction<NamespaceHandler>() {

            public NamespaceHandler run() {
                return doResolve(namespaceUri);
            }/* w  w w  . j a  v  a 2  s.c om*/
        });

    } else {
        return doResolve(namespaceUri);
    }
}

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

public ServletContext getContext(String uripath) {
    ServletContext theContext = null;/*from  ww w  .j a va  2s. co m*/
    if (System.getSecurityManager() != null) {
        theContext = (ServletContext) doPrivileged("getContext", new Object[] { uripath });
    } else {
        theContext = context.getContext(uripath);
    }
    if ((theContext != null) && (theContext instanceof ApplicationContext)) {
        theContext = ((ApplicationContext) theContext).getFacade();
    }
    return (theContext);
}

From source file:org.apache.jasper.compiler.JspRuntimeContext.java

/**
 * Create a JspRuntimeContext for a web application context.
 *
 * Loads in any previously generated dependencies from file.
 *
 * @param ServletContext for web application
 *//*from w  w  w.  j av  a  2  s.c om*/
public JspRuntimeContext(ServletContext context, Options options) {

    System.setErr(new SystemLogHandler(System.err));

    this.context = context;
    this.options = options;

    // Get the parent class loader
    parentClassLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
    if (parentClassLoader == null) {
        parentClassLoader = (URLClassLoader) this.getClass().getClassLoader();
    }

    if (log.isDebugEnabled()) {
        if (parentClassLoader != null) {
            log.debug(Localizer.getMessage("jsp.message.parent_class_loader_is", parentClassLoader.toString()));
        } else {
            log.debug(Localizer.getMessage("jsp.message.parent_class_loader_is", "<none>"));
        }
    }

    initClassPath();

    if (context instanceof org.apache.jasper.servlet.JspCServletContext) {
        return;
    }

    if (System.getSecurityManager() != null) {
        initSecurity();
    }

    // If this web application context is running from a
    // directory, start the background compilation thread
    String appBase = context.getRealPath("/");
    if (!options.getDevelopment() && appBase != null && options.getReloading()) {
        if (appBase.endsWith(File.separator)) {
            appBase = appBase.substring(0, appBase.length() - 1);
        }
        String directory = appBase.substring(appBase.lastIndexOf(File.separator));
        threadName = threadName + "[" + directory + "]";
        threadStart();
    }
}

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) {
        }/*w ww . java  2s. c o  m*/

        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:org.pepstock.jem.springbatch.tasks.JemTasklet.java

/**
 * Is called by SpringBatch framework to execute business logic.<br>
 * Prepares datasets (and the files and resources) which could be used from
 * implementation of this class.<br>
 * Loads JNDI context so all resources could be used by their name, defined
 * in JCL./* www  . j a v a2  s.com*/
 * 
 * @param stepContribution step contribution, passed by SpringBatch core
 * @param chunkContext chunk context, passed by SpringBatch core
 * @return always the status returned by abstract method
 *         <code>executeByJem</code>
 * @throws SpringBatchException if a error occurs
 */
@Override
public final RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext)
        throws SpringBatchException {
    LogAppl.getInstance();

    // this boolean is necessary to understand if I have an exception 
    // before calling the main class
    boolean isExecutionStarted = false;
    boolean isAbended = false;

    SpringBatchSecurityManager batchSM = (SpringBatchSecurityManager) System.getSecurityManager();
    batchSM.setInternalAction(true);

    RepeatStatus status = null;

    // extract stepContext because the step name is necessary
    StepContext stepContext = chunkContext.getStepContext();

    List<DataDescriptionImpl> dataDescriptionImplList = ImplementationsContainer.getInstance()
            .getDataDescriptionsByItem(stepContext.getStepName());

    // new initial context for JNDI
    InitialContext ic = null;

    try {
        ic = ContextUtils.getContext();
        // scans all datasource passed
        for (DataSource source : dataSourceList) {
            // checks if datasource is well defined
            if (source.getResource() == null) {
                throw new SpringBatchException(SpringBatchMessage.JEMS016E);
            } else if (source.getName() == null) {
                // if name is missing, it uses the same string 
                // used to define the resource
                source.setName(source.getResource());
            }
            // gets the RMi object to get resources
            CommonResourcer resourcer = InitiatorManager.getCommonResourcer();
            // lookups by RMI for the database 
            Resource res = resourcer.lookup(JobId.VALUE, source.getResource());
            if (!batchSM.checkResource(res)) {
                throw new SpringBatchException(SpringBatchMessage.JEMS017E, res.toString());
            }

            // all properties create all StringRefAddrs necessary
            Map<String, ResourceProperty> properties = res.getProperties();

            // scans all properteis set by JCL
            for (Property property : source.getProperties()) {
                if (property.isCustom()) {
                    if (res.getCustomProperties() == null) {
                        res.setCustomProperties(new HashMap<String, String>());
                    }
                    if (!res.getCustomProperties().containsKey(property.getName())) {
                        res.getCustomProperties().put(property.getName(), property.getValue());
                    } else {
                        throw new SpringBatchException(SpringBatchMessage.JEMS018E, property.getName(), res);
                    }
                } else {
                    // if a key is defined FINAL, throw an exception
                    for (ResourceProperty resProperty : properties.values()) {
                        if (resProperty.getName().equalsIgnoreCase(property.getName())
                                && !resProperty.isOverride()) {
                            throw new SpringBatchException(SpringBatchMessage.JEMS018E, property.getName(),
                                    res);
                        }
                    }
                    ResourcePropertiesUtil.addProperty(res, property.getName(), property.getValue());
                }
            }

            // creates a JNDI reference
            Reference ref = getReference(resourcer, res, source, dataDescriptionImplList);

            // loads all properties into RefAddr
            for (ResourceProperty property : properties.values()) {
                ref.add(new StringRefAddr(property.getName(), replaceProperties(property.getValue())));
            }

            // loads custom properties in a string format
            if (res.getCustomProperties() != null && !res.getCustomProperties().isEmpty()) {
                // loads all entries and substitute variables
                for (Entry<String, String> entry : res.getCustomProperties().entrySet()) {
                    String value = replaceProperties(entry.getValue());
                    entry.setValue(value);
                }
                // adds to reference
                ref.add(new StringRefAddr(CommonKeys.RESOURCE_CUSTOM_PROPERTIES,
                        res.getCustomPropertiesString()));
            }

            // binds the object with format {type]/[name]
            LogAppl.getInstance().emit(SpringBatchMessage.JEMS024I, res);
            ic.rebind(source.getName(), ref);
        }

        // check if I have resources which must be locked
        if (!dataDescriptionImplList.isEmpty()) {

            // binds all data description impl to JNDI context
            for (DataDescriptionImpl ddImpl : dataDescriptionImplList) {

                // create reference for JNDI access
                Reference reference = new DataStreamReference();

                // load GDG information, solving the real name of relative
                // position
                GDGManager.load(ddImpl);
                // serialize data description object in XML format
                XStream xstream = new XStream();
                String xml = xstream.toXML(ddImpl);
                // add string xml reference
                reference.add(new StringRefAddr(StringRefAddrKeys.DATASTREAMS_KEY, xml));

                LogAppl.getInstance().emit(SpringBatchMessage.JEMS023I, ddImpl);
                // bind resource using data description name
                ic.rebind(ddImpl.getName(), reference);
            }
        }
        // execute business logic
        // executes the java class defined in JCL
        // setting the boolean to TRUE
        SetFields.applyByAnnotation(this);
        isExecutionStarted = true;
        batchSM.setInternalAction(false);
        status = this.run(stepContribution, chunkContext);
    } catch (NamingException e) {
        isAbended = true;
        throw new SpringBatchException(SpringBatchMessage.JEMS043E, e);
    } catch (RemoteException e) {
        isAbended = true;
        throw new SpringBatchException(SpringBatchMessage.JEMS045E, e, this.getClass().getName(),
                e.getMessage());
    } catch (IOException e) {
        isAbended = true;
        throw new SpringBatchException(SpringBatchMessage.JEMS044E, e, e.getMessage());
    } catch (Exception e) {
        isAbended = true;
        throw new SpringBatchException(SpringBatchMessage.JEMS045E, e, this.getClass().getName(),
                e.getMessage());
    } finally {
        batchSM.setInternalAction(true);
        if (!dataDescriptionImplList.isEmpty()) {
            StringBuilder exceptions = new StringBuilder();
            // scans data descriptions
            for (DataDescriptionImpl ddImpl : dataDescriptionImplList) {
                try {
                    // commit the GDG index in the root
                    // if an exception, write on standard output of job
                    // only if execution started
                    if (isExecutionStarted) {
                        GDGManager.store(ddImpl);
                    }
                } catch (IOException e) {
                    // ignore
                    LogAppl.getInstance().ignore(e.getMessage(), e);

                    LogAppl.getInstance().emit(SpringBatchMessage.JEMS025E, e.getMessage());
                    if (exceptions.length() == 0) {
                        exceptions.append(e.getMessage());
                    } else {
                        exceptions.append(e.getMessage()).append("\n");
                    }
                }
                // unbinds all data sources
                try {
                    ic.unbind(ddImpl.getName());
                } catch (NamingException e) {
                    // ignore
                    LogAppl.getInstance().ignore(e.getMessage(), e);
                    LogAppl.getInstance().emit(SpringBatchMessage.JEMS047E, e.getMessage());
                }
                if (exceptions.length() > 0 && !isAbended) {
                    LogAppl.getInstance().emit(SpringBatchMessage.JEMS025E,
                            StringUtils.center("ATTENTION", 40, "-"));
                    LogAppl.getInstance().emit(SpringBatchMessage.JEMS025E, exceptions.toString());
                }

            }
        }
        for (DataSource source : dataSourceList) {
            if (source.getName() != null) {
                // unbinds all resources
                try {
                    ic.unbind(source.getName());
                } catch (NamingException e) {
                    // ignore
                    LogAppl.getInstance().ignore(e.getMessage(), e);
                    LogAppl.getInstance().emit(SpringBatchMessage.JEMS047E, e.getMessage());
                }
            }
        }
        batchSM.setInternalAction(false);
    }
    return status;
}