JMX for beginners
Hi if you are new to JMX then I will show you how to write your first JMX code:
First you need to create an interface for the Mbean to be created:
public interface HelloWorldMBean {
public void setGreeting(String greeting);
public String getGreeting();
public void printGreeting();
}
Then you will have to create your Mbean class:
import javax.management.Notification;
import javax.management.*;
public class HelloWorld extends NotificationBroadcasterSupport implements HelloWorldMBean{
private String greeting=null;
public HelloWorld(){
this.greeting=”Helo World ! this is a standard Mbean”;
}
public HelloWorld(String greeting){
this.greeting=greeting;
}
public void setGreeting(String greeting){
this.greeting=greeting;
System.out.println(“calling setGreeting method”);
//following code is to send notification
Notification notification = new Notification(“ch2.helloWorld1.test”,this,-1, System.currentTimeMillis(),greeting);
sendNotification(notification);
}
public String getGreeting(){
return greeting;
}
public void printGreeting(){
System.out.println(greeting);
}
}
Now we need to create a JMX agent that can create MBeanServer instance and register the Mbeans that needs to be monitored:
import javax.management.*;
import com.sun.jdmk.comm.*;
public class HelloAgent implements NotificationListener{
private MBeanServer mbs = null;
public HelloAgent()
{
mbs = MBeanServerFactory.createMBeanServer(“HelloAgent”);
HtmlAdaptorServer adapter = new HtmlAdaptorServer();
HelloWorld hw = new HelloWorld();
ObjectName adapterName = null;
ObjectName helloWorldName = null;
try{
helloWorldName = new ObjectName(“HelloAgent:name=helloworld1″);
adapterName = new ObjectName(“HelloAgent:name=htmladapter,port=9092″);
adapter.setPort(9092);
mbs.registerMBean(hw, helloWorldName);
mbs.registerMBean(adapter, adapterName);
adapter.start();
//following code is to register notification listener
hw.addNotificationListener(this,null,null);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void handleNotification(Notification notification, Object handback)
{
System.out.println(“receiving notification”);
System.out.println(notification.getType());
System.out.println(notification.getMessage());
}
public static void main(String args[])
{
System.out.println(“HelloAgent is running”);
HelloAgent ha = new HelloAgent();
}
}
Now you can run this HelloAgent class.
Then open a browser and try to open the link: http://localhost:9092/
You can see the browser connects to the Mbean Server and shows all the Mbeans register with this JMX agent.