How to call an MBean method (JMX) within an EJB method in Jboss

Share on:

I am going to write this post, even though you can put together all the resources you need, just because I have gone through lots of forums and posts that have quite outdated info regarding this specific task I thought to write a small post, so it can be indexed in google!it's not rocket science as you can see, though you never know! (i am sorry blogspot really sucks when it comes to writing code samples)

What I wanted to do! I had implemented some JMX Services (Mbeans) deployed in my Application Server, Jboss 4.2.0RC1. I needed to invoke some certain methods, on these services within EJB code, actually it was a Stateless Session Bean.

My Mbean (JMX) (skip that if you all about Mbeans) I have used the classic way of implementing Mbeans

  • Defined a concrete class that is going to hold the actual implementation e.g. BatchWorker.java

  • The class above (BatchWorker)

  • extends ServiceMBeanSupport implements BatchWorkerMBean

  • Defined an Interface Called BatchWorkerMBean that

  • extends ServiceMBean

  • Deployed as a sar on my JBoss instance.

Where to look for examples Eventually all the info you need in order to accomplish your task is available on the extremely helpful JBoss Wiki. So head to JMX FAQ of JBoss wiki. The section below just follows the resources tips.

How to call the Mbean As it is indicated on the resources it is a multi step process.

  1. Locate and acquire a reference of the MbeanServer running on Jboss
  2. Create a proxy object of your actual Service
  3. Invoke the method

let's see (add code to do proper exception handling)

1//get a references of the MBeanServer of Jboss
2MBeanServer server=MBeanServerLocator.locateJBoss();
3//create an Objectname //watch out how you have configured your mbean it's domain and it's name!
4        ObjectName objectName=new Objectname("BatchWorker:name=BatchWorker");
5//get a proxy object for your mbean
6        BatchworkerMbean mbean=MBeanServerInvocationHandler.newProxyInstance(server,objectName,BatchWorkerMBean.class,false);
7// Use the proxy and invoke,I have declared a method in the interface called doJob (void) mbean.doJob("Do this from//EJB");

So simple enough isn't it? Always remember to have a look on Jboss Wiki and on JBoss Forums! Happy JBossing! ;)