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:org.jahia.services.cache.ehcache.EhCacheProvider.java

public void init(SettingsBean settingsBean, CacheService cacheService) throws JahiaInitializationException {
    if (initialized) {
        return;/*from  w  ww. j  a  v  a2  s. c om*/
    }
    cacheManager = CacheManager.create(getClass().getResource(configurationResource));
    if (jmxActivated) {
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        ManagementService.registerMBeans(cacheManager, mBeanServer, true, true, true, true, true);
    }
    initialized = true;
}

From source file:org.sakaiproject.search.mbeans.SearchServiceManagement.java

/**
 * // w  ww . j  av  a2s  .  c o  m
 */
public void init() {
    try {

        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

        final ObjectName searchServiceON = new ObjectName(MBEAN_COMPONENT_BASE + name);
        mbs.registerMBean(this, searchServiceON);

        indexStorageProvider.addIndexListener(new IndexListener() {

            public void doIndexReaderClose(IndexReader oldMultiReader) throws IOException {
                sendNotification(new Notification("index-reader-close", searchServiceON, notificationNo++,
                        "Closed oldMultiReader"));
            }

            public void doIndexReaderOpen(IndexReader newMultiReader) {
                sendNotification(new Notification("index-reader-open", searchServiceON, notificationNo++,
                        "Opened newMultiReader"));
            }

            public void doIndexSearcherClose(IndexSearcher indexSearcher) throws IOException {
                sendNotification(new Notification("index-searcher-close", searchServiceON, notificationNo++,
                        "Closed " + indexSearcher.toString()));

            }

            public void doIndexSearcherOpen(IndexSearcher indexSearcher) {
                sendNotification(new Notification("index-searcher-open", searchServiceON, notificationNo++,
                        "Opened " + indexSearcher.toString()));
            }

        });

        indexWorker.addIndexWorkerDocumentListener(new IndexWorkerDocumentListener() {

            public void indexDocumentEnd(IndexWorker worker, String ref) {
                sendNotification(new Notification("index-document-start", searchServiceON, notificationNo++,
                        "Doc Ref " + ref));
            }

            public void indexDocumentStart(IndexWorker worker, String ref) {
                sendNotification(new Notification("index-document-end", searchServiceON, notificationNo++,
                        "Doc Ref " + ref));
            }

        });

        indexWorker.addIndexWorkerListener(new IndexWorkerListener() {

            public void indexWorkerEnd(IndexWorker worker) {
                sendNotification(new Notification("index-woker-start", searchServiceON, notificationNo++,
                        "Worker " + worker));

            }

            public void indexWorkerStart(IndexWorker worker) {
                sendNotification(new Notification("index-woker-end", searchServiceON, notificationNo++,
                        "Worker " + worker));
            }

        });

    } catch (Exception ex) {
        log.warn("Failed to register mbean for search service ", ex);

    }

}

From source file:fi.helsinki.opintoni.config.MetricsConfiguration.java

@PostConstruct
public void init() {
    log.debug("Registering JVM gauges");
    metricRegistry.register(PROP_METRIC_REG_JVM_MEMORY, new MemoryUsageGaugeSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_GARBAGE, new GarbageCollectorMetricSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_THREADS, new ThreadStatesGaugeSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_FILES, new FileDescriptorRatioGauge());
    metricRegistry.register(PROP_METRIC_REG_JVM_BUFFERS,
            new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer()));
    if (propertyResolver.getProperty(PROP_JMX_ENABLED, Boolean.class, false)) {
        log.info("Initializing Metrics JMX reporting");
        JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build();
        jmxReporter.start();/*from w  w  w .jav  a 2s .c om*/
    }
}

From source file:uk.co.gidley.jmxmonitor.services.InternalJmxTest.java

