Example usage for javax.management MBeanServer registerMBean

List of usage examples for javax.management MBeanServer registerMBean

Introduction

In this page you can find the example usage for javax.management MBeanServer registerMBean.

Prototype

public ObjectInstance registerMBean(Object object, ObjectName name)
        throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException;

Source Link

Document

Registers a pre-existing object as an MBean with the MBean server.

Usage

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

/**
 * Add MBean info to JMX.//from   w  w w.j av  a  2 s  .  com
 * Will be called from the constructor.
 *
 */
private void initJmx() {
    try {
        MBeanServer mbs = getMBeanServer();
        ObjectName monitorName = new ObjectName("com.cubeia.firebase.lobby:type=SysLobby");
        if (!mbs.isRegistered(monitorName)) {
            mbs.registerMBean(this, monitorName);
        }
    } catch (Exception e) {
        log.error("failed to start JMX for State Lobby", e);
    }
}

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

private void registerMbean() {
    ObjectName objectName = null;
    MBeanServer mBeanServer = null;
    try {/*w  ww.j av  a  2s . c o  m*/
        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);
        }
    }
}

From source file:com.mustardgrain.solr.SolrClient.java

private void registerMBean() {
    String name = getClass().getPackage().getName() + ":type=" + getClass().getSimpleName() + "-"
            + objectNameIdCounter.incrementAndGet();

    try {//from  w w w.  j a v a2 s.  com
        objectName = new ObjectName(name);
        name = objectName.toString();
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        mbs.registerMBean(this, new ObjectName(name));

        if (LOG.isInfoEnabled())
            LOG.info("Registered " + objectName);
    } catch (Exception e) {
        if (LOG.isWarnEnabled())
            LOG.warn("Couldn't add MBean " + name);
    }
}

From source file:org.red5.server.undertow.UndertowLoader.java

protected void registerJMX() {
    // register with jmx
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    try {//from w w w  .jav  a 2  s .  co m
        ObjectName oName = new ObjectName("org.red5.server:type=UndertowLoader");
        // check for existing registration before registering
        if (!mbs.isRegistered(oName)) {
            mbs.registerMBean(this, oName);
        } else {
            log.debug("ContextLoader is already registered in JMX");
        }
    } catch (Exception e) {
        log.warn("Error on jmx registration", e);
    }
}

From source file:com.espertech.esper.example.servershell.ServerShellMain.java

public ServerShellMain() throws Exception {
    log.info("Loading properties");
    Properties properties = new Properties();
    InputStream propertiesIS = ServerShellMain.class.getClassLoader()
            .getResourceAsStream(ServerShellConstants.CONFIG_FILENAME);
    if (propertiesIS == null) {
        throw new RuntimeException(
                "Properties file '" + ServerShellConstants.CONFIG_FILENAME + "' not found in classpath");
    }// w ww.  ja v  a2  s  .c o m
    properties.load(propertiesIS);

    // Start RMI registry
    log.info("Starting RMI registry");
    int port = Integer.parseInt(properties.getProperty(ServerShellConstants.MGMT_RMI_PORT));
    LocateRegistry.createRegistry(port);

    // Obtain MBean servera
    log.info("Obtaining JMX server and connector");
    MBeanServer mbs = MBeanServerFactory.createMBeanServer();
    String jmxServiceURL = properties.getProperty(ServerShellConstants.MGMT_SERVICE_URL);
    JMXServiceURL jmxURL = new JMXServiceURL(jmxServiceURL);
    JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(jmxURL, null, mbs);
    cs.start();

    // Initialize engine
    log.info("Getting Esper engine instance");
    Configuration configuration = new Configuration();
    configuration.addEventType("SampleEvent", SampleEvent.class.getName());
    EPServiceProvider engine = EPServiceProviderManager.getDefaultProvider(configuration);

    // Initialize engine
    log.info("Creating sample statement");
    SampleStatement.createStatement(engine.getEPAdministrator());

    // Register MBean
    log.info("Registering MBean");
    ObjectName name = new ObjectName(ServerShellConstants.MGMT_MBEAN_NAME);
    EPServiceProviderJMX mbean = new EPServiceProviderJMX(engine);
    mbs.registerMBean(mbean, name);

    // Connect to JMS
    log.info("Connecting to JMS server");
    String factory = properties.getProperty(ServerShellConstants.JMS_CONTEXT_FACTORY);
    String jmsurl = properties.getProperty(ServerShellConstants.JMS_PROVIDER_URL);
    String connFactoryName = properties.getProperty(ServerShellConstants.JMS_CONNECTION_FACTORY_NAME);
    String user = properties.getProperty(ServerShellConstants.JMS_USERNAME);
    String password = properties.getProperty(ServerShellConstants.JMS_PASSWORD);
    String destination = properties.getProperty(ServerShellConstants.JMS_INCOMING_DESTINATION);
    boolean isTopic = Boolean.parseBoolean(properties.getProperty(ServerShellConstants.JMS_IS_TOPIC));
    JMSContext jmsCtx = JMSContextFactory.createContext(factory, jmsurl, connFactoryName, user, password,
            destination, isTopic);

    int numListeners = Integer.parseInt(properties.getProperty(ServerShellConstants.JMS_NUM_LISTENERS));
    log.info("Creating " + numListeners + " listeners to destination '" + destination + "'");

    SampleJMSMessageListener listeners[] = new SampleJMSMessageListener[numListeners];
    for (int i = 0; i < numListeners; i++) {
        listeners[i] = new SampleJMSMessageListener(engine.getEPRuntime());
        MessageConsumer consumer = jmsCtx.getSession().createConsumer(jmsCtx.getDestination());
        consumer.setMessageListener(listeners[i]);
    }

    // Start processing
    log.info("Starting JMS connection");
    jmsCtx.getConnection().start();

    // Register shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            isShutdown = true;
        }
    });

    // Report statistics
    long startTime = System.currentTimeMillis();
    long currTime;
    double deltaSeconds;
    int lastTotalEvents = 0;
    AccumulatingStat avgLast5 = new AccumulatingStat(5);
    AccumulatingStat avgLast10 = new AccumulatingStat(10);
    AccumulatingStat avgLast20 = new AccumulatingStat(20);
    do {
        // sleep
        Thread.sleep(1000);
        currTime = System.currentTimeMillis();
        deltaSeconds = (currTime - startTime) / 1000.0;

        // compute stats
        int totalEvents = 0;
        for (int i = 0; i < listeners.length; i++) {
            totalEvents += listeners[i].getCount();
        }

        double totalLastBatch = totalEvents - lastTotalEvents;

        avgLast5.add(totalLastBatch);
        avgLast10.add(totalLastBatch);
        avgLast20.add(totalLastBatch);

        log.info("total=" + totalEvents + " last=" + totalLastBatch + " last5Avg=" + avgLast5.getAvg()
                + " last10Avg=" + avgLast10.getAvg() + " last20Avg=" + avgLast20.getAvg() + " time="
                + deltaSeconds);
        lastTotalEvents = totalEvents;
    } while (!isShutdown);

    log.info("Shutting down server");
    jmsCtx.destroy();

    log.info("Exiting");
    System.exit(-1);
}

