[Java] JMX connection and bean operation invocation

In this example we'll see how to create a JMX connection, with or without authentication, and invoke a bean method.

 import javax.management.remote.JMXServiceURL;  
 import javax.management.MBeanAttributeInfo;  
 import javax.management.MBeanInfo;  
 import javax.management.MBeanServerConnection;  
 import javax.management.ObjectName;  
 import javax.management.remote.JMXConnector;  
 import javax.management.remote.JMXConnectorFactory;  
 import java.util.Hashtable;  
 public class myJMXConnection{  
   private static String HOST = "HOST";  
   private static String PORT = "PORT"; //usually it's 1099  
   private static String BEAN_NAME = "BEAN_NAME"; //com.groglogs.myclass:type=MyObject  
   private static String BEAN_OP = "BEAN_OPERATION";  
   private static String USER = "USERNAME";  
   private static String PASS = "PASSWORD";  
      public static void main(String[] args) throws Exception{  
           JMXServiceURL target = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + HOST + ":" + PORT+"/jmxrmi");  
           //only if authentication is required  
           Hashtable<String, String[]> env = new Hashtable<String, String[]>();  
           String[] credentials = new String[] {USER,PASS};  
           env.put(JMXConnector.CREDENTIALS, credentials);   
     JMXConnector connector = JMXConnectorFactory.connect(target, env);  
     //if not required, use simply JMXConnector connector = JMXConnectorFactory.connect(target);  
     MBeanServerConnection remote = connector.getMBeanServerConnection();  
     ObjectName bean = new ObjectName(BEAN_NAME);  
     remote.invoke(bean, BEAN_OP, null, null);//invoke the remote method. Ensure first that the user calling this method has the necessary rights to invoke it!  
   }catch(Exception e){  

An important thing to note, is to always remember to check first if the user calling the method has the required permissions to invoke it

Copenhagen among vikings

Since with their prices they would rob you every time

Click on the image to see the full album

Cliffhanging in Bardonecchia

Now with 50% more surprise geocaching

Click on the image to see the full album

Check out the full track with MyTracks