@Test
public void testStartupShutdown()
        throws MalformedObjectNameException, InitialisationException, ConfigurationException {

    MainConfiguration mainConfiguration = mock(MainConfiguration.class);
    RegistryShutdownHub registryShutdownHub = mock(RegistryShutdownHub.class);

    Configuration configuration = new PropertiesConfiguration(
            "src/test/resources/jmxLocalMonitoringTestConfiguration.properties");
    when(mainConfiguration.getConfiguration()).thenReturn(configuration);

    InternalJmx internalJmx = new InternalJmx(mainConfiguration, registryShutdownHub);

    verify(registryShutdownHub).addRegistryShutdownListener(internalJmx);

    // Internal JMX should now be not running

    try {//from w w w .  j  a v a  2 s  . co  m
        ManagementFactory.getPlatformMBeanServer().getObjectInstance(internalJmx.getConnectorServerName());
    } catch (InstanceNotFoundException e) {
        assertThat("Exception should not have thrown", false);
    }

    try {
        JMXServiceURL serviceUrl = new JMXServiceURL(configuration.getString("jmxmonitor.localJmx"));
        JMXConnector jmxc = JMXConnectorFactory.connect(serviceUrl, null);
        MBeanServerConnection mBeanServerConnection = jmxc.getMBeanServerConnection();
        assertThat(mBeanServerConnection, notNullValue());
    } catch (IOException e) {
        assertThat("Exception should not have thrown", false);
    }

    // Fire shutdown anyhow
    internalJmx.registryDidShutdown();

    // Check JMX actually closed
    try {
        ManagementFactory.getPlatformMBeanServer().getObjectInstance(internalJmx.getConnectorServerName());
        assertThat("Exception should have thrown", false);
    } catch (InstanceNotFoundException e) {

    }

    try {
        JMXServiceURL serviceUrl = new JMXServiceURL(configuration.getString("jmxmonitor.localJmx"));
        JMXConnector jmxc = JMXConnectorFactory.connect(serviceUrl, null);
        MBeanServerConnection mBeanServerConnection = jmxc.getMBeanServerConnection();
        assertThat("Exception should have thrown", false);
    } catch (IOException e) {

    }

}

From source file:org.nuxeo.runtime.tomcat.NuxeoLauncher.java

protected void handleEvent(NuxeoWebappLoader loader, LifecycleEvent event) {
    String type = event.getType();
    try {/*from   w  ww  .  j  av a 2 s  .  co  m*/
        MutableClassLoader cl = (MutableClassLoader) loader.getClassLoader();
        boolean devMode = cl instanceof NuxeoDevWebappClassLoader;
        if (type == Lifecycle.CONFIGURE_START_EVENT) {
            File homeDir = resolveHomeDirectory(loader);
            if (devMode) {
                bootstrap = new DevFrameworkBootstrap(cl, homeDir);
                MBeanServer server = ManagementFactory.getPlatformMBeanServer();
                server.registerMBean(bootstrap, new ObjectName(DEV_BUNDLES_NAME));
                server.registerMBean(cl, new ObjectName(WEB_RESOURCES_NAME));
                ((NuxeoDevWebappClassLoader) cl).setBootstrap((DevFrameworkBootstrap) bootstrap);
            } else {
                bootstrap = new FrameworkBootstrap(cl, homeDir);
            }
            bootstrap.setHostName("Tomcat");
            bootstrap.setHostVersion(ServerInfo.getServerNumber());
            bootstrap.initialize();
        } else if (type == Lifecycle.START_EVENT) {
            bootstrap.start();
        } else if (type == Lifecycle.STOP_EVENT) {
            bootstrap.stop();
            if (devMode) {
                MBeanServer server = ManagementFactory.getPlatformMBeanServer();
                server.unregisterMBean(new ObjectName(DEV_BUNDLES_NAME));
                server.unregisterMBean(new ObjectName(WEB_RESOURCES_NAME));
            }
        }
    } catch (IOException | JMException | ReflectiveOperationException e) {
        log.error("Failed to handle event: " + type, e);
    }
}

From source file:com.taobao.diamond.server.service.task.processor.UpdateConfigInfoTaskProcessor.java

public void init() {
    try {//from  w w  w  .  j a  v  a2s . c  o  m
        ObjectName oName = new ObjectName(UpdateConfigInfoTaskProcessor.class.getPackage().getName() + ":type="
                + UpdateConfigInfoTaskProcessor.class.getSimpleName());
        ManagementFactory.getPlatformMBeanServer().registerMBean(this, oName);
    } catch (Exception e) {
        log.error("mbean", e);
    }
}

From source file:com.btoddb.chronicle.catchers.RestCatcherImpl.java

