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.apache.axis2.transport.base.AbstractTransportListener.java

private void unregisterMBean(String objectName) {
    try {//from  ww w  .  jav  a  2 s  .  c  o m
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName objName = new ObjectName(objectName);
        if (mbs.isRegistered(objName)) {
            mbs.unregisterMBean(objName);
        }
    } catch (Exception e) {
        log.warn("Error un-registering a MBean with objectname ' " + objectName + " ' for JMX management", e);
    }
}

From source file:com.webobjects.monitor.wotaskd.Application.java

/**
 * ============================================================================================
 *                  Methods Added for Enabling JMX in Wotaskd
 * ============================================================================================
 * This methods returns the platform MBean Server from the Factory
 * @return _mbeanServer  - The platform MBeanServer 
 *//*from  ww  w  .j av a 2s.  c o  m*/
@Override
public MBeanServer getMBeanServer() throws IllegalAccessException {
    if (_mbeanServer == null) {
        _mbeanServer = ManagementFactory.getPlatformMBeanServer();
        if (_mbeanServer == null)
            throw new IllegalAccessException(
                    "Error: PlatformMBeanServer could not be accessed via ManagementFactory.");
    }
    return _mbeanServer;
}

From source file:com.jkoolcloud.tnt4j.streams.custom.kafka.interceptors.reporters.metrics.MetricsReporter.java

/**
 * Collects Kafka producer domain {@code 'kafka.producer'} JMX attributes values.
 *
 * @param tracker/*from   w w w . j  av  a2  s.co  m*/
 *            tracker instance to use
 * @return activity containing snapshots of Kafka producer JMX attributes values
 *
 * @see #collectMetricsJMX(String, javax.management.MBeanServer, com.jkoolcloud.tnt4j.core.Activity)
 */
public TrackingActivity collectKafkaProducerMetricsJMX(Tracker tracker) {
    TrackingActivity activity = tracker.newActivity(OpLevel.INFO, "Kafka producer JMX metrics"); // NON-NLS

    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    try {
        collectMetricsJMX("kafka.producer:*", mBeanServer, activity); // NON-NLS
    } catch (Exception exc) {
        Utils.logThrowable(LOGGER, OpLevel.WARNING,
                StreamsResources.getBundle(KafkaStreamConstants.RESOURCE_BUNDLE_NAME),
                "MetricsReporter.producer.jmx.fail", exc);
    }
    return activity;
}

From source file:com.cubeia.firebase.server.lobby.systemstate.StateLobby.java

private MBeanServer getMBeanServer() {
    return ManagementFactory.getPlatformMBeanServer();
}

From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java

/**
 * Unregister MBeans loaded by the web application class loader
 *///from w  ww.  ja va2s  . c  o  m
protected void unregisterMBeans() {
    try {
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        final Set<ObjectName> allMBeanNames = mBeanServer.queryNames(new ObjectName("*:*"), null);
        for (ObjectName objectName : allMBeanNames) {
            try {
                final ClassLoader mBeanClassLoader = mBeanServer.getClassLoaderFor(objectName);
                if (isWebAppClassLoaderOrChild(mBeanClassLoader)) { // MBean loaded in web application
                    warn("MBean '" + objectName + "' was loaded in web application; unregistering");
                    mBeanServer.unregisterMBean(objectName);
                }
            } catch (Exception e) { // MBeanRegistrationException / InstanceNotFoundException
                error(e);
            }
        }
    } catch (Exception e) { // MalformedObjectNameException
        error(e);
    }
}

From source file:com.jkoolcloud.tnt4j.streams.custom.kafka.interceptors.reporters.metrics.MetricsReporter.java

/**
 * Collects JVM domain {@code 'java.lang'} JMX attributes values.
 *
 * @param tracker/*from ww w . jav  a  2s. com*/
 *            tracker instance to use
 * @return activity containing snapshots of JVM JMX attributes values
 *
 * @see #collectMetricsJMX(String, javax.management.MBeanServer, com.jkoolcloud.tnt4j.core.Activity)
 */
