Java client to connect JMX

Here is a sample to connect Tomcat JMX and display some server session status.

		try {
			JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/jmxrmi");
			JMXConnector jmxc = JMXConnectorFactory.connect(url);
		    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
		    ObjectName mbeanName = new ObjectName("Catalina:type=Manager,context=/,host=localhost");

		    Object value = mbsc.getAttribute(mbeanName, "activeSessions");
            System.out.println("activeSessions = " + value);

			String valueSessionIds = (String)mbsc.invoke(mbeanName, "listSessionIds", null, null);
			if (valueSessionIds != null) {
				StringTokenizer tokenizer = new StringTokenizer(valueSessionIds, " ");

				while (tokenizer.hasMoreTokens())
			    {
			       System.out.println("tokenizer = " + tokenizer.nextToken());
			    }
			}

		    jmxc.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}

If authentication is required, we add few lines to put on authentication credentials.

try {
    Map<String, String[]> env = new HashMap<>();
    String[] credentials = {"userA", "abc123"};
    env.put(JMXConnector.CREDENTIALS, credentials);
    
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/jmxrmi");
    JMXConnector jmxc = JMXConnectorFactory.connect(url, env);
    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
    ObjectName mbeanName = new ObjectName("Catalina:type=Manager,context=/,host=localhost");

    Object value = mbsc.getAttribute(mbeanName, "activeSessions");
    System.out.println("activeSessions = " + value);

    String valueSessionIds = (String)mbsc.invoke(mbeanName, "listSessionIds", null, null);
    if (valueSessionIds != null) {
        StringTokenizer tokenizer = new StringTokenizer(valueSessionIds, " ");

        while (tokenizer.hasMoreTokens())
        {
           System.out.println("tokenizer = " + tokenizer.nextToken());
        }
    }

    jmxc.close();
} catch (Exception ex) {
    ex.printStackTrace();
}

oliver

Leave a Reply

Your email address will not be published. Required fields are marked *


*