Tuesday, December 27, 2011

Setup JMX connection

JMX connection is used for invocation of JMX operations on the remote host or local Java Virtual machine. How we can establish this?

To establish the JMX connection to the remote process we need to know its JMXServiceURL, as it is used in constructor:

   private JMXConnector connector;
   public void connect(JMXServiceURL url) throws IOException {
      connector = JMXConnectorFactory.connect(url);

Getting the connector we are able to use its MBean server connection to perform some action usin JMX, eg:

   public MBeanServerConnection getMBeanServerConnection() throws IOException {
      return this.connector.getMBeanServerConnection();
   MBeanServerConnection con = getMBeanServerConnection();
         MBeanInfo beanInfo = con.getMBeanInfo(beanObjName);
         MBeanOperationInfo operationInfo = null;
         for(MBeanOperationInfo info : beanInfo.getOperations()) {
            if(operation.name().equals(info.getName())) {
               operationInfo = info;
         if(operationInfo == null) {
            throw new IllegalArgumentException(String.format(MngrUtils.AMCMessages.INCORRECT_BEAN_OP, operation.name(), beanObjName.getCanonicalName()));
         MBeanParameterInfo[] paramInfos = operationInfo.getSignature();
         if (paramInfos.length != args.length) {
            throw new IllegalArgumentException(String.format("%s" + MngrUtils.AMCMessages.INCORRECT_OP_PARAMS + "%d parameters, expected %d" , operation.name(), args.length, paramInfos.length));
         String[] signatures = new String[args.length];
         Object[] params = new Object[args.length];
         for(int iter = 0; iter < args.length; iter++) {
            MBeanParameterInfo paramInfo = paramInfos[iter];
            params[iter] = args[iter];
            signatures[iter] = paramInfo.getType();
         result = con.invoke(beanObjName, operation.name(), params, signatures);

MBean Server Connection is a necessary object for JMX operations, however what if we'd like to establish the JMX connection to the same JVM where we launch the program (for example when we are trying to cover the code with JUnit). We need the following method:


The object returned is our current MBeanServerConnection, using that we are able to invoke JMX operations as well as for remotly connected JMX object.

No comments:

Post a Comment