public TrackingActivity collectJVMMetricsJMX(Tracker tracker) {
    TrackingActivity activity = tracker.newActivity(OpLevel.INFO, "JVM JMX metrics"); // NON-NLS

    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    try {
        collectMetricsJMX("java.lang:*", mBeanServer, activity); // NON-NLS
    } catch (Exception exc) {
        Utils.logThrowable(LOGGER, OpLevel.WARNING,
                StreamsResources.getBundle(KafkaStreamConstants.RESOURCE_BUNDLE_NAME),
                "MetricsReporter.jvm.jmx.fail", exc);
    }
    return activity;
}

From source file:org.rhq.enterprise.server.system.SystemManagerBean.java

public void enableHibernateStatistics() {
    PersistenceUtility.enableHibernateStatistics(this.entityManager,
            ManagementFactory.getPlatformMBeanServer());
}

From source file:se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor.java

/** Unregister MBeans loaded by the web application class loader */
protected void unregisterMBeans() {
    try {/*w  w  w  . ja  v a 2  s.  c om*/
        JettyJMXRemover jettyJMXRemover = null;
        // If you enable jmx support in jetty 8 or 9  some mbeans (e.g. for the servletholder or sessionmanager) are instanciated in the web application thread 
        // and a reference to the WebappClassloader is stored in a private ObjectMBean._loader which is unfortunatly not the classloader that loaded the class.
        // So for unregisterMBeans to work even for the jetty mbeans we need to access the MBeanContainer class of the jetty container.  
        try {
            jettyJMXRemover = new JettyJMXRemover(getWebApplicationClassLoader());
        } catch (Exception ex) {
            error(ex);
        }

        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        final Set<ObjectName> allMBeanNames = mBeanServer.queryNames(new ObjectName("*:*"), null);
        for (ObjectName objectName : allMBeanNames) {
            try {
                if (jettyJMXRemover != null && jettyJMXRemover.unregisterJettyJMXBean(objectName)) {
                    continue;
                }
                final ClassLoader mBeanClassLoader = mBeanServer.getClassLoaderFor(objectName);
                if (isWebAppClassLoaderOrChild(mBeanClassLoader)) { // MBean loaded in web application
                    warn("MBean '" + objectName + "' was loaded in web application; unregistering");
                    mBeanServer.unregisterMBean(objectName);
                }
            } catch (Exception e) { // MBeanRegistrationException / InstanceNotFoundException
                error(e);
            }
        }
    } catch (Exception e) { // MalformedObjectNameException
        error(e);
    }
}

From source file:de.tudarmstadt.lt.lm.app.StartLM.java

void startLM() {
    try {/*www.ja  v a 2  s  . c o m*/

        _providerService = getStringProviderInstance(_type_provider);

        _providerService.publish(_registry, _name, _port);

        File srcdir = new File(_srcdir);
        try {
            LOG.info("Loading '{}' languagemodel from '{}'... ", _type_lm, srcdir.getAbsolutePath());
            long begin_ms = System.currentTimeMillis();
            LanguageModel<String> lm = getLanguageModelInstance(_type_lm, _providerService, srcdir, _n,
                    _mincount, _discount, _overwrite);

            _providerService.setLanguageModel(lm);

            long end_ms = System.currentTimeMillis();
            long duration_ms = end_ms - begin_ms;
            long duration_s = duration_ms / 1000;
            String duration_str = String.format("%04dh:%02dm:%02ds", duration_s / 3600,
                    (duration_s % 3600) / 60, (duration_s % 60));
            LOG.info("... finished loading language model {}. Took {}.", _name, duration_str);
        } catch (Exception e) {
            e.printStackTrace();
            LOG.error("{}: {}", e.getClass(), e.getMessage(), e);
            try {
                _registry.unbind(_name);
            } catch (Exception e1) {
                /* handle silently */
            }
            CliUtils.print_usage_quit(System.err, StartLM.class.getSimpleName(), null, USAGE_HEADER,
                    String.format("%s: %s%n", e.getClass().getName(), e.getMessage()), 1);
        }

        if (_mbs == null)
            _mbs = ManagementFactory.getPlatformMBeanServer();
        _mbs.registerMBean(_providerService, _providerJmxBeanName);

    } catch (Exception e) {
        LOG.error("Could not start language model server. {}: {}", e.getClass(), e.getMessage());
        try {
            _registry.unbind(_name);
        } catch (Exception e1) {
            /* handle silently */
        }
        _providerService = null;
        CliUtils.print_usage_quit(System.err, StartLM.class.getSimpleName(), null, USAGE_HEADER,
                String.format("%s: %s%n", e.getClass().getName(), e.getMessage()), 1);
    }

    _overwrite = false;

}

