Wednesday, May 6, 2015

JMX client sample

This is a JMX client sample:

public class JmxTests {

  /**
   * Run with the following VM options:
   * -Dcom.sun.management.jmxremote.port=9999
   * -Dcom.sun.management.jmxremote.authenticate=false
   * -Dcom.sun.management.jmxremote.ssl=false
   *
   * @throws IOException
   */
  @Test
  public void test() throws IOException, MalformedObjectNameException, InstanceNotFoundException, MBeanException, AttributeNotFoundException, ReflectionException {
    echo("\nCreate an RMI connector client and "
        + "connect it to the RMI connector server");
//    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:9999/jmxrmi");
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://10.99.99.35:30001/jmxrmi");
    JMXConnector jmxc = JMXConnectorFactory.connect(url, null);

    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

    echo("\nDomains:");
    String domains[] = mbsc.getDomains();
    Arrays.sort(domains);
    for (String domain : domains) {
      echo("\tDomain = " + domain);
    }

    echo("\nMBeanServer default domain = " + mbsc.getDefaultDomain());

    echo("\nMBean count = " +  mbsc.getMBeanCount());
    echo("\nQuery MBeanServer MBeans:");
    Set<ObjectName> names = new TreeSet<ObjectName>(mbsc.queryNames(null, null));
    for (ObjectName name : names) {
      echo("\tObjectName = " + name);
    }

    ObjectName objectName = new ObjectName("java.lang:type=OperatingSystem");
    double systemLoadAverage = (double) mbsc.getAttribute(objectName, "SystemLoadAverage");
    System.out.println(systemLoadAverage);

    jmxc.close();
  }

  private void echo(String message) {
    System.out.println(message);
  }

}

References:
https://docs.oracle.com/javase/tutorial/jmx/remote/custom.html
http://docs.oracle.com/cd/E19226-01/821-0031/gcitw/index.html

No comments:

Post a Comment