Entering content frame

Background documentation Source Code of JMS Scenarios Locate the document in its SAP Library structure

This section contains the complete source code for all scenarios described in this document. For the compilation you require a Java SDK and a J2EE Library, which contains the JMS classes (see JMS Scenarios). The common package used here contains program parts that are used by the scenarios.

Common Package

common.Commandline (common/Commandline.java)

/**

 * This utility class receives keyboard input asynchronously

 * and passes it to a key listener.

 * Once started, it only stops when System.exit() is called.

 */

package common;

 

import java.io.IOException;

import java.io.InputStreamReader;

 

public class Commandline implements Runnable {

 

   KeyListener listener;

   InputStreamReader inputStreamReader = null;

   char answer = '\0';

 

   public Commandline(KeyListener listener) {

      this.listener = listener;

   }

 

   /**

    * endless loop to receive key input with blocking calls

    */

   public void run() {

      inputStreamReader = new InputStreamReader(System.in);

      while (true) {

         try {

            answer = (char) inputStreamReader.read();

            if (!(answer == '\r' || answer == '\n')) {

               listener.keyInput(answer);

            }

         } catch (IOException e) {

            System.out.println("I/O exception: " + e.toString());

         }

      }

   }

 

}

 

common.Constants (common/Constants.java)

package common;

 

/**

 * Constants used by all scenarios

 *

 */

public interface Constants {

 

   // Name of queue connection factory

   public static final String QUEUE_CONNECTION_FACTORY =

      "QueueConnectionFactory";

 

   // Name of topic connection factory

   public static final String TOPIC_CONNECTION_FACTORY =

      "TopicConnectionFactory";

 

   // Name of topic connection factory

   public static final String DUR_SUB_CONNECTION_FACTORY =

      "DurSubConnectionFactory";

 

   // Name of requirements queue production unit -> warehouse

   public static final String PU_REQUIREMENT_QUEUE          =

      "ProductionUnitRequirements";

   // Name of requirements queue warehouse -> storage unit

   public static final String STORAGE_REQUIREMENT_QUEUE        =

      "StorageRequirements";

   // Name of requirements queue warehouse -> transportation

   public static final String TRANSPORTATION_REQUIREMENT_QUEUE =

      "TransportationRequirements";

 

   // Name of requirements topic warehouse -> purchasing

   public static final String WH_REQUIREMENT_TOPIC   =

      "WarehouseRequirements";

 

   // Key for requirement ID

   public static final String REQ_ID_KEY     = "RequirementID";

   // Key for production unit ID

   public static final String PU_ID_KEY         = "ProductionUnitID";

   // Key for material ID

   public static final String MAT_ID_KEY     = "MaterialID";  

   // Key for material amount

   public static final String MAT_AMOUNT_KEY = "MaterialAmount"; 

   // Key for requirements date

   public static final String MAT_REQ_DATE_KEY  =

      "MaterialRequirementDate";

   // Key for storage unit ID

   public static final String STORAGE_ID_KEY = "StorageUnitID";

 

}

 

common.KeyListener (common/KeyListener.java)

/*

 * Interface for programs that process user input */

package common;

 

public interface KeyListener {

   public void keyInput(char input);

}

 

common.Utils (common/ Utils.java)

/*

 * Utility class for common messaging related tasks   */

package common;

 

import java.util.Properties;

import javax.naming.*;

 

public class Utils {

   private static final boolean sap = false;

 

   /*

    * Create a JNDI InitialContext object

    */

   public static Context getContext() {

      Context jndiContext = null;

      try {

         if (sap) {

            Properties properties = new Properties();

            properties.put(Context.INITIAL_CONTEXT_FACTORY,

            "com.sap.engine.services.jndi.InitialContextFactoryImpl");

            properties.put(Context.SECURITY_PRINCIPAL,

               "Administrator");

            properties.put(Context.SECURITY_CREDENTIALS, "");

            jndiContext = new InitialContext(properties);

         }

         else {

            jndiContext = new InitialContext();

         }

         return (jndiContext);

      } catch (NamingException e) {

         System.out.println("Could not create JNDI API " +

            "context: " + e.toString());

         System.exit(1);

      }

      return jndiContext;

   }

}

Simple Point-to-Point Scenario

scenario1.ProductionUnitSender (scenario1/ProductionUnitSender.java)

/**

 * The ProductionUnitSender class consists only of a main method,

 * which sends a material requirement message to a queue. Specify

‑{}‑ * the message parameters on the command line when you run the

 * program.

 */

package scenario1;

import javax.jms.*;

import javax.naming.*;

 

import common.Constants;

import common.Utils;

 

public class ProductionUnitSender {

 

   /**

    * Main method.

    *

    * @param args    the requirement message parameters

    */

   public static void main(String[] args) {

      Context                    jndiContext = null;

      QueueConnectionFactory     queueConnectionFactory = null;

      QueueConnection            queueConnection = null;

      QueueSession               queueSession = null;

      Queue                      queue = null;

      QueueSender                queueSender = null;

      MapMessage                 message = null;

 

      if ( (args.length != 5) ) {

         System.out.println("Usage: java ProductionUnitSender " +

            "<requirement ID> <production unit ID> <material ID>

             <material amount> <requirement date>");

         System.exit(1);

      }

 

      /*

       * Get naming context.

       */

      jndiContext = Utils.getContext();

 

      /*

       * Get connection factory and queue from the naming context.

       * In case of problems, leave the program.

       */

      try {

         queueConnectionFactory = (QueueConnectionFactory)

            jndiContext.lookup(Constants.QUEUE_CONNECTION_FACTORY);

         queue = (Queue) jndiContext.lookup(Constants.JMS_SUBCONTEXT+

            Constants.PU_REQUIREMENT_QUEUE);

      } catch (NamingException e) {

         System.out.println("JNDI API lookup failed: " + e.toString());

         System.exit(1);

      }

 

      /*

       * Initialize the connection, session and sender.

       * The session is not transacted.

       * Create a map message and send it.

       * Afterwards close the connection and leave the program.

       */

      try {

         queueConnection =

            queueConnectionFactory.createQueueConnection();

         queueSession = queueConnection.createQueueSession(false,

            Session.AUTO_ACKNOWLEDGE);

         queueSender = queueSession.createSender(queue);

         message = queueSession.createMapMessage();

         message.setString(Constants.REQ_ID_KEY, args[0]);

         message.setString(Constants.PU_ID_KEY, args[1]);

         message.setString(Constants.MAT_ID_KEY, args[2]);

         message.setString(Constants.MAT_AMOUNT_KEY, args[3]);

         message.setString(Constants.MAT_REQ_DATE_KEY, args[4]);

         queueSender.send(message);

 

      } catch (JMSException e) {

         System.out.println("Exception occurred: " + e.toString());

      } finally {

         if (queueConnection != null) {

            try {

               queueConnection.close();

            } catch (JMSException e) {}

         }

      }

   }

}

 

scenario1.WarehouseReceiver (scenario1/WarehouseReceiver.java)

/**

 * The WarehouseReceiver class fetches one or more messages from a queue

 * synchronously.

 * Run this program in conjunction with ProductionUnitSender.

 */

package scenario1;

 

import common.*;

 

import java.util.Enumeration;

 

import javax.jms.*;

import javax.naming.*;

 

public class WarehouseReceiver implements KeyListener {

 

