Example usage for javax.management MBeanServerFactory createMBeanServer

List of usage examples for javax.management MBeanServerFactory createMBeanServer

Introduction

In this page you can find the example usage for javax.management MBeanServerFactory createMBeanServer.

Prototype

public static MBeanServer createMBeanServer() 

Source Link

Document

Return a new object implementing the MBeanServer interface with a standard default domain name.

Usage

From source file:com.tomcat.monitor.jmx.obj.bean.MServer.java

/**
 * Zugriff zu dem lokalen Platform Server oder erzeuge neuen.
 *///from   ww w.  j  a  v a2  s.  c o m
protected MBeanServer getMBeanServer() {
    MBeanServer server;
    server = ManagementFactory.getPlatformMBeanServer();
    if (server == null)
        server = MBeanServerFactory.createMBeanServer();
    return (server);
}

From source file:com.flexive.shared.mbeans.MBeanHelper.java

private static List<MBeanServer> findMBeanServers() {
    final ArrayList<MBeanServer> servers = MBeanServerFactory.findMBeanServer(null);
    if (servers.isEmpty()) {
        LOG.error("No active JMX MBean servers found - creating a new one");
        servers.add(MBeanServerFactory.createMBeanServer());
    }/*from   ww  w .  ja v a  2  s .co m*/
    return servers;
}

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");
    }//from  w w w  .  ja v  a 2s .  c om
    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:fedorax.server.module.storage.IrodsExternalContentManager.java

@SuppressWarnings("unused")
private MBeanServer getMBeanServer() {
    MBeanServer mbserver = null;//from w  w w.ja  v  a  2  s  .c  o  m
    ArrayList<MBeanServer> mbservers = MBeanServerFactory.findMBeanServer(null);

    if (mbservers.size() > 0) {
        mbserver = (MBeanServer) mbservers.get(0);
    }

    if (mbserver != null) {
        System.out.println("Found our MBean server");
    } else {
        mbserver = MBeanServerFactory.createMBeanServer();
    }

    return mbserver;
}

From source file:org.kjkoster.zapcat.test.ZabbixAgentProtocolTest.java

@Test
public void testMultiAgent() throws Exception {
    ZabbixAgent agent1;//from  www .j  av  a2 s  . c  o  m
    {
        MBeanServer mbeanServer = MBeanServerFactory.createMBeanServer();
        agent1 = new ZabbixAgent(InetAddress.getLocalHost(), 1098);
        agent1.setMbeanServer(mbeanServer);

        MBeanExporter exporter = new MBeanExporter();
        exporter.setServer(agent1.getMbeanServer());

        Monitor monitor = MonitorFactory.getMonitor("monitor1", "");
        monitor.setHits(1);
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("test:name=monitor", monitor);
        exporter.setBeans(map);

        exporter.afterPropertiesSet();
    }
    ZabbixAgent agent2;
    {
        MBeanServer mbeanServer = MBeanServerFactory.createMBeanServer();
        agent2 = new ZabbixAgent(InetAddress.getLocalHost(), 1099);
        agent2.setMbeanServer(mbeanServer);

        MBeanExporter exporter = new MBeanExporter();
        exporter.setServer(agent2.getMbeanServer());

        Monitor monitor = MonitorFactory.getMonitor("monitor2", "");
        monitor.setHits(2);
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("test:name=monitor", monitor);
        exporter.setBeans(map);

        exporter.afterPropertiesSet();
    }

    Thread.sleep(1000);
    query(1098, "jmx[\"test:name=monitor\",\"Hits\"]", new byte[] { '1' });
    query(1099, "jmx[\"test:name=monitor\",\"Hits\"]", new byte[] { '2' });

    agent1.stop();
    agent2.stop();
}

From source file:org.acmsl.commons.utils.jmx.MBeanRegistrator.java

/**
 * Obtains a reference to the MBean server. If at least one
 * MBean server already exists, then a reference to that MBean
 * server is returned. Otherwise a new instance is created.
 * @param cachedInstance the cached instance, if any.
 * @return such server.//  w ww .j  av  a2 s.  c o  m
 */
@Nullable
protected MBeanServer getMBeanServer(@Nullable final MBeanServer cachedInstance) {
    MBeanServer result = cachedInstance;

    if (result == null) {
        @NotNull
        final List<MBeanServer> mbeanServers = MBeanServerFactory.findMBeanServer(null);

        @NotNull
        final Iterator<MBeanServer> serverIterator = mbeanServers.iterator();

        while (serverIterator.hasNext()) {
            @NotNull
            final MBeanServer mbeanServer = serverIterator.next();

            mbeanServer.queryMBeans(null, null);
        }

        result = (mbeanServers.size() > 0) ? mbeanServers.get(0) : MBeanServerFactory.createMBeanServer();

        setMBeanServer(result);
    }

    return result;
}

From source file:org.apache.jk.common.JkMX.java

MBeanServer getMBeanServer() {
    MBeanServer server;/*from  ww  w  . j av a 2 s  . c  o m*/
    if (MBeanServerFactory.findMBeanServer(null).size() > 0) {
        server = (MBeanServer) MBeanServerFactory.findMBeanServer(null).get(0);
    } else {
        server = MBeanServerFactory.createMBeanServer();
    }
    return (server);
}

From source file:org.apache.tomcat.util.mx.DynamicMBeanProxy.java

public static MBeanServer getMBeanServer() {
    if (mserver == null) {
        if (MBeanServerFactory.findMBeanServer(null).size() > 0) {
            mserver = (MBeanServer) MBeanServerFactory.findMBeanServer(null).get(0);
        } else {/*  w w  w  .ja  v  a 2  s  . c o  m*/
            mserver = MBeanServerFactory.createMBeanServer();
        }
    }

    return mserver;
}

From source file:org.chorusbdd.chorus.tools.webagent.JmxManagementServerExporter.java

public void startServer() throws Exception {

    // Ensure cryptographically strong random number generator used
    // to choose the object number - see java.rmi.server.ObjID
    ////from w  w  w  .  jav  a2 s.  c o m
    //System.setProperty("java.rmi.server.randomIDs", "true");

    // Start an RMI registry on port 3000.
    //
    if (!registriesCreated.contains(port)) {
        log.info("Creating RMI registry on port " + port);
        LocateRegistry.createRegistry(port);
        registriesCreated.add(port);
    } else {
        //there's no way to shut it dnwn? So if we run a sequence of tests we clean up by unexporting the
        //listener object, and have to reuse the registry instance
        log.info("RMI registry was already running on port " + port);
    }

    // Retrieve the PlatformMBeanServer.
    //
    log.info(usePlatformMBeanServer ? "Using Platform MBean Server" : "Creating the MBean server");
    mBeanServer = usePlatformMBeanServer ? ManagementFactory.getPlatformMBeanServer()
            : MBeanServerFactory.createMBeanServer();

    // Environment map.
    //
    log.info("Initialize the environment map");
    HashMap<String, Object> env = new HashMap<String, Object>();

    // Provide SSL-based RMI socket factories.
    //
    // The protocol and cipher suites to be enabled will be the ones
    // defined by the default JSSE implementation and only server
    // authentication will be required.
    //
    //SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory();
    //SslRMIServerSocketFactory ssf = new SslRMIServerSocketFactory();
    //env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf);
    //env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, ssf);

    // Provide the password file used by the connector server to
    // perform user authentication. The password file is a properties
    // based text file specifying username/password pairs.
    //
    //env.put("jmx.remote.x.password.file", "password.properties");

    // Provide the access level file used by the connector server to
    // perform user authorization. The access level file is a properties
    // based text file specifying username/access level pairs where
    // access level is either "readonly" or "readwrite" access to the
    // MBeanServer operations.
    //
    //env.put("jmx.remote.x.access.file", "access.properties");

    // Create an RMI connector server.
    //
    // As specified in the JMXServiceURL the RMIServer stub will be
    // registered in the RMI registry running in the local host on
    // port 3000 with the name "jmxrmi". This is the same name the
    // out-of-the-box management agent uses to register the RMIServer
    // stub too.
    //
    log.info("Create an RMI connector server");
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:" + port + "/jmxrmi");
    jmxConnectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mBeanServer);

    // Start the RMI connector server.
    //
    log.info("Start the JMX connector server on port " + port);
    jmxConnectorServer.start();
}

From source file:org.jboss.web.tomcat.tc5.session.JBossCacheCluster.java

/**
 * Get the current Catalina MBean Server.
 * /*from   ww  w.j ava 2 s.c  om*/
 * @return
 * @throws Exception
 */
private MBeanServer getMBeanServer() throws Exception {
    if (mserver == null) {
        ArrayList servers = MBeanServerFactory.findMBeanServer(null);
        if (servers.size() > 0) {
            mserver = (MBeanServer) servers.get(0);
        } else {
            mserver = MBeanServerFactory.createMBeanServer();
        }
    }
    return mserver;
}