Writing a Client

Listing 14.5 demonstrates how a client sends a message to the JMS Destination.

Listing 14.5. The Full Text of day14/Client.java
package day14;

import javax.jms.*;
import javax.naming.*;
import javax.ejb.*;
import java.util.*;

import day11.OrderHome;
import day11.Order;

public class Client {
public static void main(String[] args) {
   print("Starting Client . . .");
   try {
      String orderVerifierJndiName = args[0];
      String connectionFactoryJndiName = args[1];
      print("Looking up the JMS destination(Topic) via JNDI.");
      Context context = new InitialContext();
      Topic topic = (Topic) context.lookup(orderVerifierJndiName);

      print("Locating connection factory.");
      TopicConnectionFactory connectionFactory = (TopicConnectionFactory)
         context.lookup(connectionFactoryJndiName);
      print("Creating a connection  and establishing a session.");
      TopicConnection connection =
         connectionFactory.createTopicConnection();
      TopicSession session = connection.createTopicSession
         (false,Session.AUTO_ACKNOWLEDGE);
      TopicPublisher publisher = session.createPublisher(topic);

      print("Creating an order with status:Submitted");
      Context initialContext = new InitialContext();
      Object object = initialContext.lookup("day11/Order");
      OrderHome orderHome = (OrderHome)
         javax.rmi.PortableRemoteObject.narrow(object,OrderHome.class);
      Order order = (Order)orderHome.create
                  ( "1", "Submitted", 100);
      String orderId = order.getOrderId();
      print("Order id " + orderId + " is created");
      print("Creating a text message with order id and publishing it.");
      TextMessage tm = session.createTextMessage();
      tm.setText(orderId);
      publisher.publish(tm);
      print("Sleeping for 2 sec.");
      Thread.sleep(2000);
      print("Now the order status is:" + order.getStatus());
   }
   catch(Exception ex) {
      System.err.println(ex);
      ex.printStackTrace();
   }
}
static void print(String s) {
   System.out.println(s);
}
}

The client accepts two command-line arguments: the Topic JNDI name and the connection factory JNDI name. The client locates the Topic via JNDI. It locates the connection factory in the JNDI name space, creates a TopicConnection, and establishes a TopicSession. It then uses that TopicSession to create a TopicSubscriber so that we can publish messages.

The code creates a sample order and marks its status as Submitted. Before publishing the message, the client creates a text message and populates it with the order ID. The client then publishes the message. As you know, the OrderVerifier bean receives the message and changes the order status to Verified. Finally, the client prints the order status.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.128.145