Сейчас мы узнаем как легко подключится к нашему серверу(например Tomcat) через JMX в Java.

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

public class Tester {

public static void main(String[] args) {

String url = "service:jmx:rmi:///jndi/rmi://localhost:19999/jmxrmi"; // Link to connect
JMXServiceURL serviceUrl;
JMXConnector jmxConnector;
try {
serviceUrl = new JMXServiceURL(url);
Map env = new HashMap<>();
String[] credentials = {"controlRole", "tomcat"}; // Login and password
env.put(JMXConnector.CREDENTIALS, credentials);
jmxConnector = JMXConnectorFactory.connect(serviceUrl, env);
MBeanServerConnection mbeanConn = jmxConnector.getMBeanServerConnection();
ObjectName name = new ObjectName("java.lang:type=OperatingSystem");// MBean which we using

System.out.println(mbeanConn.getAttribute(name, "ProcessCpuTime"));// Attribute

} catch (IOException e) {

e.printStackTrace();
} catch (MalformedObjectNameException e) {

e.printStackTrace();
} catch (AttributeNotFoundException e) {

e.printStackTrace();
} catch (InstanceNotFoundException e) {

e.printStackTrace();
} catch (MBeanException e) {

e.printStackTrace();
} catch (ReflectionException e) {

e.printStackTrace();

}
}

}