From source file:org.red5.server.stream.ClientBroadcastStream.java

protected void registerJMX() {
    if (registerJMX) {
        // register with jmx
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        try {/*w w  w  .j  a  va 2 s. c  o  m*/
            ObjectName oName = new ObjectName(
                    String.format("org.red5.server:type=ClientBroadcastStream,scope=%s,publishedName=%s",
                            getScope().getName(), publishedName));
            mbs.registerMBean(new StandardMBean(this, ClientBroadcastStreamMXBean.class, true), oName);
        } catch (InstanceAlreadyExistsException e) {
            log.debug("Instance already registered", e);
        } catch (Exception e) {
            log.warn("Error on jmx registration", e);
        }
    }
}

From source file:org.codice.ddf.ui.admin.api.ConfigurationAdminTest.java

/**
 * Tests the {@link ConfigurationAdmin#init()} method for the case where
 * an exception is thrown by mBeanServer.registerMBean(...)
 *
 * @throws Exception/*  w ww . j  a va2 s . c  o m*/
 */
@Test(expected = RuntimeException.class)
public void testInitException() throws Exception {
    org.osgi.service.cm.ConfigurationAdmin testConfigAdmin = mock(org.osgi.service.cm.ConfigurationAdmin.class);
    MBeanServer testServer = mock(MBeanServer.class);

    ConfigurationAdmin configAdmin = new ConfigurationAdmin(testConfigAdmin);

    configAdmin.setMBeanServer(testServer);
    when(testServer.registerMBean(any(Object.class), any(ObjectName.class)))
            .thenThrow(new NullPointerException());

    configAdmin.init();
}

From source file:org.codice.ddf.ui.admin.api.ConfigurationAdminTest.java

/**
 * Tests the {@link ConfigurationAdmin#init()} method for the case where
 * it has already been initialized// w w w  .  j av a 2  s .co  m
 *
 * @throws Exception
 */
@Test
public void testInitAlreadyExists() throws Exception {
    org.osgi.service.cm.ConfigurationAdmin testConfigAdmin = mock(org.osgi.service.cm.ConfigurationAdmin.class);
    MBeanServer testServer = mock(MBeanServer.class);

    ConfigurationAdmin configAdmin = new ConfigurationAdmin(testConfigAdmin);

    configAdmin.setMBeanServer(testServer);
    when(testServer.registerMBean(any(Object.class), any(ObjectName.class)))
            .thenThrow(new InstanceAlreadyExistsException()).thenReturn(null);

    configAdmin.init();

    verify(testServer, times(2)).registerMBean(any(Object.class), any(ObjectName.class));
    verify(testServer).unregisterMBean(any(ObjectName.class));
}

From source file:edu.umd.cs.buildServer.BuildServer.java

protected void configureBuildServerForMBeanManagement() {
    buildServerConfiguration = new BuildServerConfiguration();
    // Try to configure a BuildServerConfiguration object
    try {/*  w  ww . j a  v a2  s  .  co  m*/
        buildServerConfiguration.loadAllProperties(getConfig(), getLog());
        // Get MBeanServer
        MBeanServer platformMBeanserver = ManagementFactory.getPlatformMBeanServer();
        // Register the BuildServerMBean
        ObjectName buildServerName = new ObjectName("edu.umd.cs.buildServer:id=BuildServerManager");
        platformMBeanserver.registerMBean(buildServerConfiguration, buildServerName);
    } catch (MalformedObjectNameException e) {
        throw new RuntimeException(e);
    } catch (MBeanRegistrationException e) {
        throw new RuntimeException(e);
    } catch (NotCompliantMBeanException e) {
        throw new RuntimeException(e);
    } catch (InstanceAlreadyExistsException e) {
        throw new RuntimeException(e);
    } catch (MissingConfigurationPropertyException e) {
        // getLog().warn("Unable to configure (experimental) BuildServerConfiguration object");
        if (!isQuiet()) {
            System.out.println(e);
            e.printStackTrace();
        }

    }
}