Example usage for java.lang.management ManagementFactory getPlatformMBeanServer

List of usage examples for java.lang.management ManagementFactory getPlatformMBeanServer

Introduction

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

Prototype

public static synchronized MBeanServer getPlatformMBeanServer() 

Source Link

Document

Returns the platform javax.management.MBeanServer MBeanServer .

Usage

From source file:be.fgov.kszbcss.rhq.websphere.config.ConfigQueryServiceImpl.java

public void release() {
    try {/*from   ww  w  .  ja  va  2 s.c o m*/
        ManagementFactory.getPlatformMBeanServer().unregisterMBean(mbean.getObjectName());
    } catch (Throwable ex) {
        log.error("MBean unregistration failed", ex);
    }
    config.destroy();
    future.cancel(false);
    epochPollExecutorService.shutdownNow();
    try {
        queryCache.stop();
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
    }
}

From source file:org.apereo.portal.jmx.JavaManagementServerBean.java

/**
 * Starts the RMI server and JMX connector server
 *//*from w w w . j  a va 2  s  .  com*/
public void startServer() {
    if (!System.getProperties().containsKey(JMX_ENABLED_PROPERTY)) {
        this.logger.info("System Property '" + JMX_ENABLED_PROPERTY + "' is not set, skipping initialization.");
        return;
    }

    try {
        //Get the base rmi port
        final int portOne = this.getPortOne();

        //Get the second rmi port or calculate it
        final int portTwo = this.calculatePortTwo(portOne);

        //Create the RMI registry on the base port
        try {
            LocateRegistry.createRegistry(portOne);

            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Started RMI Registry on port " + portOne);
            }
        } catch (RemoteException re) {
            throw new IllegalStateException("Could not create RMI Registry on port " + portOne, re);
        }

        //Generate the JMX Service URL
        final JMXServiceURL jmxServiceUrl = this.getServiceUrl(portOne, portTwo);

        //Map for the JMX environment configuration
        final Map<String, Object> jmxEnv = this.getJmxServerEnvironment();

        //Create the MBean Server
        final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();

        //Create the JMX Connector
        try {
            this.jmxConnectorServer = JMXConnectorServerFactory.newJMXConnectorServer(jmxServiceUrl, jmxEnv,
                    mbeanServer);

            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Created JMXConnectorServer for JMXServiceURL='" + jmxServiceUrl
                        + "', jmxEnv='" + jmxEnv + "' MBeanServer='" + mbeanServer + "'");
            }
        } catch (IOException ioe) {
            throw new IllegalStateException("Failed to create a new JMXConnectorServer for JMXServiceURL='"
                    + jmxServiceUrl + "', jmxEnv='" + jmxEnv + "' MBeanServer='" + mbeanServer + "'", ioe);
        }

        //Start the JMX Connector
        try {
            this.jmxConnectorServer.start();
            this.logger.info("Started JMXConnectorServer. Listening on '" + jmxServiceUrl + "'");
        } catch (IOException ioe) {
            throw new IllegalStateException("Failed to start the JMXConnectorServer", ioe);
        }
    } catch (RuntimeException re) {
        if (this.failOnException) {
            throw re;
        }

        this.logger.error("Failed to initialize the JMX Server", re);
    }
}

From source file:org.apache.cloudstack.ServerDaemon.java