From source file:org.springframework.ldap.config.LdapTemplateNamespaceHandlerTest.java

@Test
public void verifyParsePooling2Defaults() {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
            "/ldap-namespace-config-pooling2-defaults.xml");

    ContextSource outerContextSource = ctx.getBean(ContextSource.class);
    assertThat(outerContextSource).isNotNull();
    assertThat(outerContextSource instanceof TransactionAwareContextSourceProxy).isTrue();

    ContextSource pooledContextSource = ((TransactionAwareContextSourceProxy) outerContextSource).getTarget();
    assertThat(pooledContextSource).isNotNull();
    assertThat(pooledContextSource instanceof PooledContextSource).isTrue();
    assertThat(getInternalState(pooledContextSource, "poolConfig")).isNotNull();

    Object objectFactory = getInternalState(pooledContextSource, "dirContextPooledObjectFactory");
    assertThat(getInternalState(objectFactory, "contextSource")).isNotNull();
    assertThat(getInternalState(objectFactory, "dirContextValidator")).isNull();
    Set<Class<? extends Throwable>> nonTransientExceptions = (Set<Class<? extends Throwable>>) getInternalState(
            objectFactory, "nonTransientExceptions");
    assertThat(nonTransientExceptions).hasSize(1);
    assertThat(nonTransientExceptions.contains(CommunicationException.class)).isTrue();

    org.apache.commons.pool2.impl.GenericKeyedObjectPool objectPool = (org.apache.commons.pool2.impl.GenericKeyedObjectPool) getInternalState(
            pooledContextSource, "keyedObjectPool");
    assertThat(objectPool.getMaxIdlePerKey()).isEqualTo(8);
    assertThat(objectPool.getMaxTotal()).isEqualTo(-1);
    assertThat(objectPool.getMaxTotalPerKey()).isEqualTo(8);
    assertThat(objectPool.getMinIdlePerKey()).isEqualTo(0);
    assertThat(objectPool.getBlockWhenExhausted()).isEqualTo(true);
    assertThat(objectPool.getEvictionPolicyClassName())
            .isEqualTo(GenericKeyedObjectPoolConfig.DEFAULT_EVICTION_POLICY_CLASS_NAME);
    assertThat(objectPool.getFairness()).isEqualTo(false);

    // ensures the pool is registered
    ObjectName oname = objectPool.getJmxName();
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    Set<ObjectName> result = mbs.queryNames(oname, null);
    assertThat(result).hasSize(1);/*from  w w w  . j  a va2 s. c  o  m*/

    assertThat(objectPool.getLifo()).isEqualTo(true);
    assertThat(objectPool.getMaxWaitMillis()).isEqualTo(-1L);
    assertThat(objectPool.getMinEvictableIdleTimeMillis()).isEqualTo(1000L * 60L * 30L);
    assertThat(objectPool.getNumTestsPerEvictionRun()).isEqualTo(3);
    assertThat(objectPool.getSoftMinEvictableIdleTimeMillis()).isEqualTo(-1L);
    assertThat(objectPool.getTimeBetweenEvictionRunsMillis()).isEqualTo(-1L);
    assertThat(objectPool.getTestOnBorrow()).isEqualTo(false);
    assertThat(objectPool.getTestOnCreate()).isEqualTo(false);
    assertThat(objectPool.getTestOnReturn()).isEqualTo(false);
    assertThat(objectPool.getTestWhileIdle()).isEqualTo(false);
}