Java MQ Code to List Channel Status

I thought I posted this code sample but I guess I forgot to do it. 😉

If you have done the runmqsc command for Channel Status for all channels of a queue manager as follows:

DIS CHS(*) ALL

And you wanted to do the same thing via a program, here is a fully functioning Java MQ example that will connect to a remote queue manager, issue a PCF “Inquire Channel Status” command, get the PCF response messages, loop through the PCF responses and output the information. You can download the source code from here.

For more information about the PCF “Inquire Channel Status” command, go to MQ KnowLedge Center here.

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;

import com.ibm.mq.MQException;
import com.ibm.mq.MQQueueManager;
import com.ibm.mq.constants.CMQC;
import com.ibm.mq.constants.CMQCFC;
import com.ibm.mq.headers.MQDataException;
import com.ibm.mq.headers.pcf.PCFMessage;
import com.ibm.mq.headers.pcf.PCFMessageAgent;

/**
 * Program Name
 *  MQListChannelStatus01
 *
 * Description
 *  This java class issues a PCF "inquire channel status" request message for all ("*") channels 
 *  of a remote queue manager. 
 *
 * Sample Command Line Parameters
 *  -m MQA1 -h 127.0.0.1 -p 1414 -c TEST.CHL -q TEST.Q1 -u UserID -x Password
 *
 * @author Roger Lacroix
 */
public class MQListChannelStatus01
{
   private static final SimpleDateFormat  LOGGER_TIMESTAMP = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");

   private Hashtable<String,String> params;
   private Hashtable<String,Object> mqht;
   private String qMgrName;

   public MQListChannelStatus01()
   {
      super();
      params = new Hashtable<String,String>();
      mqht = new Hashtable<String,Object>();
   }

   /**
    * Make sure the required parameters are present.
    * @return true/false
    */
   private boolean allParamsPresent()
   {
      boolean b = params.containsKey("-h") && params.containsKey("-p") &&
                  params.containsKey("-c") && params.containsKey("-m") &&
                  params.containsKey("-u") && params.containsKey("-x");
      if (b)
      {
         try
         {
            Integer.parseInt((String) params.get("-p"));
         }
         catch (NumberFormatException e)
         {
            b = false;
         }
      }

      return b;
   }

   /**
    * Extract the command-line parameters and initialize the MQ HashTable.
    * @param args
    * @throws IllegalArgumentException
    */
   private void init(String[] args) throws IllegalArgumentException
   {
      int port = 1414;
      if (args.length > 0 && (args.length % 2) == 0)
      {
         for (int i = 0; i < args.length; i += 2)
         {
            params.put(args[i], args[i + 1]);
         }
      }
      else
      {
         throw new IllegalArgumentException();
      }

      if (allParamsPresent())
      {
         qMgrName = (String) params.get("-m");
         
         try
         {
            port = Integer.parseInt((String) params.get("-p"));
         }
         catch (NumberFormatException e)
         {
            port = 1414;
         }
         
         mqht.put(CMQC.CHANNEL_PROPERTY, params.get("-c"));
         mqht.put(CMQC.HOST_NAME_PROPERTY, params.get("-h"));
         mqht.put(CMQC.PORT_PROPERTY, new Integer(port));
         mqht.put(CMQC.USER_ID_PROPERTY, params.get("-u"));
         mqht.put(CMQC.PASSWORD_PROPERTY, params.get("-x"));

         // I don't want to see MQ exceptions at the console.
         MQException.log = null;
      }
      else
      {
         throw new IllegalArgumentException();
      }
   }
   
