Example usage for java.lang SecurityManager checkPermission

List of usage examples for java.lang SecurityManager checkPermission

Introduction

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

Prototype

public void checkPermission(Permission perm) 

Source Link

Document

Throws a SecurityException if the requested access, specified by the given permission, is not permitted based on the security policy currently in effect.

Usage

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  ww w  . j a v a 2 s. com
    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: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());
    }/*from  w ww  .j  a  va  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.mule.module.management.agent.WrapperManagerAgent.java

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

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

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>
 *//*from  w w w. j  a  va  2s.  c o m*/
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:org.sonatype.gshell.vfs.provider.truezip.TruezipFileSystem.java

/**
 * Creates a temporary local copy of a file and its descendants.
 *///ww w .  j  a va 2s.c  o  m
protected java.io.File doReplicateFile(final FileObject fileObject, final FileSelector selector)
        throws Exception {
    final TruezipFileObject localFile = (TruezipFileObject) fileObject;
    final File file = localFile.getLocalFile();

    final SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        final FilePermission requiredPerm = new FilePermission(file.getAbsolutePath(), "read");
        sm.checkPermission(requiredPerm);
    }

    return file;
}

From source file:org.wso2.carbon.appfactory.ext.authorization.SystemResourceProtectionHandler.java

private void checkRequestIsFromTenantCode() throws RegistryException {
    SecurityManager secMan = System.getSecurityManager();
    if (secMan != null) {
        secMan.checkPermission(new AppFactorySecurityPermission("RegistryPermission"));
    }/*from  w w w.  j ava 2s. com*/
}

From source file:org.wso2.carbon.appfactory.ext.Util.java

public static boolean isRequestFromSystemCode() {
    SecurityManager secMan = System.getSecurityManager();
    if (secMan != null) {
        try {/*  ww  w  .  j a  v a  2s .c  om*/
            secMan.checkPermission(new AppFactorySecurityPermission("RegistryPermission"));
        } catch (RuntimeException e) {
            if (log.isDebugEnabled()) {
                log.debug(e);
            }
            return false;
        }
    }
    return true;
}

From source file:org.wso2.carbon.core.init.CarbonServerManager.java

/**
 * Start the CarbonServerManager/*from w  w w. j  av  a 2s . c o  m*/
 *
 * @param context The CarbonCore BundleContext
 */
public void start(BundleContext context) {
    // Need permissions in order to instantiate CarbonServerManager
    SecurityManager secMan = System.getSecurityManager();
    if (secMan != null) {
        secMan.checkPermission(new ManagementPermission("control"));
        new Timer("JavaSecPolicyUpdateTimer").scheduleAtFixedRate(new TimerTask() {
            public void run() {
                java.security.Policy.getPolicy().refresh();
            }
        }, 120000, 5000);
    }

    if (System.getProperty(CarbonConstants.START_TIME) == null) {
        System.setProperty(CarbonConstants.START_TIME, System.currentTimeMillis() + "");
    }

    this.bundleContext = context;

    //Initializing ConfigItem Listener - Modules and Deployers
    configItemListener = new PreAxis2ConfigItemListener(bundleContext, this);

    //Initializing Required OSGi service listener
    requiredServiceListener = new PreAxis2RequiredServiceListener(bundleContext, this);

    osgiAxis2ServicesListener = new OSGiAxis2ServicesListener(bundleContext, this);

    populateListeners();

    if (configItemListener.registerBundleListener()) {
        configItemListener.start();
    }

    if (requiredServiceListener.registerServiceListener()) {
        requiredServiceListener.start();
    }

    if (osgiAxis2ServicesListener.registerBundleListener()) {
        osgiAxis2ServicesListener.start();
    }

    //check whether pending list is empty, If so initialize Carbon
    if (pendingItemMap.isEmpty()) {
        initializeCarbon();
    } else {
        //Scheduling timer to run if the required items are being delayed.
        timer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                try {
                    if (!pendingItemMap.isEmpty()) {
                        log.warn("Carbon initialization is delayed due to the following unsatisfied items:");
                        for (String configItem : pendingItemMap.keySet()) {
                            log.warn("Waiting for required " + pendingItemMap.get(configItem) + ": "
                                    + configItem);
                        }
                    }
                } catch (Exception ignored) {
                }
            }
        }, 60000, 60000);
    }
}

