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.wso2.carbon.core.internal.CarbonCoreActivator.java

public void start(BundleContext context) throws Exception {
    // Need permissions in order to activate Carbon Core
    SecurityManager secMan = System.getSecurityManager();
    if (secMan != null) {
        secMan.checkPermission(new ManagementPermission("control"));
    }/*from  www  . ja v a  2s .  c o m*/
    // We assume it's super tenant during the deployment time
    PrivilegedCarbonContext privilegedCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    privilegedCarbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    privilegedCarbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);

    dataHolder.setBundleContext(context);
    log.info("Starting WSO2 Carbon...");
    log.info("Operating System : " + System.getProperty("os.name") + " " + System.getProperty("os.version")
            + ", " + System.getProperty("os.arch"));
    log.info("Java Home        : " + System.getProperty("java.home"));
    log.info("Java Version     : " + System.getProperty("java.version"));
    log.info("Java VM          : " + System.getProperty("java.vm.name") + " "
            + System.getProperty("java.vm.version") + "," + System.getProperty("java.vendor"));

    String carbonHome;
    if ((carbonHome = System.getProperty("carbon.home")).equals(".")) {
        carbonHome = new File(".").getAbsolutePath();
    }

    log.info("Carbon Home      : " + carbonHome);
    log.info("Java Temp Dir    : " + System.getProperty("java.io.tmpdir"));
    log.info(
            "User             : " + System.getProperty("user.name") + ", " + System.getProperty("user.language")
                    + "-" + System.getProperty("user.country") + ", " + System.getProperty("user.timezone"));

    Security.addProvider(new BouncyCastleProvider());
    if (log.isDebugEnabled()) {
        log.debug("BouncyCastle security provider is successfully registered in JVM.");
    }
}

From source file:org.wso2.carbon.core.ServerManagement.java

/**
 * Method to switch a node to maintenance mode.
 * <p/>/* w  w  w  . j a  v  a  2s  .  c om*/
 * Here is the sequence of events:
 * <p/>
 * <ol>
 * <li>Client calls this method</li>
 * <li>The server stops accepting new requests/connections, but continues to stay alive so
 * that old requests & connections can be served</li>
 * <li>Once all requests have been processed, the method returns</li
 * </ol>
 * @throws Exception - on errors while starting maintenance
 */
public void startMaintenance() throws Exception {
    SecurityManager secMan = System.getSecurityManager();
    if (secMan != null) {
        secMan.checkPermission(new ManagementPermission("control"));
    }
    log.info("Starting to switch to maintenance mode...");
    for (TransportInDescription tinDesc : inTransports.values()) {
        TransportListener transport = tinDesc.getReceiver();
        transport.stop();
    }
    log.info("Stopped all transport listeners");

    waitForRequestCompletion();
}

From source file:org.wso2.carbon.core.ServerManagement.java

/**
 * Wait till all service requests have been serviced. This method will only wait for a maximum
 * of {@link ServerManagement#TIMEOUT}//from w  w  w .  j  ava2 s  .c o m
 *
 * @throws Exception If an error occurs while trying to connect to the Tomcat MBean
 */
public void waitForRequestCompletion() throws Exception {
    SecurityManager secMan = System.getSecurityManager();
    if (secMan != null) {
        secMan.checkPermission(new ManagementPermission("control"));
    }
    log.info("Waiting for request service completion...");
    /**
     * Get all MBeans with names such as Catalina:type=RequestProcessor,worker=http-9762,name=HttpRequest<n>
     * & Catalina:type=RequestProcessor,worker=http-9762,name=HttpsRequest<n>
     */
    MBeanServer mbs = ManagementFactory.getMBeanServer();
    boolean areRequestsInService;
    long start = System.currentTimeMillis();
    do {
        // Check whether there are any processors which are currently in the SERVICE stage (3)
        QueryExp query = Query.eq(Query.attr("stage"), Query.value(3)); // 3 = org.apache.coyote.Constants.STAGE_SERVICE
        Set set = mbs.queryNames(new ObjectName("Catalina:type=RequestProcessor,*"), query);
        if (set.size() > 0) {
            areRequestsInService = true;
            if (System.currentTimeMillis() - start > TIMEOUT) {
                log.warn("Timeout occurred even though there are active connections.");
                break;
            }
            Thread.sleep(2000);
        } else {
            areRequestsInService = false;
        }
    } while (areRequestsInService);
    log.info("All requests have been served.");
}

From source file:org.wso2.carbon.core.ServerManagement.java

/**
 * Method to change the state of a node from "maintenance" to "normal"
 *
 * @throws Exception If an error occurs while trying to connect to the Tomcat MBean
 *///from w w w  . j a  v  a  2s  .c  om
public void endMaintenance() throws Exception {
    SecurityManager secMan = System.getSecurityManager();
    if (secMan != null) {
        secMan.checkPermission(new ManagementPermission("control"));
    }
    log.info("Switching to normal mode...");
    for (Iterator iter = inTransports.values().iterator(); iter.hasNext();) {
        TransportInDescription tinDesc = (TransportInDescription) iter.next();
        TransportListener transport = tinDesc.getReceiver();
        transport.start();
    }
    log.info("Switched to normal mode");
}

From source file:org.wso2.carbon.micro.integrator.core.internal.Activator.java

