Example usage for java.lang.management ManagementPermission ManagementPermission

List of usage examples for java.lang.management ManagementPermission ManagementPermission

Introduction

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

Prototype

public ManagementPermission(String name) 

Source Link

Document

Constructs a ManagementPermission with the specified name.

Usage

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

/**
 * Start the CarbonServerManager/*  w w  w  . j  a  va2s  . co 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 ww w . j  a va2s  .  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/*w  ww  .j  ava  2s. 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();
        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);
        }
    }
}

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"));
    }// w w  w .  j a va 2  s .  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/>//from   w  ww.j av a2s  . com
 * 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 ww.  ja va 2s . c om*/
 *
 * @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  ww .  java 2 s  .  c  o  m*/
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 va 2s  .  c om*/
        // 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   w w w  .  j  ava2  s. co 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.
 *///from   w  w  w . jav a  2s  .  c o  m
@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);
    }
}