Query JMX programmatically in JBoss and Tomcat
Rewrite for EAP6 https://access.redhat.com/kb/docs/DOC-49209 How do I query JMX programmatically in JBoss and Tomcat? Article ID: 49209 - Created on: May 25, 2010 1:59 AM - Last Modified: Apr 1, 2011 12:56 PM Issue How to query JMX by ObjectName in JBoss? I want to query port and protocol attributes of all Tomcat Connectors. I would like to monitor the invocation statistics on my Servlets and JSPs. Environment JBoss Enterprise Application Platform (EAP) 5 Resolution You can use the MBeanServer#queryNames() method: http://download.oracle.com/javase/6/docs/api/javax/management/MBeanServer.html#queryMBeans%28javax.management.ObjectName ,%20javax.management.QueryExp JBoss EAP Here is an example written in beanshell: [mbeanquery.bsh] import javax.management.MBeanServer; import javax.management.ObjectName; import org.jboss.mx.util.MBeanServerLocator; MBeanServer server = MBeanServerLocator.locateJBoss(); objectName = ObjectName.getInstance("jboss.web:type=Connector,*"); set = server.queryNames(objectName, null); for (it = set.iterator(); it.hasNext(); ) { print(it.next()); } Tomcat An example of retreiving the errorCount from the Replicated Counter servlet: import javax.management.MBeanServer; import javax.management.ObjectName; import org.jboss.mx.util.MBeanServerLocator; Map env = new HashMap(); env.put( JMXConnector.CREDENTIALS, new String[]{"user","pass"} ); JMXServiceURL address = new JMXServiceURL("service:rmi:///jndi/rmi://host:port/jmxrmi"); JMXConnector connector = JMXConnectorFactory.connect(address,env); MBeanServerConnection mbs = connector.getMBeanServerConnection(); int errorCount = ((Integer)mbs.getAttribute( "Catalina:j2eeType=Servlet,name=CounterServlet,WebModule=//localhost/counter,J2EEApplication=none,J2EEServer=none", "errorCount")).intValue(); System.out.println(" Error Count = " + errorCount); Monitoring Servlets and JSPs Note that Servlets can be monitored very easily for invocation statistics like requestCount and errorCount as they are mapped automatically via an MBean in the jmx-console. See the above example. With straight JSPs however, those will not show up in the jmx-console. To monitor those, you must precompile them, then they will be available as MBeans to access and pull stats from. For precompiling JSPs see How do I precompile JSP's?