Monday, September 10, 2012

QuickTip: Programmatic MBean access under JBoss

I have been struggeling a bit with the programmatic access of MBeans under JBoss. This is my current conclusion.
With JBoss 5 there are two methods for accessing MBeans:
  • By JNDI-lookup of the RMIAdaptor. With this method you need the JBoss client libraries (the jars in your $JBOSS_HOME/client) on the classpath since the RMIAdaptor is a type that is provided by JBoss.
  • By pure JMX. You don't need the JBoss client libraries your class path here. 

The following snipped shows both methods:
public static void main(String[] args) throws Exception {
System.out.println("Starting lookup ...");
ObjectName mBeanName = new ObjectName("jboss.system:type=Server");
String attributeName = "StartDate";
String host = "localhost";
int jndiPort = 1099;
int jmxPort = 1090;
// First method: Get MBean via RMIAdaptor
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
p.put(Context.PROVIDER_URL, host + ":" + jndiPort);
InitialContext ctx = new InitialContext(p);
RMIAdaptor rmiAdaptor = (RMIAdaptor) ctx.lookup("jmx/rmi/RMIAdaptor");
System.out.println("Value via RMI:" + rmiAdaptor.getAttribute(mBeanName, attributeName));
// Second method: Get MBean via JMX
String serviceURL = "service:jmx:rmi:///jndi/rmi://" + host + ":" + jmxPort + "/jmxconnector";
JMXServiceURL jmxUrl = new JMXServiceURL(serviceURL);
JMXConnector jmxCon = JMXConnectorFactory.connect(jmxUrl);
MBeanServerConnection connection = jmxCon.getMBeanServerConnection();
System.out.println("Value via JMX: " + connection.getAttribute(mBeanName ,attributeName));
}

With JBoss 7 the way to access MBeans changed quite a bit:
public static void main(String[] args) throws Exception {
System.out.println("Starting lookup ...");
ObjectName mBeanName = new ObjectName("java.lang:type=Runtime");
String attributeName = "StartTime";
String host = "localhost";
int port = 9999; // management-native port
String urlString = System.getProperty("jmx.service.url","service:jmx:remoting-jmx://" + host + ":" + port);
JMXServiceURL serviceURL = new JMXServiceURL(urlString);
JMXConnector jmxConnector = JMXConnectorFactory.connect(serviceURL, null);
MBeanServerConnection connection = jmxConnector.getMBeanServerConnection();
Object attrVal = connection.getAttribute(mBeanName, attributeName);
System.out.println("Value via JMX: " + new Date((Long) attrVal));
}
The tricky thing here is, that you need the JBoss client libraries (the jars in $JBOSS_HOME/bin/client) on your classpath even though you don't explicitly import types provided by JBoss.

If the client libraries are missing, you get the following exception: java.net.MalformedURLException: Unsupported protocol: remoting-jmx

As far as I could figure, this is the only way to access MBeans under JBoss 7.
Related Posts Plugin for WordPress, Blogger...