@Override
public void start() throws Exception {
    // Thread pool
    final QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setMinThreads(10);/*from w  w w .  j a v a2s. c o  m*/
    threadPool.setMaxThreads(500);

    // Jetty Server
    server = new Server(threadPool);

    // Setup Scheduler
    server.addBean(new ScheduledExecutorScheduler());

    // Setup JMX
    final MBeanContainer mbeanContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    server.addBean(mbeanContainer);

    // HTTP config
    final HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.addCustomizer(new ForwardedRequestCustomizer());
    httpConfig.setSecureScheme("https");
    httpConfig.setSecurePort(httpsPort);
    httpConfig.setOutputBufferSize(32768);
    httpConfig.setRequestHeaderSize(8192);
    httpConfig.setResponseHeaderSize(8192);
    httpConfig.setSendServerVersion(false);
    httpConfig.setSendDateHeader(false);

    // HTTP Connector
    final ServerConnector httpConnector = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
    httpConnector.setPort(httpPort);
    httpConnector.setHost(bindInterface);
    httpConnector.setIdleTimeout(30000);
    server.addConnector(httpConnector);

    // Setup handlers
    server.setHandler(createHandlers());

    // Extra config options
    server.setStopAtShutdown(true);

    // Configure SSL
    if (httpsEnable && !Strings.isNullOrEmpty(keystoreFile) && new File(keystoreFile).exists()) {
        // SSL Context
        final SslContextFactory sslContextFactory = new SslContextFactory();
        // Define keystore path and passwords
        sslContextFactory.setKeyStorePath(keystoreFile);
        sslContextFactory.setKeyStorePassword(keystorePassword);
        sslContextFactory.setKeyManagerPassword(keystorePassword);

        // HTTPS config
        final HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
        httpsConfig.addCustomizer(new SecureRequestCustomizer());

        // HTTPS connector
        final ServerConnector sslConnector = new ServerConnector(server,
                new SslConnectionFactory(sslContextFactory, "http/1.1"),
                new HttpConnectionFactory(httpsConfig));
        sslConnector.setPort(httpsPort);
        sslConnector.setHost(bindInterface);
        server.addConnector(sslConnector);
    }

    server.start();
    server.join();
}

From source file:org.zanata.ZanataInit.java

private void checkAppServerVersion() throws MalformedObjectNameException, AttributeNotFoundException,
        MBeanException, ReflectionException, InstanceNotFoundException {
    MBeanServer jmx = ManagementFactory.getPlatformMBeanServer();
    ObjectName server = new ObjectName("jboss.as:management-root=server");
    String releaseCodename = (String) jmx.getAttribute(server, "releaseCodename");
    String releaseVersion = (String) jmx.getAttribute(server, "releaseVersion");
    String productName = (String) jmx.getAttribute(server, "productName");
    String productVersion = (String) jmx.getAttribute(server, "productVersion");
    log.info("App server release codename: {}", releaseCodename);
    log.info("App server release version: {}", releaseVersion);
    switch ((productName == null) ? "" : productName) {
    case "JBoss EAP":

    case "EAP":
        checkEAPVersion(productVersion);
        break;/* w  w  w .j  a  v  a 2  s.  c o m*/

    case "WildFly Full":
        checkWildFlyVersion(productVersion);
        break;

    default:
        log.warn("Unknown app server.  This application requires EAP >= {} or WildFly Full >= {}",
                MIN_EAP_VERSION, MIN_WILDFLY_VERSION);
        break;

    }
}

From source file:com.googlecode.jmxtrans.model.output.StatsDWriter.java

@Override
public void close() throws LifecycleException {
    try {//w  w w  . j  av  a 2s.  c om
        if (this.mbean != null) {
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            mbs.unregisterMBean(this.mbean.getObjectName());
            this.mbean = null;
        }
        if (this.pool != null) {
            pool.close();
            this.pool = null;
        }
    } catch (Exception e) {
        throw new LifecycleException(e);
    }
}

From source file:com.googlecode.jmxtrans.guice.JmxTransModule.java

private <K, V> GenericKeyedObjectPool getObjectPool(KeyedPoolableObjectFactory<K, V> factory, String poolName) {
    GenericKeyedObjectPool<K, V> pool = new GenericKeyedObjectPool<K, V>(factory);
    pool.setTestOnBorrow(true);/*from w  w w . ja va  2  s  .c o m*/
    pool.setMaxActive(-1);
    pool.setMaxIdle(-1);
    pool.setTimeBetweenEvictionRunsMillis(MILLISECONDS.convert(5, MINUTES));
    pool.setMinEvictableIdleTimeMillis(MILLISECONDS.convert(5, MINUTES));

    try {
        ManagedGenericKeyedObjectPool mbean = new ManagedGenericKeyedObjectPool(pool, poolName);
        ManagementFactory.getPlatformMBeanServer().registerMBean(mbean, mbean.getObjectName());
    } catch (Exception e) {
        log.error("Could not register mbean for pool [{}]", poolName, e);
    }

    return pool;
}

From source file:org.apache.hadoop.hdfs.server.datanode.TestDataNodeMXBean.java