private void startJettyServer() {
    QueuedThreadPool tp = new QueuedThreadPool(200, 8, 30000, new ArrayBlockingQueue<Runnable>(1000));
    tp.setName("Chronicle-RestV1-ThreadPool");

    server = new Server(tp);

    // Setup JMX - do this before setting *anything* else on the server object
    MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    server.addEventListener(mbContainer);
    server.addBean(mbContainer);//from  w ww . j  a va 2 s  .  c  om
    server.addBean(Log.getLogger(RestCatcherImpl.class));

    // bind connector to IP and port
    ServerConnector connector = new ServerConnector(server);
    connector.setHost(bind);
    connector.setPort(port);
    server.setConnectors(new Connector[] { connector });

    // setup handlers/stats for the context "/v1/events"
    HandlerCollection v1EventHandlers = new HandlerCollection();
    v1EventHandlers.addHandler(new RequestHandler());
    v1EventHandlers.addHandler(new DefaultHandler());
    StatisticsHandler statsHandler = new StatisticsHandler();
    statsHandler.setHandler(v1EventHandlers);

    ContextHandler context = new ContextHandler();
    context.setDisplayName("Chronicle-RestV1");
    context.setContextPath("/v1/events");
    context.setAllowNullPathInfo(true); // to avoid redirect on POST
    context.setHandler(statsHandler);

    // setup handlers/contexts for the overall server
    HandlerCollection serverHandlers = new HandlerCollection();
    serverHandlers.addHandler(context);
    server.setHandler(serverHandlers);
    server.addBean(new ErrorHandler() {
        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException {
            logger.warn(String.format("RESTv1 response code = %d : %s : forward-for=%s : %s",
                    baseRequest.getResponse().getStatus(), baseRequest.getRemoteAddr(),
                    baseRequest.getHeader("X-Forwarded-For"), baseRequest.getRequestURL()));
            super.handle(target, baseRequest, request, response);
        }
    });

    try {
        server.start();
        logger.info("jetty started and listening on port " + port);
    } catch (Exception e) {
        logger.error("exception while starting jetty server", e);
    }
}

From source file:org.opendaylight.infrautils.diagstatus.MBeanUtils.java

public static MBeanServer registerServerMBean(Object mxBeanImplementor, String objNameStr) throws JMException {

    LOG.debug("register MBean for {}", objNameStr);
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    try {/*from w  w  w . j  a v a 2 s . co m*/
        ObjectName objName = new ObjectName(objNameStr);
        mbs.registerMBean(mxBeanImplementor, objName);
        LOG.info("MBean registration for {} SUCCESSFUL.", objNameStr);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException
            | MalformedObjectNameException ex) {
        LOG.error("MBean registration for {} FAILED.", objNameStr, ex);
        throw ex;
    }
    return mbs;
}

From source file:org.springframework.boot.admin.SpringApplicationAdminMXBeanRegistrar.java

@Override
public void destroy() throws Exception {
    ManagementFactory.getPlatformMBeanServer().unregisterMBean(this.objectName);
}

From source file:org.apache.cassandra.utils.JMXServerUtils.java

/**
 * Creates a server programmatically. This allows us to set parameters which normally are
 * inaccessable./*from   w  w w .  ja  v a 2  s.  c o m*/
 */
public static JMXConnectorServer createJMXServer(int port, boolean local) throws IOException {
    Map<String, Object> env = new HashMap<>();

    String urlTemplate = "service:jmx:rmi://%1$s/jndi/rmi://%1$s:%2$d/jmxrmi";
    InetAddress serverAddress = null;
    if (local) {
        serverAddress = InetAddress.getLoopbackAddress();
        System.setProperty("java.rmi.server.hostname", serverAddress.getHostAddress());
    }

    // Configure the RMI client & server socket factories, including SSL config.
    env.putAll(configureJmxSocketFactories(serverAddress, local));

    // Configure authn, using a JMXAuthenticator which either wraps a set log LoginModules configured
    // via a JAAS configuration entry, or one which delegates to the standard file based authenticator.
    // Authn is disabled if com.sun.management.jmxremote.authenticate=false
    env.putAll(configureJmxAuthentication());

    // Configure authz - if a custom proxy class is specified an instance will be returned.
    // If not, but a location for the standard access file is set in system properties, the
    // return value is null, and an entry is added to the env map detailing that location
    // If neither method is specified, no access control is applied
    MBeanServerForwarder authzProxy = configureJmxAuthorization(env);

    // Make sure we use our custom exporter so a full GC doesn't get scheduled every
    // sun.rmi.dgc.server.gcInterval millis (default is 3600000ms/1 hour)
    env.put(RMIExporter.EXPORTER_ATTRIBUTE, new Exporter());

    String url = String.format(urlTemplate,
            (serverAddress != null ? serverAddress.getHostAddress() : "0.0.0.0"), port);

    int rmiPort = Integer.getInteger("com.sun.management.jmxremote.rmi.port", 0);
    JMXConnectorServer jmxServer = JMXConnectorServerFactory.newJMXConnectorServer(
            new JMXServiceURL("rmi", null, rmiPort), env, ManagementFactory.getPlatformMBeanServer());

    // If a custom authz proxy was created, attach it to the server now.
    if (authzProxy != null)
        jmxServer.setMBeanServerForwarder(authzProxy);

    jmxServer.start();

    // use a custom Registry to avoid having to interact with it internally using the remoting interface
    configureRMIRegistry(port, env);

    logger.info("Configured JMX server at: {}", url);
    return jmxServer;
}