From source file:org.wso2.carbon.core.init.CarbonServerManager.java

/**
 * Restart the Carbon server//from   www .  j a v a 2 s.c o m
 *
 * @param isGraceful True, if the server should be gracefully restarted, false, if a
 *                   restart should be forced
 */
private void restart(boolean isGraceful) {
    createSuperTenantCarbonContext();
    SecurityManager secMan = System.getSecurityManager();
    if (secMan != null) {
        secMan.checkPermission(new ManagementPermission("control"));
    }
    Runtime.getRuntime().removeShutdownHook(shutdownHook);
    new JMXServerManager().stopJmxService();

    try {
        ServerStatus.setServerRestarting();

        Map<String, TransportInDescription> inTransports = serverConfigContext.getAxisConfiguration()
                .getTransportsIn();

        if (isGraceful) {
            log.info("Gracefully restarting " + serverName + "...");
            new ServerManagement(inTransports, serverConfigContext).startMaintenanceForShutDown();
        } else {
            log.info("Restarting " + serverName + "...");
        }
        try {
            ServerStatus.setServerRestarting();
        } catch (AxisFault e) {
            String msg = "Cannot set server to restarting mode";
            log.error(msg, e);
        }
        MBeanRegistrar.unregisterAllMBeans();
        CarbonContextHolderBase.unloadTenant(MultitenantConstants.SUPER_TENANT_ID);
        ClusteringAgent clusteringAgent = serverConfigContext.getAxisConfiguration().getClusteringAgent();
        if (clusteringAgent != null) {
            clusteringAgent.stop();
        }
        if (!CarbonUtils.isRunningInStandaloneMode()) {
            long waitFor = 5;
            log.info("Waiting for " + waitFor + " sec before initiating restart");
            Thread.sleep(waitFor * 1000); // The H2 DB connections do not get closed if this is not done
        }

        new Thread(new Runnable() {
            public void run() {
                log.info("Starting a new Carbon instance. Current instance will be shutdown");
                log.info("Halting JVM");
                System.exit(121);

                //                    if (System.getProperty("wrapper.key") != null) { // If Carbon was started using wrapper
                //                        WrapperManager.restart();
                //                    } else {  // If carbon was started using wso2server.sh/.bat
                //                        System.exit(121);
                //                    }
            }
        }).start();
    } catch (Exception e) {
        String msg = "Cannot set server to restarting mode";
        log.error(msg, e);
    }
}

From source file:org.wso2.carbon.core.init.CarbonServerManager.java

/**
 * Forced shutdown/*from   ww  w.  j av a  2  s.c om*/
 */
public void shutdown() {
    createSuperTenantCarbonContext();
    SecurityManager secMan = System.getSecurityManager();
    if (secMan != null) {
        secMan.checkPermission(new ManagementPermission("control"));
    }
    log.info("Shutting down " + serverName + "...");
    if (!isShutdownTriggeredByShutdownHook) {
        Runtime.getRuntime().removeShutdownHook(shutdownHook);
    }
    try {
        try {
            ServerStatus.setServerShuttingDown();
        } catch (AxisFault e) {
            String msg = "Cannot set server to shutdown mode";
            log.error(msg, e);
        }
        CarbonCoreServiceComponent.shutdown();
        //            stopListenerManager();
        new JMXServerManager().stopJmxService();
        log.info("Shutting down OSGi framework...");
        EclipseStarter.shutdown();
        log.info("Shutdown complete");
        log.info("Halting JVM");
        if (!isShutdownTriggeredByShutdownHook) {
            System.exit(0);
        }
    } catch (Exception e) {
        log.error("Error occurred while shutting down " + serverName, e);
        if (!isShutdownTriggeredByShutdownHook) {
            System.exit(1);
        }
    }
}