Tuesday, October 20, 2009

JMX component for Tomcat

Last few weeks I faced with task to create JMX component for Java EE application deployed to Tomcat application server. It seemed to be easy task to do, although pure Tomcat do not include nice to use instruments for this.
Creating custom MBean for Tomcat (management bean) require a lot of tricky stuff to do. See [3] for details

The solution came from Apache Common Modeler API. They allow to create, configure etc model MBeans
With this API it cost me 150 lines to deal with JMX for Tomcat

The centric class of Modeler is Registry. Init spike of code looks like

// create the registry
registry = null;
try {
URL url = this.getClass().getResource("mbeans-descriptors.xml");
log.info("Load mbeans descriptors from: " + url);
registry = Registry.getRegistry(null, null);
registry.loadMetadata(url);
mBeanServer = registry.getMBeanServer();
}
catch (Exception e) {
log.error("Problems creating JMX registry: " + e.getMessage());


All you need to do next - just register custom JMX component

ObjectName oName = new ObjectName("JMX notation component name");
registry.registerComponent(getJmxComponentOjectInstace(), oName, getJmxComponentOjectInstace().getClass()
.toString());


After that you are welcome to use standard JMX API to manage MBean:
To set attribute
ObjectName oName = new ObjectName(getJmxComponentObjectName());
mBeanServer.setAttribute(oName, new Attribute(attrName, attrValue)


To get attribute
oName = new ObjectName(getJmxComponentObjectName());
return mBeanServer.getAttribute(oName, attrName);


To invoke an operation
oName = new ObjectName(getJmxComponentObjectName());
mBeanServer.invoke(oName, operationName, null, null);


Full version of JMX component is available here

References
  1. http://www.devx.com/Java/Article/21726/1763/page/1
  2. http://www.javaworld.com/javaworld/jw-06-2005/jw-0606-commons.html?page=1
  3. http://oss.wxnet.org/mbeans.html
  4. http://blog.eorlovsky.dp.ua/jmx.rar
  5. http://commons.apache.org/modeler

0 comments: