[Gukulkan]

Learn, develop, play.

Java JMX Authentication and Authorization

Here is shot example about Authentication and Authorization in JMX Java code

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();

}
}

}

Config JMX in Tomcat

To make enable JMX in Tomcat edit startup.but file and add following line


set "CATALINA_OPTS=-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=%my.jmx.port% -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false"