@Test
public void testDataNodeMXBeanBlockCount() throws Exception {
    Configuration conf = new Configuration();
    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build();

    try {//from   ww w.j a  va2 s .  c om
        List<DataNode> datanodes = cluster.getDataNodes();
        assertEquals(datanodes.size(), 1);

        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName mxbeanName = new ObjectName("Hadoop:service=DataNode,name=DataNodeInfo");
        FileSystem fs = cluster.getFileSystem();
        for (int i = 0; i < 5; i++) {
            DFSTestUtil.createFile(fs, new Path("/tmp.txt" + i), 1024, (short) 1, 1L);
        }
        assertEquals("Before restart DN", 5, getTotalNumBlocks(mbs, mxbeanName));
        cluster.restartDataNode(0);
        cluster.waitActive();
        assertEquals("After restart DN", 5, getTotalNumBlocks(mbs, mxbeanName));
        fs.delete(new Path("/tmp.txt1"), true);
        // The total numBlocks should be updated after one file is deleted
        GenericTestUtils.waitFor(new Supplier<Boolean>() {
            @Override
            public Boolean get() {
                try {
                    return getTotalNumBlocks(mbs, mxbeanName) == 4;
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
            }
        }, 100, 30000);
    } finally {
        if (cluster != null) {
            cluster.shutdown();
        }
    }
}

From source file:org.apache.hadoop.hdfs.server.namenode.TestHostsFiles.java

@Test
public void testHostsIncludeForDeadCount() throws Exception {
    Configuration conf = getConf();
    // Configure an excludes file
    FileSystem localFileSys = FileSystem.getLocal(conf);
    Path workingDir = localFileSys.getWorkingDirectory();
    Path dir = new Path(workingDir, "build/test/data/temp/decommission");
    Path excludeFile = new Path(dir, "exclude");
    Path includeFile = new Path(dir, "include");
    assertTrue(localFileSys.mkdirs(dir));
    StringBuilder includeHosts = new StringBuilder();
    includeHosts.append("localhost:52").append("\n").append("127.0.0.1:7777").append("\n");
    DFSTestUtil.writeFile(localFileSys, excludeFile, "");
    DFSTestUtil.writeFile(localFileSys, includeFile, includeHosts.toString());
    conf.set(DFSConfigKeys.DFS_HOSTS_EXCLUDE, excludeFile.toUri().getPath());
    conf.set(DFSConfigKeys.DFS_HOSTS, includeFile.toUri().getPath());
    MiniDFSCluster cluster = null;//from   w  ww. j  a  va  2 s .c o m
    try {
        cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0).build();
        final FSNamesystem ns = cluster.getNameNode().getNamesystem();
        assertTrue(ns.getNumDeadDataNodes() == 2);
        assertTrue(ns.getNumLiveDataNodes() == 0);
        // Testing using MBeans
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName mxbeanName = new ObjectName("Hadoop:service=NameNode,name=FSNamesystemState");
        String nodes = mbs.getAttribute(mxbeanName, "NumDeadDataNodes") + "";
        assertTrue((Integer) mbs.getAttribute(mxbeanName, "NumDeadDataNodes") == 2);
        assertTrue((Integer) mbs.getAttribute(mxbeanName, "NumLiveDataNodes") == 0);
    } finally {
        if (cluster != null) {
            cluster.shutdown();
        }
    }
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

private void registerMbean() {
    ObjectName objectName = null;
    MBeanServer mBeanServer = null;
    try {//  w  w  w.j av  a2  s.c  om
        objectName = new ObjectName(KeystoreEditor.class.getName() + ":service=keystore");
        mBeanServer = ManagementFactory.getPlatformMBeanServer();
    } catch (MalformedObjectNameException e) {
        LOGGER.error("Unable to create Keystore Editor MBean.", e);
    }
    if (mBeanServer != null) {
        try {
            try {
                mBeanServer.registerMBean(this, objectName);
                LOGGER.info("Registered Keystore Editor MBean under object name: {}", objectName.toString());
            } catch (InstanceAlreadyExistsException e) {
                // Try to remove and re-register
                mBeanServer.unregisterMBean(objectName);
                mBeanServer.registerMBean(this, objectName);
                LOGGER.info("Re-registered Keystore Editor MBean");
            }
        } catch (Exception e) {
            LOGGER.error("Could not register MBean [{}].", objectName.toString(), e);
        }
    }
}