@Override
public void start(BundleContext bundleContext) throws Exception {
    try {//  w w w.  j a  v a2  s .  c  o m
        // Need permissions in order to activate Carbon Core
        SecurityManager secMan = System.getSecurityManager();
        if (secMan != null) {
            secMan.checkPermission(new ManagementPermission("control"));
        }
        // We assume it's super tenant during the deployment time
        PrivilegedCarbonContext privilegedCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        privilegedCarbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        privilegedCarbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        log.info("Starting WSO2 Micro Integrator ...");
        log.info("Operating System : " + System.getProperty("os.name") + " " + System.getProperty("os.version")
                + ", " + System.getProperty("os.arch"));
        if (log.isDebugEnabled()) {
            log.debug("Java Home        : " + System.getProperty("java.home"));
        }
        log.info("Java Version     : " + System.getProperty("java.version"));
        log.info("Java VM          : " + System.getProperty("java.vm.name") + " "
                + System.getProperty("java.vm.version") + "," + System.getProperty("java.vendor"));

        String carbonHome;
        if ((carbonHome = System.getProperty("carbon.home")).equals(".")) {
            carbonHome = new File(".").getAbsolutePath();
        }
        log.info("Micro Integrator Home      : " + carbonHome);

        if (log.isDebugEnabled()) {
            log.info("Java Temp Dir    : " + System.getProperty("java.io.tmpdir"));
            log.info("User             : " + System.getProperty("user.name") + ", "
                    + System.getProperty("user.language") + "-" + System.getProperty("user.country") + ", "
                    + System.getProperty("user.timezone"));
        }
        Security.addProvider(new BouncyCastleProvider());
        if (log.isDebugEnabled()) {
            log.debug("BouncyCastle security provider is successfully registered in JVM.");
        }
        bundleContext.registerService(CarbonCoreInitializedEvent.class.getName(),
                new CarbonCoreInitializedEventImpl(), null);
        GhostServiceMetaArtifactsLoader serviceMetaArtifactsLoader = new GhostServiceMetaArtifactsLoader();
        bundleContext.registerService(GhostMetaArtifactsLoader.class.getName(), serviceMetaArtifactsLoader,
                null);
        CarbonCoreDataHolder.getInstance().setBundleContext(bundleContext);
    } catch (Throwable e) {
        throw new Exception(e);
    }
}

From source file:org.wso2.carbon.micro.integrator.core.internal.ServiceComponent.java

/**
 * Forced shutdown//from  ww  w.  j  a  v a 2  s.c o m
 */
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();
        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);
        }
    }
}

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

/**
 * Activates the Registry Kernel bundle.
 *
 * @param context the OSGi component context.
 *//*www . j a  va 2s .com*/
@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.wso2.carbon.repository.core.internal.RepositoryServiceComponent.java

/**
 * Activates the Repository Kernel bundle.
 *
 * @param context the OSGi component context.
 *///w ww .  ja v a 2s. c o m
protected void activate(ComponentContext context) {
    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 to activate Registry
    SecurityManager securityManager = System.getSecurityManager();

    if (securityManager != null) {
        securityManager.checkPermission(new ManagementPermission("control"));
    }

    try {
        bundleContext = context.getBundleContext();
        repositoryService = buildRepositoryService();

        log.debug("Completed initializing the Registry Kernel");

        registrations.push(bundleContext.registerService(new String[] { RepositoryService.class.getName() },
                repositoryService, null));
        registrations.push(bundleContext.registerService(SimulationService.class.getName(),
                new DefaultSimulationService(), null));

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

From source file:org.wso2.carbon.user.core.internal.Activator.java

public void startDeploy(BundleContext bundleContext) throws Exception {
    // Need permissions in order to instantiate user core
    SecurityManager secMan = System.getSecurityManager();

    /*//from  w  ww  .j a  v  a 2  s .c om
       * Read the SSL trust store configurations from the Security.TrustStore
     * element of the Carbon.xml
     */
    ServerConfiguration config = ServerConfiguration.getInstance();
    String type = config.getFirstProperty("Security.TrustStore.Type");
    String password = config.getFirstProperty("Security.TrustStore.Password");
    String storeFile = new File(config.getFirstProperty("Security.TrustStore.Location")).getAbsolutePath();
    // set the SSL trust store System Properties
    System.setProperty("javax.net.ssl.trustStore", storeFile);
    System.setProperty("javax.net.ssl.trustStoreType", type);
    System.setProperty("javax.net.ssl.trustStorePassword", password);

    if (secMan != null) {
        secMan.checkPermission(new ManagementPermission("control"));
    }
    try {
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        RealmService realmService = new DefaultRealmService(bundleContext);
        bundleContext.registerService(
                new String[] { RealmService.class.getName(), UserRealmService.class.getName() }, realmService,
                null);
        UserCoreUtil.setRealmService(realmService);
    } catch (Throwable e) {
        String msg = "Cannot start User Manager Core bundle";
        log.error(msg, e);
        // do not throw exceptions;
    }
}

From source file:org.wso2.carbon.webapp.mgt.TomcatGenericWebappsDeployer.java

/**
 * Constructor//from w  ww . ja  v a2 s  .c  o  m
 *
 * @param webContextPrefix         The Web context prefix
 * @param tenantId                 The tenant ID of the tenant to whom this deployer belongs to
 * @param tenantDomain             The tenant domain of the tenant to whom this deployer belongs to
 * @param webApplicationsHolderMap WebApplicationsHolder
 */
public TomcatGenericWebappsDeployer(String webContextPrefix, int tenantId, String tenantDomain,
        Map<String, WebApplicationsHolder> webApplicationsHolderMap,
        ConfigurationContext configurationContext) {
    SecurityManager secMan = System.getSecurityManager();
    if (secMan != null) {
        secMan.checkPermission(new ManagementPermission("control"));
    }
    this.tenantId = tenantId;
    this.tenantDomain = tenantDomain;
    this.webContextPrefix = webContextPrefix;
    this.webApplicationsHolderMap = webApplicationsHolderMap;
    this.configurationContext = configurationContext;
}