12/04/2015

[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{  
   
   try{  
        
           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!  
   
     connector.close();  
   
   }catch(Exception e){  
   
     System.out.println(e.getMessage());  
   
     System.exit(0);  
   
      }  
   }  
 }  
   

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


No comments:

Post a Comment

With great power comes great responsibility