   private void doPCF()
   {
      MQQueueManager qMgr = null;
      PCFMessageAgent agent = null;
      PCFMessage   request = null;
      PCFMessage[] responses = null;
      String chlStatus = "Inactive"; 

      try
      {
         qMgr = new MQQueueManager(qMgrName, mqht);
         MQListChannelStatus01.logger("successfully connected to "+ qMgrName);

         agent = new PCFMessageAgent(qMgr);
         MQListChannelStatus01.logger("successfully created agent");
      
         // https://www.ibm.com/support/knowledgecenter/en/SSFKSJ_9.1.0/com.ibm.mq.ref.adm.doc/q087540_.htm
         request = new PCFMessage(CMQCFC.MQCMD_INQUIRE_CHANNEL_STATUS);
         
         /**
          * You can explicitly set a channel name like "TEST.CHL" or
          * use a wild card like "TEST.*"
          */
         request.addParameter(CMQCFC.MQCACH_CHANNEL_NAME, "*");
         
         // Add a parameter to select the instance type (current)
         request.addParameter(CMQCFC.MQIACH_CHANNEL_INSTANCE_TYPE, CMQC.MQOT_CURRENT_CHANNEL);

         // Add a parameter that selects all of the attributes we want
         request.addParameter(CMQCFC.MQIACH_CHANNEL_INSTANCE_ATTRS, 
                              new int [] { CMQCFC.MQCACH_CHANNEL_NAME,
                                           CMQCFC.MQCACH_CONNECTION_NAME,
                                           CMQCFC.MQIACH_MSGS,
                                           CMQCFC.MQCACH_LAST_MSG_DATE,
                                           CMQCFC.MQCACH_LAST_MSG_TIME,
                                           CMQCFC.MQIACH_CHANNEL_STATUS
                              });

         responses = agent.send(request);
         
         for (int i = 0; i < responses.length; i++)
         {
            if ( ((responses[i]).getCompCode() == CMQC.MQCC_OK) &&
                 ((responses[i]).getParameterValue(CMQCFC.MQCACH_CHANNEL_NAME) != null) )
            {
               //  get the channel name and trim the spaces               
               String name = responses[i].getStringParameterValue(CMQCFC.MQCACH_CHANNEL_NAME);
               if (name != null)
                  name = name.trim();
               
               //  get the channel name and trim the spaces
               String connName = responses[i].getStringParameterValue(CMQCFC.MQCACH_CONNECTION_NAME);
               if (connName != null)
                  connName = connName.trim();
               
               //  get the channel last message date/time
               String lastMsgDate = responses[i].getStringParameterValue(CMQCFC.MQCACH_LAST_MSG_DATE);
               if (lastMsgDate != null)
                  lastMsgDate = lastMsgDate.trim();
               
               String lastMsgTime = responses[i].getStringParameterValue(CMQCFC.MQCACH_LAST_MSG_TIME);
               if (lastMsgTime != null)
                  lastMsgTime = lastMsgTime.trim();

               //  get the channel current messages total
               int totalMsgs = responses [i].getIntParameterValue(CMQCFC.MQIACH_MSGS);

               //  get the channel status
               chlStatus = getChannelStatus(responses [i].getIntParameterValue(CMQCFC.MQIACH_CHANNEL_STATUS));
               
               MQListChannelStatus01.logger("Name=" + name + " : Connection Name=" + connName  + " : Total Messages=" + totalMsgs +  
                                            " : Last Message Date='" + lastMsgDate +  "' : Last Message Time='" + lastMsgTime +
                                          "' : Status='" + chlStatus+"'");
            }
         }
      }
      catch (MQException e)
      {
         MQListChannelStatus01.logger("CC=" +e.completionCode + " : RC=" + e.reasonCode);
      }
      catch (IOException e)
      {
         MQListChannelStatus01.logger("IOException:" +e.getLocalizedMessage());
      }
      catch (MQDataException e)
      {
         MQListChannelStatus01.logger("MQDataException:" +e.getLocalizedMessage());
      }
      finally
      {
         try
         {
            if (agent != null)
            {
               agent.disconnect();
               MQListChannelStatus01.logger("disconnected from agent");
            }
         }
         catch (MQDataException e)
         {
            MQListChannelStatus01.logger("CC=" +e.completionCode + " : RC=" + e.reasonCode);
         }

         try
         {
            if (qMgr != null)
            {
               qMgr.disconnect();
               MQListChannelStatus01.logger("disconnected from "+ qMgrName);
            }
         }
         catch (MQException e)
         {
            MQListChannelStatus01.logger("CC=" +e.completionCode + " : RC=" + e.reasonCode);
         }
      }
   }
   
   private String getChannelStatus(int cs)
   {
      String chlStatus = "Inactive"; 

      switch (cs)
      {
         case CMQCFC.MQCHS_INACTIVE:
            chlStatus = "Inactive";
            break;
         case CMQCFC.MQCHS_BINDING:
            chlStatus = "Binding";
            break;
         case CMQCFC.MQCHS_STARTING:
            chlStatus = "Starting";
            break;
         case CMQCFC.MQCHS_RUNNING:
            chlStatus = "Running";
            break;
         case CMQCFC.MQCHS_STOPPING:
            chlStatus = "Stopping";
            break;
         case CMQCFC.MQCHS_RETRYING:
            chlStatus = "Retrying";
            break;
         case CMQCFC.MQCHS_STOPPED:
            chlStatus = "Stopped";
            break;
         case CMQCFC.MQCHS_REQUESTING:
            chlStatus = "Requesting";
            break;
         case CMQCFC.MQCHS_PAUSED:
            chlStatus = "Paused";
            break;
         case CMQCFC.MQCHS_DISCONNECTED:
            chlStatus = "Disconnected";
            break;
         case CMQCFC.MQCHS_INITIALIZING:
            chlStatus = "Initializing";
            break;
         case CMQCFC.MQCHS_SWITCHING:
            chlStatus = "Switching";
            break;
         default:
            chlStatus = "Unknown ["+cs+"]";
            break;
      }
      
      return chlStatus;
   }

   /**
    * A simple logger method
    * @param data
    */
   public static void logger(String data)
   {
      String className = Thread.currentThread().getStackTrace()[2].getClassName();

      // Remove the package info.
      if ( (className != null) && (className.lastIndexOf('.') != -1) )
         className = className.substring(className.lastIndexOf('.')+1);

      System.out.println(LOGGER_TIMESTAMP.format(new Date())+" "+className+": "+Thread.currentThread().getStackTrace()[2].getMethodName()+": "+data);
   }

   public static void main(String[] args)
   {
      MQListChannelStatus01 mqlqs = new MQListChannelStatus01();
      
      try
      {
         mqlqs.init(args);
         mqlqs.doPCF();
      }
      catch (IllegalArgumentException e)
      {
         MQListChannelStatus01.logger("Usage: java MQListChannelStatus01 -m QueueManagerName -h host -p port -c channel -u UserID -x Password");
         System.exit(1);
      }

      System.exit(0);
   }
}

Regards,
Roger Lacroix
Capitalware Inc.

This entry was posted in Capitalware, HPE NonStop, IBM i (OS/400), IBM MQ, Java, Linux, macOS (Mac OS X), Open Source, PCF, Programming, Unix, Windows.

3 Responses to Java MQ Code to List Channel Status