JMS/MQ Program That Creates Connection Factory from Scratch

On StackOverflow, someone asked a question about why their JMS/MQ code was failing. There are many errors in the code. Here is a fully functioning JMS/MQ program that will create the Connection Factory from scratch, connect to a remote queue manager and put a message to a queue.

You can download the source code from here.

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

import javax.jms.*;

import com.ibm.msg.client.jms.*;
import com.ibm.msg.client.wmq.*;

/**
 * Program Name
 *  MQTestJMS51
 *
 * Description
 *  This java JMS class will connect to a remote queue manager and put a message to a queue.
 *  This code will create the Connection Factory from scratch.
 *
 * 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 MQTestJMS51
{
   private static final SimpleDateFormat  LOGGER_TIMESTAMP = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
   private Hashtable<String,String> params;

   public MQTestJMS51()
   {
      super();
      params = new Hashtable<String,String>();
   }

   /**
    * 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("-q") &&
                  params.containsKey("-u") && params.containsKey("-x");
      
      return b;
   }

   /**
    * Extract the command-line parameters and initialize the MQ variables.
    * @param args
    * @throws IllegalArgumentException
    */
   private void init(String[] args) throws IllegalArgumentException
   {
      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())
      {
         throw new IllegalArgumentException();
      }
   }

   /**
    * Create a connection to the queue manager then publish a message to a queue.
    */
   private void handleIt() 
   {
      Connection conn = null;
      Session session = null;
      Destination destination = null;
      MessageProducer producer = null;
      
      try
      {
         /*
          * Set JVM system environment variables
          */
         System.setProperty("com.ibm.mq.cfg.useIBMCipherMappings", "false");
         
//         System.setProperty("javax.net.ssl.trustStore", trustedStore);
//         System.setProperty("javax.net.ssl.trustStorePassword", trustedStorePasswd);
         
         JmsFactoryFactory ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
         JmsConnectionFactory cf = ff.createConnectionFactory();

         // Set the properties
         cf.setStringProperty(WMQConstants.WMQ_HOST_NAME, (String) params.get("-h"));
         try
         {
            cf.setIntProperty(WMQConstants.WMQ_PORT, Integer.parseInt((String) params.get("-p")));
         }
         catch (NumberFormatException e)
         {
            cf.setIntProperty(WMQConstants.WMQ_PORT, 1414);
         }
         
         cf.setStringProperty(WMQConstants.WMQ_CHANNEL, (String) params.get("-c"));
         cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);
         cf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, (String) params.get("-m"));
         cf.setStringProperty(WMQConstants.WMQ_APPLICATIONNAME, "MQTestJMS51");
         cf.setBooleanProperty(WMQConstants.USER_AUTHENTICATION_MQCSP, true);
         
         cf.setStringProperty(WMQConstants.USERID, (String) params.get("-u"));
         cf.setStringProperty(WMQConstants.PASSWORD, (String) params.get("-x"));
         
//         cf.setStringProperty(WMQConstants.WMQ_SSL_CIPHER_SUITE, "TLS_RSA_WITH_AES_128_CBC_SHA256");
         
         conn = cf.createConnection((String) params.get("-u"), (String) params.get("-x"));
         logger("created connection.");
         
         // Start the connection
         conn.start();
         logger("started connection.");

         session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
         logger("created session.");

         /*
          * targetClient=0 means it is sending a JMS message
          * targetClient=1 means it is sending an MQ message (non JMS)
          */
         destination = session.createQueue("queue://" + (String) params.get("-m") + "/" + (String) params.get("-q") + "?targetClient=0");
         logger("created destination.");

         producer = session.createProducer(destination);
         logger("created producer.");
         
         sendMsg(session, producer);
      }
      catch (JMSException e)
      {
         if (e != null)
         {
            logger(e.getLocalizedMessage());
            e.printStackTrace();
            
            Exception gle = e.getLinkedException();
            if (gle != null)
               logger(gle.getLocalizedMessage());
         }
      }
      finally
      {
         try
         {
            if (producer != null)
            {
               producer.close();
               logger("closed producer.");
            }
         }
         catch (Exception e)
         {
            logger("producer.close() : " + e.getLocalizedMessage());
         }

         try
         {
            if (session != null)
            {
               session.close();
               logger("closed session.");
            }
         }
         catch (Exception e)
         {
            logger("session.close() : " + e.getLocalizedMessage());
         }

         try
         {
            if (conn != null)
            {
               conn.stop();
               logger("stopped connection.");
            }
         }
         catch (Exception e)
         {
            logger("conn.stop() : " + e.getLocalizedMessage());
         }

         try
         {
            if (conn != null)
            {
               conn.close();
               logger("closed connection.");
            }
         }
         catch (Exception e)
         {
            logger("connection.close() : " + e.getLocalizedMessage());
         }
      }
   }

   /**
    * Send a message to a queue.
    */
   private void sendMsg(Session session, MessageProducer producer)
   {
      try
      {
         long uniqueNumber = System.currentTimeMillis() % 1000;
         TextMessage msg = session.createTextMessage("Your lucky number today is " + uniqueNumber);

         producer.send(msg);
         logger("Sent message: " + msg);
      }
      catch (JMSException e)
      {
         if (e != null)
         {
            logger(e.getLocalizedMessage());
            e.printStackTrace();
            
            Exception gle = e.getLinkedException();
            if (gle != null)
               logger(gle.getLocalizedMessage());
         }
      }
   }

   /**
    * 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);
   }

   /**
    * main line
    * @param args
    */
   public static void main(String[] args)
   {
      logger("starting...");
      try
      {
         MQTestJMS51 tj = new MQTestJMS51();
         tj.init(args);
         tj.handleIt();
      }
      catch (IllegalArgumentException e)
      {
         logger("Usage: java MQTestJMS51 -m QueueManagerName -h host -p port -c channel -q Queue_Name -u UserID -x Password");
      }
      catch (Exception e)
      {
         logger(e.getLocalizedMessage());
         e.printStackTrace();
      }
      logger("ending...");
   }
}

Regards,
Roger Lacroix
Capitalware Inc.

This entry was posted in HPE NonStop, IBM i (OS/400), IBM MQ, IBM MQ Appliance, Java, JMS, Linux, macOS (Mac OS X), Programming, Raspberry Pi, Unix, Windows, z/OS.

Comments are closed.