   Context                    jndiContext = null;

   QueueConnectionFactory     queueConnectionFactory = null;

   QueueConnection            queueConnection = null;

   QueueSession               queueSession = null;

   Queue                      queue = null;

   QueueReceiver              queueReceiver = null;

   MapMessage                 message = null;

   char                       key = '\0';

 

   public void init(String[] args) {

      /*

       * Get naming context.

       */

      jndiContext = Utils.getContext();

 

      /*

       * Get connection factory and queue from the naming context.

       * In case of problems, exit.

       /

      try {

         queueConnectionFactory = (QueueConnectionFactory)

         jndiContext.lookup(Constants.QUEUE_CONNECTION_FACTORY);

         queue = (Queue) jndiContext.lookup(

            Constants.JMS_SUBCONTEXT+Constants.PU_REQUIREMENT_QUEUE);

      } catch (NamingException e) {

         System.out.println("JNDI API lookup failed: " + e.toString());

         System.exit(1);

      }

 

      /*

       * Initialize the connection, session and receiver.

       * The session is not transacted.

       * In case of problems, close connection and exit.

       */

      try {

         queueConnection =

            queueConnectionFactory.createQueueConnection();

         queueSession = queueConnection.createQueueSession(false,

            Session.AUTO_ACKNOWLEDGE);

         queueReceiver = queueSession.createReceiver(queue);

      } catch (JMSException e) {

         System.out.println("Exception occurred: " + e.toString());

         if (queueConnection != null) {

            try {

               queueConnection.close();

            } catch (JMSException ex) {}

         }

         System.exit(1);

      }

   }

  

   public void run() {

      /*

       * Start to listen for messages and for the command line.

       * Only MapMessages are handled.

       * Once the loop ends, close the connection.    */

      try {

         Thread stop = new Thread(new Commandline(this));

         stop.start();

         System.out.println("Now receiving, enter q and" +

                            "<Return> to end the program");

 

         queueConnection.start();

 

         while (!(key == 'q')) {

            Message m = queueReceiver.receive(1);

            if (m != null) {

               if (m instanceof MapMessage) {

                  message = (MapMessage) m;

                  System.out.println("Reading message with content: ");

                  for (Enumeration e = message.getMapNames() ;

                     e.hasMoreElements() ;) {

                     String key = (String)e.nextElement();

                     System.out.println(key+": "

                        +message.getString(key));

                  }

               }

            }

         }

         } catch (JMSException e) {

            System.out.println("Exception occurred: " + e.toString());

         } finally {

            if (queueConnection != null) {

               try {

                  queueConnection.close();

               } catch (JMSException e) {}

            }

         }

      }

   }

 

   /**

    * receive command line input

    */

   public void keyInput(char input) {

      key = input;

   }

 

   /**

    * Main method to initialize and run the warehouse receiver.

    *

    * @param args     command line arguments

    */

   public static void main(String[] args) {

      WarehouseReceiver receiver = new WarehouseReceiver();

      receiver.init(args);

      receiver.run();

      System.exit(0);

   }

}

Point-to-Point Scenario with Client Confirmation

scenario2.WarehouseReceiver (scenario1/WarehouseReceiver.java)

/**

 * The WarehouseReceiver class fetches one or more messages from a queue

 * synchronously.

 * Run this program in conjunction with ProductionUnitSender.

 */

package scenario2;

 

import common.*;

 

import java.util.Enumeration;

import java.util.Random;

 

import javax.jms.*;

import javax.naming.*;

 

public class WarehouseReceiver implements KeyListener {

 

   Context                    jndiContext = null;

   QueueConnectionFactory     queueConnectionFactory = null;

   QueueConnection            queueConnection = null;

   QueueSession               queueSession = null;

   Queue                      queue = null;

   QueueReceiver              queueReceiver = null;

   MapMessage                 message = null;

   char                       key = '\0';

   Random                     failure = new Random();

   int                        NO_FAILURE = 1;

 

   public void init(String[] args) {

      /*

       * Get naming context.

       */

      jndiContext = Utils.getContext();

 

      /*

       * Get connection factory and queue from the naming context.

       * In case of problems, exit.

       */

      try {

         queueConnectionFactory = (QueueConnectionFactory)

            jndiContext.lookup(Constants.QUEUE_CONNECTION_FACTORY);

         queue = (Queue) jndiContext.lookup(Constants.JMS_SUBCONTEXT+

            Constants.PU_REQUIREMENT_QUEUE);

      } catch (NamingException e) {

         System.out.println("JNDI API lookup failed: " + e.toString());

         System.exit(1);

      }

 

      /*

       * Initialize the connection, session and receiver.

       * The session is not transacted.

       * In case of problems, close connection and exit.

       */

      try {

         queueConnection =

            queueConnectionFactory.createQueueConnection();

         queueSession = queueConnection.createQueueSession(false,

            Session.CLIENT_ACKNOWLEDGE);

         queueReceiver = queueSession.createReceiver(queue);

      } catch (JMSException e) {

         System.out.println("Exception occurred: " + e.toString());

         if (queueConnection != null) {

            try {

               queueConnection.close();

            } catch (JMSException ex) {}

         }

         System.exit(1);

      }

   }

  

   public void run() {

      /*

       * Start to listen for messages and for the command line.

       * Only MapMessages are handled.

       * Once the loop ends, close the connection.

       */

      try {

         queueConnection.start();

 

         Thread stop = new Thread(new Commandline(this));

         stop.start();

         System.out.println("Now receiving, enter q and <Return>

                             to end the program");

         while (!(key == 'q')) {

            Message m = queueReceiver.receive(1);

            if (m != null) {

               if (m instanceof MapMessage) {

               // simulate processing problem for every second message

                  if (failure.nextInt(2) == NO_FAILURE) {

                     message = (MapMessage) m;

                     System.out.println("Reading message with

                                         content: ");

                     for (Enumeration e = message.getMapNames() ;

                           e.hasMoreElements() ;) {

                           String key = (String)e.nextElement();

                           System.out.println(key+": "

                              +message.getString(key));

                     }

                     message.acknowledge();

                  }

                  else {

                     System.out.println("Processing failure, no

                                         acknowledgement");

                     /* recover the session to receive the

                      * non-acknowledged message again

                      */

                     queueSession.recover();

                  }

               } else {

                  m.acknowledge();

               }

            }

         }

      } catch (JMSException e) {

         System.out.println("Exception occurred: " + e.toString());

      } finally {

         if (queueConnection != null) {

            try {

               queueConnection.close();

            } catch (JMSException e) {}

         }

      }

   }

 

   /**

    * receive command line input

    */

   public void keyInput(char input) {

      key = input;

   }

 

   /**

    * Main method to initialize and run the warehouse receiver.

    *

    * @param args     command line arguments

    */

   public static void main(String[] args) {

      WarehouseReceiver receiver = new WarehouseReceiver();

      receiver.init(args);

      receiver.run();

      System.exit(0);

   }

}

Simple Publish/Subscribe Scenario

scenario3.PurchasingSubscriber (scenario3/PurchasingSubscriber.java)

/**

 * The PurchasingSubscriber receives one or more messages from

 * a topic asynchronously using a RequirementListener.

 * Run this program in conjunction with a WarehousePublisher. 

 */

package scenario3;

 

import common.*;

 

import javax.jms.*;

import javax.naming.*;

 

public class PurchasingSubscriber implements KeyListener {

 

   Context                    jndiContext = null;

   TopicConnectionFactory     topicConnectionFactory = null;

   TopicConnection            topicConnection = null;

   TopicSession               topicSession = null;

   Topic                      topic = null;

   TopicSubscriber            topicSubscriber = null;

   RequirementListener        topicListener = null;

   char                       key = '\0';

 

   public void init(String[] args) {

      /*

       * Get naming context.

       */

      jndiContext = Utils.getContext();

 

      System.out.println("Listening on topic " +

         Constants.WH_REQUIREMENT_TOPIC);

 

      /*

       * Get connection factory and topic from the naming context.

       * In case of problems, exit.

       */

      try {

         topicConnectionFactory = (TopicConnectionFactory)

         jndiContext.lookup(Constants.TOPIC_CONNECTION_FACTORY);

         topic = (Topic)

            jndiContext.lookup(Constants.WH_REQUIREMENT_TOPIC);

      } catch (NamingException e) {

         System.out.println("JNDI API lookup failed: " + e.toString());

         System.exit(1);

      }

 

      /*

       * Initialize the connection, session and subscriber.

       * The session is not transacted.

       * Create and register the requirement listener.

       * In case of problems, close connection and exit.         *

       */

      try {

         topicConnection =

            topicConnectionFactory.createTopicConnection();

         topicSession = topicConnection.createTopicSession(false,

            Session.AUTO_ACKNOWLEDGE);

         topicSubscriber = topicSession.createSubscriber(topic);

         topicListener = new RequirementListener();

         topicSubscriber.setMessageListener(topicListener);

      } catch (JMSException e) {

         System.out.println("Exception occurred: " + e.toString());

         if (topicConnection != null) {

            try {

               topicConnection.close();

            } catch (JMSException ex) {}

         }

         System.exit(1);

      }

   }

 

   public void run() {

      /*

       * Start to listen for messages and for the command line.

       * Once the loop ends, close the connection.

       */ 

      try {

         topicConnection.start();

 

         Thread stop = new Thread(new Commandline(this));

         stop.start();

         System.out.println("Now receiving, enter q and

                             <Return> to end the program");

         while (!(key == 'q')) {

         }

      } catch (JMSException e) {

         System.out.println("Exception occurred: " + e.toString());

      } finally {

         if (topicConnection != null) {

            try {

               topicConnection.close();

            } catch (JMSException e) {}

         }

      }

   }

 

   /**

    * receive command line input

    */

   public void keyInput(char input) {

      key = input;

   }

 

   /**

    * Main method to initialize and run the warehouse receiver.

    *

    * @param args     command line arguments

    */

   public static void main(String[] args) {

      PurchasingSubscriber subscriber = new PurchasingSubscriber();

      subscriber.init(args);

      subscriber.run();

      System.exit(0);

   }

}

 

scenario3.RequirementListener (scenario3/RequirementListener.java)

/**

 * The RequirementListener class implements the MessageListener

 * interface by defining an onMessage method that displays

 * the contents of a MapMessage.

 */

package scenario3;

 

import common.*;

 

import javax.jms.*;

 

public class RequirementListener implements MessageListener {

 

   /**

    * Casts the message to a MapMessage and displays its text.

    *

    * @param message     the incoming message

    */

   public void onMessage(Message message) {

      MapMessage msg = null;

 

      try {

         if (message instanceof MapMessage) {

            msg = (MapMessage) message;

            System.out.println("Reading message with content: ");

            System.out.println(Constants.MAT_ID_KEY+": "

               +msg.getString(Constants.MAT_ID_KEY));

            System.out.println(Constants.MAT_AMOUNT_KEY+": "

               +msg.getString(Constants.MAT_AMOUNT_KEY));

            System.out.println(Constants.MAT_REQ_DATE_KEY+": "

               +msg.getString(Constants.MAT_REQ_DATE_KEY));

         } else {

            System.out.println("Message of wrong type: " +

               message.getClass().getName());

         }

      } catch (JMSException e) {

         System.out.println("JMSException in onMessage(): " +

            e.toString());

      } catch (Throwable t) {

         System.out.println("Exception in onMessage():" +

            t.getMessage());

      }

   }

}

 

scenario3.WarehousePublisher (scenario3/WarehousePublisher.java)

/**

 * The WarehousePublisher class consists only of a main method

 * which sends a material requirement message to a topic. Specify

 * the message parameters on the command line when you run the

 * program.

 */

package scenario3;

 

import common.*;

 

import javax.jms.*;

import javax.naming.*;

 

public class WarehousePublisher {

 

   /**

    * Main method.

    *

    * @param args     the requirement message parameters

    */

   public static void main(String[] args) {

      Context                 jndiContext = null;

      TopicConnectionFactory  topicConnectionFactory = null;

      TopicConnection         topicConnection = null;

      TopicSession            topicSession = null;

      Topic                   topic = null;

      TopicPublisher          topicPublisher = null;

      MapMessage              message = null;

 

      if ( (args.length != 3) ) {

         System.out.println("Usage: java WarehousePublisher " +

            "<material ID> <material amount> <requirement date>");

         System.exit(1);

      }

 

      /*

       * Get naming context.

       */

      jndiContext = Utils.getContext();

 

      /*

       * Get connection factory and topic from the naming context.

       * In case of problems, leave the program.

       */

      try {

         topicConnectionFactory = (TopicConnectionFactory)

            jndiContext.lookup(Constants.TOPIC_CONNECTION_FACTORY);

         topic = (Topic)

            jndiContext.lookup(Constants.WH_REQUIREMENT_TOPIC);

      } catch (NamingException e) {

         System.out.println("JNDI API lookup failed: " + e.toString());

         System.exit(1);

      }

 

      /*

       * Initialize the connection, session and publisher.

       * The session is not transacted.

       * Create a map message and publish it.

       * Afterwards close the connection and leave the program.

       */

      try {

         topicConnection =

            topicConnectionFactory.createTopicConnection();

         topicSession = topicConnection.createTopicSession(false,

            Session.AUTO_ACKNOWLEDGE);

         topicPublisher = topicSession.createPublisher(topic);

         message = topicSession.createMapMessage();

         message.setString(Constants.MAT_ID_KEY, args[0]);

         message.setString(Constants.MAT_AMOUNT_KEY, args[1]);

         message.setString(Constants.MAT_REQ_DATE_KEY, args[2]);

         topicPublisher.publish(message);

      } catch (JMSException e) {

         System.out.println("Exception occurred: " + e.toString());

      } finally {

         if (topicConnection != null) {

            try {

               topicConnection.close();

            } catch (JMSException e) {}

         }

      }

   }

}

Publish/Subscribe Scenario with Permanent Backup

scenario4. PurchasingSubscriber (scenario4/PurchasingSubscriber.java)

/**

 * The PurchasingSubscriber receives one or more messages from

 * a topic asynchronously using a RequirementListener.

 * Run this program as a receiver for a WarehousePublisher. 

 */

package scenario4;

 

import common.*;

 

import javax.jms.*;

import javax.naming.*;

 

import scenario3.RequirementListener;

 

public class PurchasingSubscriber implements KeyListener {

 

   Context                    jndiContext = null;

   TopicConnectionFactory     topicConnectionFactory = null;

   TopicConnection            topicConnection = null;

   TopicSession               topicSession = null;

   Topic                      topic = null;

   TopicSubscriber            topicSubscriber = null;

   RequirementListener        topicListener = null;

   String                     subscriptionId = null;

   char                       key = '\0';

 

   public void init(String[] args) {

      /*

       * Ensure that a subscription ID is provided.

       */

      if (args.length != 1) {

         System.out.println("Usage: java " +

             "PurchasingSubscriber <subscriptionId>");

         System.exit(1);

      }

 

      subscriptionId = args[0];

 

      System.out.println("Subscription "+subscriptionId+" listening

                          on topic " + Constants.WH_REQUIREMENT_TOPIC);

 

      /*

       * Get naming context.

      */

      jndiContext = Utils.getContext();

 

      /*

       * Get connection factory and topic from the naming context.

       * In case of problems, exit.

       */

      try {

         topicConnectionFactory = (TopicConnectionFactory)

         jndiContext.lookup(Constants.DUR_SUB_CONNECTION_FACTORY);

         topic = (Topic)

            jndiContext.lookup(Constants.WH_REQUIREMENT_TOPIC);

      } catch (NamingException e) {

         System.out.println("JNDI API lookup failed: " + e.toString());

         System.exit(1);

      }

 

      /*

       * Initialize the connection, session and subscriber.

       * The session is not transacted.

       * Create and register the requirement listener.

       * In case of problems, close connection and exit.         *

       */

      try {

         topicConnection =

            topicConnectionFactory.createTopicConnection();

         topicSession = topicConnection.createTopicSession(false,

            Session.AUTO_ACKNOWLEDGE);

         topicSubscriber =

            topicSession.createDurableSubscriber(topic,subscriptionId);

         topicListener = new RequirementListener();

         topicSubscriber.setMessageListener(topicListener);

      } catch (JMSException e) {

         System.out.println("Exception occurred: " + e.toString());

         if (topicConnection != null) {

            try {

               topicConnection.close();

            } catch (JMSException ex) {}

         }

      }

   }

 

   public void run() {

      /*

       * Start to listen for messages and for the command line.

       * Once the loop ends, close the connection.

       */ 

      try {

         Thread stop = new Thread(new Commandline(this));

         stop.start();

         System.out.println("Now receiving, enter q (unsubscribe) or c

                             (close) and <Return> to end the program");

 

         topicConnection.start();

 

         while (!((key == 'q') || (key == 'c') )) {

         }

         if (key == 'c') {

            System.out.println(subscriptionId+" closing subscription");

            topicSubscriber.close();

         }

         else if (key == 'q') {

            System.out.println(subscriptionId+" unsubscribing from

                                                topic");

            topicSubscriber.close();

            topicSession.unsubscribe(subscriptionId);

         }

      } catch (JMSException e) {

         System.out.println("Exception occurred: " + e.toString());

      } finally {

         if (topicConnection != null) {

            try {

               topicConnection.close();

            } catch (JMSException e) {}

         }

      }

 

   }

 

   /**

    * receive command line input

    */

   public void keyInput(char input) {

      key = input;

   }

 

   /**

    * Main method to initialize and run the purchasing subscriber.

    *

    * @param args     subscription id

    */

   public static void main(String[] args) {

      PurchasingSubscriber subscriber = new PurchasingSubscriber();

      subscriber.init(args);

      subscriber.run();

      System.exit(0);

   }

}

Simple Transaction Message Processing

scenario5.RequirementReceiver (scenario5/RequirementReceiver.java)

/**

 * The WarehouseReceiver class fetches one or more messages from a   

 * queue synchronously.

 * Run this program in conjunction with ProductionUnitSender.

 */

 

package scenario5;

 

import common.*;

 

import java.util.Enumeration;

 

import javax.jms.*;

import javax.naming.*;

 

public class RequirementReceiver implements KeyListener{

 

   Context                    jndiContext = null;

   QueueConnectionFactory     queueConnectionFactory = null;

   QueueConnection            queueConnection = null;

   QueueSession               queueSession = null;

   Queue                      queue = null;

   QueueReceiver              queueReceiver = null;

   MapMessage                 message = null;

   char                       key = '\0';

 

   public void init(String[] args) {

      /*

       * Ensure that the queue name is provided.

       */

      if (args.length != 1) {

         System.out.println("Usage: java " +

            "RequirementReceiver <queue-name>");

         System.exit(1);

      }

 

      /*

       * Get naming context.

       */

      jndiContext = Utils.getContext();

 

      /*

       * Get connection factory and queue from the naming context.

       * In case of problems, exit.

       */

      try {

         queueConnectionFactory = (QueueConnectionFactory)

         jndiContext.lookup(Constants.QUEUE_CONNECTION_FACTORY);

         queue = (Queue)

            jndiContext.lookup(Constants.JMS_SUBCONTEXT+args[0]);

      } catch (NamingException e) {

         System.out.println("JNDI API lookup failed: " + e.toString());

         System.exit(1);

      }

 

      /*

       * Initialize the connection, session and receiver.

       * The session is not transacted.

       * In case of problems, close connection and exit.

       */

      try {

         queueConnection =

            queueConnectionFactory.createQueueConnection();

         queueSession = queueConnection.createQueueSession(false,

            Session.AUTO_ACKNOWLEDGE);

         queueReceiver = queueSession.createReceiver(queue);

      } catch (JMSException e) {

         System.out.println("Exception occurred: " + e.toString());

         if (queueConnection != null) {

            try {

               queueConnection.close();

            } catch (JMSException ex) {}

         }

         System.exit(1);

      }

   }

 

   public void run() {

      /*

       * Start to listen for messages and for the command line.

       * Only MapMessages are handled.

       * Once the loop ends, close the connection.    */

      try{

         Thread stop = new Thread(new Commandline(this));

         stop.start();

         System.out.println("Now receiving, enter q and <Return> to

                             end the program");

 

         queueConnection.start();

 

         while (!(key == 'q')) {

            Message m = queueReceiver.receive(1);

            if (m != null) {

               if (m instanceof MapMessage) {

                  message = (MapMessage) m;

                  System.out.println("Reading message with content: ");

                  for (Enumeration e = message.getMapNames() ;

                     e.hasMoreElements() ;) {

                     String key = (String)e.nextElement();

                     System.out.println(key+": "

                        +message.getString(key));

                  }

               }

            }

         }

      } catch (JMSException e) {

         System.out.println("Exception occurred: " + e.toString());

      } finally {

         if (queueConnection != null) {

            try {

               queueConnection.close();

            } catch (JMSException e) {}

         }

      }

   }

 

   /**

    * receive command line input

    */

   public void keyInput(char input) {

      key = input;

   }

 

   /**

    * Main method to initialize and run the warehouse receiver.

    *

    * @param args     command line arguments

    */

   public static void main(String[] args) {

      RequirementReceiver receiver = new RequirementReceiver();

      receiver.init(args);

      receiver.run();

      System.exit(0);

   }

}

 

scenario5.WarehouseReceiver (scenario5/WarehouseReceiver.java)

 /**

 * The WarehouseReceiver class fetches one or more messages from a

 * queue synchronously and processes them in a transaction.

 * Run this program in conjunction with ProductionUnitSender.

 */

package scenario5;

 

import common.*;

 

import java.util.Enumeration;

import java.util.Random;

 

import javax.jms.*;

import javax.naming.*;

 

public class WarehouseReceiver implements KeyListener {

 

   Context                    jndiContext = null;

   QueueConnectionFactory     queueConnectionFactory = null;

   QueueConnection            queueConnection = null;

   QueueSession               queueSession = null;

   Queue                      productionQueue = null;

   Queue                      storageQueue = null;

   Queue                      transportQueue = null;

   QueueReceiver              queueReceiver = null;

   QueueSender                storageSender = null;

   QueueSender                transportSender = null;

   MapMessage                 message = null;

   char                       key = '\0';

   Random                     failure = new Random();

   int                        NO_FAILURE = 1;

  

   public void init(String[] args) {

      /*

       * Get naming context.

       */

      jndiContext = Utils.getContext();

 

      /*

       * Get connection factory and queues from the naming context.

       * In case of problems, exit.

       */

      try {

         queueConnectionFactory = (QueueConnectionFactory)

            jndiContext.lookup(Constants.QUEUE_CONNECTION_FACTORY);

         productionQueue = (Queue)

            jndiContext.lookup(Constants.PU_REQUIREMENT_QUEUE);

         storageQueue = (Queue)

            jndiContext.lookup(Constants.STORAGE_REQUIREMENT_QUEUE);

         transportQueue = (Queue) jndiContext.lookup

            (Constants.TRANSPORTATION_REQUIREMENT_QUEUE);

      } catch (NamingException e) {

         System.out.println("JNDI API lookup failed: " + e.toString());

         System.exit(1);

      }

 

      /*

       * Initialize the connection, session,receivers and senders.

       * The session is not transacted.

       * In case of problems, close connection and exit.

      */

      try {

         queueConnection =

            queueConnectionFactory.createQueueConnection();

         queueSession = queueConnection.createQueueSession(true,

            Session.AUTO_ACKNOWLEDGE);

         queueReceiver =

            queueSession.createReceiver(productionQueue);

         storageSender = queueSession.createSender(storageQueue);

         transportSender = queueSession.createSender(transportQueue);

      } catch (JMSException e) {

         System.out.println("Exception occurred: " + e.toString());

         if (queueConnection != null) {

            try {

               queueConnection.close();

            } catch (JMSException ex) {}

         }

         System.exit(1);

      }

   }

  

   public void run() {

      /*

       * Start to listen for messages and for the command line.

       * Only MapMessages are handled.

       * Once the loop ends, close the connection.

       */

      try {

         Thread stop = new Thread(new Commandline(this));

         stop.start();

         System.out.println("Now receiving, enter q and <Return> to

                             end the program");

 

         queueConnection.start();

 

         while (!(key == 'q')) {

            Message m = queueReceiver.receive(1);

            if (m != null) {

               System.out.println("Message received");

               if (m instanceof MapMessage) {

                  message = (MapMessage) m;

               if (process(message)) {

                  System.out.println("Processed message with

                                      content: ");

                  for (Enumeration e = message.getMapNames() ;

                     e.hasMoreElements() ;) {

                     String key = (String)e.nextElement();

                     System.out.println(key+": "

                        +message.getString(key));

                  }

                  queueSession.commit();

               }

               else {

                  System.out.println("Processing failed, rolling

                                      back session");

                  queueSession.rollback();

               }

            }

         }

      }

   } catch (JMSException e) {

      System.out.println("Exception occurred: " + e.toString());

      } finally {

         if (queueConnection != null) {

            try {

               queueConnection.close();

            } catch (JMSException e) {}

         }

      }

   }

 

   /**

    * receive command line input

    */

   public void keyInput(char input) {

      key = input;

   }

 

   /**

    * process one message

    */  

   private boolean process(MapMessage m) {

      try {

         storageSender.send(m);

         transportSender.send(m);

      } catch (JMSException e) {

         System.out.println("Exception occurred: " + e.toString());

         return false;

      }

      if (!updateDatabase()) {

         System.out.println("Database failure");

         return false;

      }

      return true;

   }

 

   /**

    * simulate database failures

    */  

   private boolean updateDatabase() {

      // database fails with 50% probability

      if (failure.nextInt(2) == NO_FAILURE)

         return true;

      else

         return false;

   }

 

   /**

    * Main method to initialize and run the warehouse receiver.

    *

    * @param args     command line arguments

    */

   public static void main(String[] args) { 

      WarehouseReceiver receiver = new WarehouseReceiver();

      receiver.init(args);

      receiver.run();

      System.exit(0);

   }

}

Message Processing: Confirmation in a Temporary Queue

scenario6.ProductionUnitSender (scenario6/ProductionUnitSender.java)

/**

 * The ProductionUnitSender class consists only of a main method,

 * which sends a material requirement message to a queue.

 * Then it waits for a confirmation by the receiver.

 * Specify the message parameters on the command line when you run the

 * program.

 */

package scenario6;

 

import common.*;

 

import java.util.Enumeration;

 

import javax.jms.*;

import javax.naming.*;

 

public class ProductionUnitSender {

 

   /**

    * Main method.

    *

    * @param args    the requirement message parameters

    */

   public static void main(String[] args) {

      Context                 jndiContext = null;

      QueueConnectionFactory  queueConnectionFactory = null;

      QueueConnection            queueConnection = null;

      QueueSession               queueSession = null;

      Queue                      productionQueue = null;

      QueueSender                queueSender = null;

      Queue                      replyQueue = null;

      QueueReceiver              replyReceiver = null;

      MapMessage                 message = null;

 

      if ( (args.length != 5) ) {

         System.out.println("Usage: java ProductionUnitSender " +

            "<requirement ID> <production unit ID> <material ID>

             <material amount> <requirement date>");

         System.exit(1);

      }

 

      /*

       * Get naming context.

       */

      jndiContext = Utils.getContext();

 

      /*

       * Get connection factory and queue from the naming context.

       * In case of problems, leave the program.

       */

      try {

         queueConnectionFactory = (QueueConnectionFactory)

            jndiContext.lookup(Constants.QUEUE_CONNECTION_FACTORY);

         productionQueue = (Queue) jndiContext.lookup

            (Constants.JMS_SUBCONTEXT+Constants.PU_REQUIREMENT_QUEUE);

      } catch (NamingException e) {

         System.out.println("JNDI API lookup failed: " + e.toString());

         System.exit(1);

      }

 

      /*

       * Initialize the connection, session and sender.

       * The session is not transacted.

       * Create a map message and send it.

       * Wait for the receivers reply.

       * Afterwards close the connection and leave the program.

       */

      try {

         queueConnection =

            queueConnectionFactory.createQueueConnection();

         queueSession = queueConnection.createQueueSession(false,

            Session.AUTO_ACKNOWLEDGE);

         queueSender = queueSession.createSender(productionQueue);

         /* generate a queue to be used by the receiver to send

          * the reply */

         replyQueue = queueSession.createTemporaryQueue();

         replyReceiver = queueSession.createReceiver(replyQueue);

         queueConnection.start();

 

         message = queueSession.createMapMessage();

         message.setString(Constants.REQ_ID_KEY, args[0]);

         message.setString(Constants.PU_ID_KEY, args[1]);

         message.setString(Constants.MAT_ID_KEY, args[2]);

         message.setString(Constants.MAT_AMOUNT_KEY, args[3]);

         message.setString(Constants.MAT_REQ_DATE_KEY, args[4]);

         // enable receiver to send an answer

         message.setJMSReplyTo(replyQueue);

         queueSender.send(message);

 

         System.out.println("Waiting for reply...");

         while (true) {

            Message m = replyReceiver.receive(1);

            if (m != null) {

               System.out.println("Message received");

               if (m instanceof MapMessage) {

                  MapMessage reply = (MapMessage) m;

                  System.out.println("Reply for message "

                     +reply.getJMSCorrelationID());

                  System.out.println("Reply for requirement "

                     +reply.getString(Constants.REQ_ID_KEY));

               }

               break;

            }

         }

 

      } catch (JMSException e) {

         System.out.println("Exception occurred: " + e.toString());

      } finally {

         if (queueConnection != null) {

            try {

               queueConnection.close();

            } catch (JMSException e) {}

         }

      }

   }

}

 

scenario6.WarehouseReceiver (scenario6/WarehouseReceiver.java)

/**

 * The WarehouseReceiver class fetches one or more messages from a

 * queue synchronously and processes them in a transaction,

 * including a response to the sender.

 * Run this program in conjunction with ProductionUnitSender.

 */

package scenario6;

 

import common.*;

 

import java.util.Enumeration;

import java.util.Random;

 

import javax.jms.*;

import javax.naming.*;

 

public class WarehouseReceiver implements KeyListener {

 

   Context                 jndiContext = null;

   QueueConnectionFactory  queueConnectionFactory = null;

   QueueConnection         queueConnection = null;

   QueueSession            queueSession = null;

   Queue                   productionQueue = null;

   Queue                   storageQueue = null;

   Queue                   transportQueue = null;

   QueueReceiver           queueReceiver = null;

   QueueSender             storageSender = null;

   QueueSender             transportSender = null;

   QueueSender             replySender = null; 

   MapMessage              message = null;

   char                    key = '\0';   

   Random                  failure = new Random();

   int                     NO_FAILURE = 1;

 

   public void init(String[] args) {

      /*

       * Get naming context.

       */

      jndiContext = Utils.getContext();

 

      /*

       * Get connection factory and queues from the naming context.

       * In case of problems, exit.

       */

      try {

         queueConnectionFactory = (QueueConnectionFactory)

            jndiContext.lookup(Constants.QUEUE_CONNECTION_FACTORY);

         productionQueue = (Queue)

            jndiContext.lookup(Constants.PU_REQUIREMENT_QUEUE);

         storageQueue = (Queue)

            jndiContext.lookup(Constants.STORAGE_REQUIREMENT_QUEUE);

         transportQueue = (Queue) jndiContext.lookup

            (Constants.TRANSPORTATION_REQUIREMENT_QUEUE);

      } catch (NamingException e) {

         System.out.println("JNDI API lookup failed: " + e.toString());

         System.exit(1);

      }

 

      /*

       * Initialize the connection, session,receivers and senders.

       * The session is not transacted.

       * In case of problems, close connection and exit.

       */

      try {

         queueConnection =

            queueConnectionFactory.createQueueConnection();

         queueSession = queueConnection.createQueueSession(true,

            Session.AUTO_ACKNOWLEDGE);

         queueReceiver =

            queueSession.createReceiver(productionQueue);

         storageSender = queueSession.createSender(storageQueue);

         transportSender =

            queueSession.createSender(transportQueue);

         /* create unidentified sender to be used with temporary

          * reply queues

          */

         replySender = queueSession.createSender(null);

      } catch (JMSException e) {

         System.out.println("Exception occurred: " + e.toString());

         if (queueConnection != null) {

            try {

               queueConnection.close();

            } catch (JMSException ex) {}

         }

         System.exit(1);

      }

   }

 

   public void run() {

      /*

       * Start to listen for messages and for the command line.

       * Only MapMessages are handled.

       * Once the loop ends, close the connection.

       */         

      try {

         queueConnection.start();

 

         Thread stop = new Thread(new Commandline(this));

         stop.start();

         System.out.println("Now receiving, enter q and <Return> to

                             end the program");

         while (!(key == 'q')) {        

            Message m = queueReceiver.receive(1);

            if (m != null) {

               System.out.println("Message received");

               if (m instanceof MapMessage) {

                  message = (MapMessage) m;

                  if (process(message)) {

                     System.out.println("Processed message with

                                         content: ");

                     for (Enumeration e = message.getMapNames() ;

                        e.hasMoreElements() ;) {

                        String key = (String)e.nextElement();

                        System.out.println(key+": "

                           +message.getString(key));

                     }

                     queueSession.commit();

                  }

                  else {

                     System.out.println("Processing failed, rolling

                                         back session");

                     queueSession.rollback();

                  }

               }

            }

         }

      } catch (JMSException e) {

         System.out.println("Exception occurred: " + e.toString());

      } finally {

         if (queueConnection != null) {

            try {

               queueConnection.close();

            } catch (JMSException e) {}

         }

      }

   }

 

   /**

    * receive command line input

    */

   public void keyInput(char input) {

      key = input;

   }

 

   /**

    * process one message and send a reply to the sender */  

   private boolean process(MapMessage m) {

      try {

         storageSender.send(m);

         transportSender.send(m);

         MapMessage reply = queueSession.createMapMessage();

         reply.setJMSCorrelationID(message.getJMSMessageID());

         reply.setString(Constants.REQ_ID_KEY,

            message.getString(Constants.REQ_ID_KEY));

         System.out.println("sending reply");

         replySender.send((Queue)message.getJMSReplyTo(), reply);

      } catch (JMSException e) {

         System.out.println("Exception occurred: " + e.toString());

         return false;

      }

      if (!updateDatabase()) {

         System.out.println("Database failure");

         return false;

      }

      return true;

   }

 

   /**

    * simulate database failures */

   private boolean updateDatabase() {

      // database fails with 50% probability

      if (failure.nextInt(2) == NO_FAILURE)

         return false;

      else

         return true;

   }

  

   /**

    * Main method to initialize and run the warehouse receiver.

    *

    * @param args     command line arguments

    */

   public static void main(String[] args) {

      WarehouseReceiver receiver = new WarehouseReceiver();

      receiver.init(args);

      receiver.run();

      System.exit(0);

   }

}

Using Message Filters

scenario7.StorageReceiver (scenario7/StorageReceiver.java)

/**

 * The StorageReceiver class fetches one or more messages from a queue

 * synchronously.

 * It only asks for the messages targeted at its own storage id.

 * Run this program in conjunction with ProductionUnitSender.

 */

package scenario7;

 

import common.*;

 

import java.util.Enumeration;

import java.util.Iterator;

 

import javax.jms.*;

import javax.naming.*;

 

 

public class StorageReceiver implements KeyListener {

 

   Context                    jndiContext = null;

   QueueConnectionFactory     queueConnectionFactory = null;

   QueueConnection            queueConnection = null;

   QueueSession               queueSession = null;

   Queue                      queue = null;

   QueueReceiver              queueReceiver = null;

   MapMessage                 message = null;

   char                       key = '\0';   

 

   public void init(String[] args) {

      /*

       * Read storage name from command line and display it.

       */

      if (args.length != 1) {

         System.out.println("Usage: java " +

            "StorageReceiver <storage-name>");

         System.exit(1);

      }

 

      /*

       * Get naming context.

       */

      jndiContext = Utils.getContext();

 

      /*

       * Get connection factory and queue from the naming context.

       * In case of problems, exit.

       */

      try {

         queueConnectionFactory = (QueueConnectionFactory)

            jndiContext.lookup(Constants.QUEUE_CONNECTION_FACTORY);

         queue = (Queue) jndiContext.lookup

          (Constants.JMS_SUBCONTEXT+Constants.PU_REQUIREMENT_QUEUE);

      } catch (NamingException e) {

         System.out.println("JNDI API lookup failed: " + e.toString());

         System.exit(1);

      }

 

      /*

       * Initialize the connection, session and receiver.    

       * The session is not transacted.

       * The receiver is initialized with a message selection string

       * carrying the storage id.

       * In case of problems, close connection and exit.

       */

      try {

         queueConnection =

            queueConnectionFactory.createQueueConnection();

         queueSession = queueConnection.createQueueSession(false,

            Session.AUTO_ACKNOWLEDGE);

         String selector = Constants.STORAGE_ID_KEY + " =

            '"+args[0]+"'";

         queueReceiver = queueSession.createReceiver(queue, selector);

      } catch (JMSException e) {

         System.out.println("Exception occurred: " + e.toString());

         if (queueConnection != null) {

            try {

               queueConnection.close();

            } catch (JMSException ex) {}

         }

         System.exit(1);

      }

   }

 

   public void run() {

      /*

       * Start to listen for messages and for the command line.

       * Only MapMessages are handled.

       * Once the loop ends, close the connection.

       */

      try{

         Thread stop = new Thread(new Commandline(this));

         stop.start();

         System.out.println("Now receiving, enter q and <Return> to end

                             the program");

 

         queueConnection.start();

 

         while (!(key == 'q')) {

            Message m = queueReceiver.receive(1);

            if (m != null) {

               if (m instanceof MapMessage) {

                  message = (MapMessage) m;

                  System.out.println("Reading message with content: ");

                  for (Enumeration e = message.getMapNames() ;

                     e.hasMoreElements() ;) {

                     String key = (String)e.nextElement();

                     System.out.println(key+": " 

                        +message.getString(key));

                  }

               }

            }

         }

      } catch (JMSException e) {

         System.out.println("Exception occurred: " + e.toString());

      } finally {

         if (queueConnection != null) {

            try {

               queueConnection.close();

            } catch (JMSException e) {}

         }

      }

   }

 

   /**

    * receive command line input

    */

   public void keyInput(char input) {

      key = input;

   }

 

   /**

    * Main method to initialize and run the warehouse receiver.

    *

    * @param args     command line arguments

    */

   public static void main(String[] args) {

      StorageReceiver receiver = new StorageReceiver();

      receiver.init(args);

      receiver.run();

      System.exit(0);

   }

}

 

scenario7.WarehouseSender (scenario7/WarehouseSender.java)

/**

 * The WarehouseSender class consists only of a main method,

 * which sends a material requirement message to a queue.

 * Specify the target storage and the message parameters on

 * the command line when you run the program.

 */

package scenario7;

 

import common.*;

 

import javax.jms.*;

import javax.naming.*;

 

public class WarehouseSender {

 

   /**

    * Main method.

    *

    * @param args     the storage target and the message parameters

    */

   public static void main(String[] args) {

      Context                 jndiContext = null;

      QueueConnectionFactory  queueConnectionFactory = null;

      QueueConnection         queueConnection = null;

      QueueSession            queueSession = null;

      Queue                   queue = null;

      QueueSender             queueSender = null;

      MapMessage              message = null;

 

      if ( (args.length != 4) ) {

         System.out.println("Usage: java WarehouseSender " +

            "<storage ID> <material ID> <material amount> <requirement

             date>");

         System.exit(1);

      }

 

      /*

       * Get naming context.

       */

      jndiContext = Utils.getContext();

 

      /*

       * Get connection factory and queue from the naming context.

       * In case of problems, leave the program.

       */

      try {

         queueConnectionFactory = (QueueConnectionFactory)

            jndiContext.lookup(Constants.QUEUE_CONNECTION_FACTORY);

         queue = (Queue) jndiContext.lookup

            (Constants.JMS_SUBCONTEXT+Constants.PU_REQUIREMENT_QUEUE);

      } catch (NamingException e) {

         System.out.println("JNDI API lookup failed: " + e.toString());

         System.exit(1);

      }

 

      /*

       * Initialize the connection, session and sender.

       * The session is not transacted.

       * Create a map message and send it.

       * The target storage is identified as a header property.

       * Afterwards close the connection and leave the program.

       */

      try {

         queueConnection =

            queueConnectionFactory.createQueueConnection();

         queueSession = queueConnection.createQueueSession(false,

            Session.AUTO_ACKNOWLEDGE);

         queueSender = queueSession.createSender(queue);

         message = queueSession.createMapMessage();

         // identify the target storage

         message.setStringProperty(Constants.STORAGE_ID_KEY, args[0]);

         message.setString(Constants.MAT_ID_KEY, args[1]);

         message.setString(Constants.MAT_AMOUNT_KEY, args[2]);

         message.setString(Constants.MAT_REQ_DATE_KEY, args[3]);

         queueSender.send(message);

 

      } catch (JMSException e) {

         System.out.println("Exception occurred: " + e.toString());

      } finally {

         if (queueConnection != null) {

            try {

               queueConnection.close();

            } catch (JMSException e) {}

         }

      }

   }

}

 

 

Leaving content frame