Accessing Jboss JMX programmatically


The next example will explain how to retrieve attributes from the JMX console via java.

The reason why you want to access the JMX console would be the need of having values which you wont be able to retrieve via the common API.

For example if we want to get the current subscribers of a specific Topic/Queue resource for any purpose
we wont be able to get it via the common JMS API.

We need to access to the JMX(locally or remotely) and read the attribute we desire.

Some code:

An example of connecting to the JMX and accessing the current number of subscribers which listening to a Topic:

public static int getCurrentTopicSubscribers()

		//use this code when you are connecting remotely(outside the jboss container).
//			Hashtable ht = new Hashtable();
//			ht.put(Context.INITIAL_CONTEXT_FACTORY,
//					"org.jnp.interfaces.NamingContextFactory");
//			ht.put(Context.PROVIDER_URL, "localhost:1099");
//			ht.put(Context.SECURITY_PRINCIPAL, "admin");
//			ht.put(Context.SECURITY_CREDENTIALS, "admin");
//			System.out.println("nt 1- Gotting InitialContext...... ");
//			Context ctx = new InitialContext(ht);

                       //(Connection within the jboss container)
		 MBeanServer server = (MBeanServer) MBeanServerFactory.findMBeanServer(null).get(0);
			server = (MBeanServerConnection) ctx.lookup("jmx/invoker/RMIAdaptor");
			if (server != null)
				log.error("Couldnt connect to JMX server");
		catch (Exception e)
			log.error("Couldnt connect to JMX server");

After we have connection we can easily retrieve the attributes from the JMX:

public static void monitorJMS() throws Exception
		ObjectName objectName = new ObjectName(
		System.out.println("DurableMessageCount = "
				+ (Integer) server.getAttribute(objectName, new String("DurableMessageCount")));
		System.out.println("AllSubscriptionsCount = "
				+ (Integer) server
						.getAttribute(objectName, new String("AllSubscriptionsCount")));


Related Articles: