- Introduction to Messaging
- Components of the JMS Architecture
- The Two JMS Message Models
- The JMS Interfaces
- The Details of a JMS Message
- Message Selection and Filtering
- Using the JMS Point-to-Point Model
- Using the JMS Publish/Subscribe Model
- Synchronous Versus Asynchronous Messaging
- Message Persistence
- Using Transactions with JMS
- Using JMS with Enterprise JavaBeans
- Troubleshooting
Using the JMS Point-to-Point Model
Up to this point you have not seen a complete example of a JMS application. The focus has been to understand the concepts and interfaces of the JMS APIs. Now we will take a look at a complete example using JMS.
The JMS application example that you will see here is one based on the Auction example that runs throughout this book. The Auction service will allow e-mail messages to be sent to auction participants based on the normal events that occur throughout the life cycle of an auction. The normal events that the application will support are
A user's bid has become a trailing bid
A user's bid is the winning bid for an auction
First, you will see how a queue can be used to support this functionality and then later, in the section "Using the JMS Publish/Subscribe Model," a topic will be used so that a log message will be written for the administrator so that auction notifications can be later audited.
The JMS application developed in this chapter will utilize the horizontal services that will be discussed later in Chapter 21, "Horizontal Services." The term horizontal services refers to services that are used across many different components, sort of like a framework. Don't worry if this doesn't make much sense right now; it's covered in depth in Chapter 21.
For now, only stubs to those services will be used. For example, instead of complicating this example with the details of how to send e-mails using the JavaMail API, we will merely call the horizontal service that provides that capability and not discuss that functionality here. The horizontal service will only print the e-mail message out. Later in Chapter 21, when the horizontal services are discussed further, you'll see how to generate the actual e-mails using the JavaMail API.
In this example, the MessageConsumer will be a separate Java client that connects to the destination from outside the EJB container and uses the horizontal service to send the e-mail messages. The producer will also be a Java client. It's possible that the producer code might belong inside a session or entity bean method, but to keep the example simple, we will not use enterprise beans here.
We will revisit this example in Chapter 11 and see how the message-driven bean can be used as the consumer instead of this Java client. For now, we will try to keep it simple.
' For more information on the horizontal services, see Chapter 21, "Horizontal Services."
Creating the JMS Administered Objects
The first thing that has to be done for this example is to configure the JMS server and set up the JMS administered objects. The process of setting up the JMS administered objects varies greatly between vendors. In BEA's WebLogic, there is a web administration console that allows an administrator to add the ConnectionFactory and Destination to the set of components that are created and started when the server starts. In other JMS implementations, you might have to edit some type of configuration file manually. Check with your vendor documentation on how to do this. For this JMS example, you'll need to set up two JMS administered objects:
Connection_Factory with a JNDI name of com.que.ejb20book.AuctionConnectionFactory
A Queue with a JNDI name of com.que.ejb20book.EmailQueue
The JNDI names of these are critical for the JMS examples in this chapter. The example uses the naming service to locate the JMS objects. You must be sure that you use these JNDI names when setting up the JMS configuration. Listing 10.1 shows a resource properties file that will be used by the examples. If you want to change the names of the administered objects in JNDI, change it in this property file also. This properties file must be placed somewhere in the system classpath for it to be found. The name of the resource file must be auction_jms.properties for the examples to work correctly. If you must change the names of the administered objects, change only the value on the right side of the equal (=) sign in the file. Don't change the value on the left side. The examples will look up the JNDI names based on the key part of the key/value pair.
Listing 10.1 auction_jms.properties Resource File Used By the JMS Examples
AUCTION_CONNECTION_FACTORY=com.que.ejb20book.AuctionConnectionFactory AUCTION_NOTIFICATION_QUEUE=com.que.ejb20book.EmailQueue
Listening for Messages from a Queue
The first part of the JMS application that we will look at is the consumer portion. Listing 10.2 shows the AuctionNotificationConsumer class. This class is responsible for registering a MessageListener with the QueueReceiver and waiting for a message to arrive. The onMessage method is called and passed the message that was put into the queue. From there, the generation of the e-mail message is delegated to the e-mail horizontal service. The e-mail message is generated as long as the object within the JMS message implements the AuctionNotification interface.
Notice by looking at the source code in Listing 10.2 that this is a Java program that runs outside the EJB container. We have done this because, under normal circumstances, there's no nonproprietary way to kick off a consumer to start listening for messages. Each EJB vendor typically has services that enable you to create a sort of startup class, but usually they are specific to that vendor and are not very portable. By using a Java client program running outside the container, you can control very easily when the consumer program starts up. In the next chapter, you will see how this functionality can be performed using the new message-driven bean. For now, we will leave it as a standalone Java program.
Listing 10.2 Source Code for AuctionNotificationConsumer.java
/** * Title: AuctionNotificationConsumer * Description: The MessageConsumer that gets messages from a Queue * and sends an email. */ package com.que.ejb20.notification; import javax.jms.*; import java.io.*; import java.util.*; import javax.naming.*; import com.que.ejb20.services.email.*; /** * This class is used to listen for incoming JMS Messages on a Queue and then * generate an email based on the Message. The incoming Message must be * a javax.jms.ObjectMessage and the contents of the Message must be a * com.que.ejb20.notification.NofiticationEmail for an Email to be * generated. */ public class AuctionNotificationConsumer implements Runnable, MessageListener { // The reference to the JNDI Context needed to look up Administered // JMS objects private InitialContext ctx = null; // Private static names for the Administered JMS Objects // These values will be read from a resource properties file private static String connectionFactoryName = null; private static String queueName = null; private QueueConnectionFactory qcf = null; private QueueReceiver receiver = null; private QueueConnection queueConnection = null; private Queue queue = null; /** * Default Constructor */ public AuctionNotificationConsumer() { super(); } /** * This is the method that must be implemented from the MessageListener * interface. This method will be called when a message has arrived at the * Queue and the container calls this method and passes the new Message. * * @param msg The javax.jms.Message that was sent to the Queue * * @see javax.jms.Message * @see javax.jms.MessageListener */
Listing 10.2 Continued
public void onMessage( Message msg ) { if ( msg instanceof ObjectMessage) { try { Object obj = ((ObjectMessage)msg).getObject(); if ( obj instanceof AuctionNotification ) { sendEmail( (AuctionNotification)obj ); } } catch( JMSException ex ) { ex.printStackTrace(); } } } /** * The run method is necessary because this method implements the * Runnable interface to keep the thread alive and waiting for messages. * Otherwise, this thread would not keep running and would not * be able to listen for messages continuously. */ public void run() { while( true ) { synchronized( this ){ try{ wait(); }catch( InterruptedException ex ){ // Do Nothing } } } } // Private Accessor for Connection Factory Name private static String getConnectionFactoryName() { return connectionFactoryName; } // Private mutator for the Connection factory Name private static void setConnectionFactoryName( String name ) { connectionFactoryName = name; } // Private Accessor for the Queue Name private static String getQueueName() { return queueName; } // Private mutator for Queue Name private static void setQueueName( String name ) { queueName = name; } /** * This method is called to set up and initialize the necessary * Connection and Session references. * * @exception JMSException Problem finding a JMS administered object * @exception NamingException Problem with JNDI and a named object* *
Listing 10.2 Continued
*/ public void init() throws JMSException, NamingException { try{ loadProperties(); // Look up the jndi factory ctx = new InitialContext(); // Get a connection to the QueueConnectionFactory qcf = (QueueConnectionFactory)ctx.lookup( getConnectionFactoryName() ); // Create a connection queueConnection = qcf.createQueueConnection(); // Create a session that is non-transacted and is notified automatically QueueSession ses = queueConnection.createQueueSession( false, Session.AUTO_ACKNOWLEDGE ); // Look up a destination queue = (Queue)ctx.lookup( getQueueName() ); // Create the receiver receiver = ses.createReceiver( queue ); // It's a good idea to always put a finally block so that the // context is closed }catch( NamingException ex ) { ex.printStackTrace(); }finally { try { // Close up the JNDI connection since we have found what we needed if ( ctx != null ) ctx.close(); }catch ( Exception ex ) { ex.printStackTrace(); } } // Inform the receiver that the callbacks should be sent to this instance receiver.setMessageListener( this ); // Start listening queueConnection.start(); System.out.println( "Listening on queue " + queue.getQueueName() ); } /** * This method is called to load the JSM resource properties */ private void loadProperties() { String connectionFactoryName = null; String queueName = null; // Uses a Properties file to get the properties for the JMS objects Properties props = new Properties(); try {
Listing 10.2 Continued
props.load( getClass().getResourceAsStream( "/auction_jms.properties" ) ); }catch( IOException ex ){ ex.printStackTrace(); }catch( Exception ex ){ System.out.println( "Had a problem locating auction_jms.properties"); ex.printStackTrace(); } connectionFactoryName = props.getProperty( "AUCTION_CONNECTION_FACTORY" ); queueName = props.getProperty( "AUCTION_NOTIFICATION_QUEUE" ); // Set the JMS Administered values for this instance setConnectionFactoryName( connectionFactoryName ); setQueueName( queueName ); } /** * Delegate the sending of the email to the horizontal service. */ private void sendEmail( AuctionNotification msg ) { NotificationEmail email = new NotificationEmail(); email.setToAddress( msg.getNotificationEmailAddress() ); email.setBody( msg.toString() ); email.setFromAddress( "AuctionSite" ); email.setSubject( msg.getNotificationSubject() ); // Delete to the horizontal service try{ EmailService.sendEmail( email ); }catch( EmailException ex ){ ex.printStackTrace(); } } /** * Main Method * This is the main entry point that starts the Email listening for * messages in the Queue. */ public static void main( String args[]) { // Create an instance of the client AuctionNotificationConsumer emailConsumer = new AuctionNotificationConsumer(); try { emailConsumer.init(); }catch( NamingException ex ){ ex.printStackTrace(); }catch( JMSException ex ){ ex.printStackTrace(); } // Start the client running Thread newThread = new Thread( emailConsumer ); newThread.start(); } }
Many things are going on in Listing 10.2. Here are the main steps this class performs:
Locate the auction_jms.properties file and read the names for the JMS administered objects.
Implement the onMessage method.
Get the connection, destination, and session.
Keep the thread alive.
Send e-mail messages when a JMS message arrives.
Several classes and interfaces are being used by the AuctionNofiticationConsumer in Listing 10.2. The Java interface for the auction notification and the two notification classes that implement this interface appear in Listings 10.3, 10.4, and 10.5 respectively.
Listing 10.3 Source Code for AuctionNotification.java
/** * Title: AuctionNotification<p> * Description: This interface defines the methods required for an Auction * Notification.<p> */ package com.que.ejb20.notification; public interface AuctionNotification extends java.io.Serializable { public void setAuctionName( String newAuctionName ); public String getAuctionName(); public void setNotificationEmailAddress( String emailAddress ); public String getNotificationEmailAddress(); public String getNotificationSubject(); }
Listing 10.4 Source Code for AuctionWinnerNotification.java
/** * Title: AuctionWinnerNotification<p> * Description: Contains information about a winner of a * particular Auction.<p> */ package com.que.ejb20.notification; /** * This class encapsulates the information about a winner of an Auction * that is needed when sending an email Notification to the winner or * another administrator. This class implements java.io.Serializable * so that it can be sent over the network to the JMS destination. * */ public class AuctionWinnerNotification implements java.io.Serializable, AuctionNotification { /** * Default Constructor */ public AuctionWinnerNotification() { super();
Listing 10.4 Continued
} // Private instance references private String auctionName; private String auctionWinner; private String auctionWinPrice; private String notificationEmailAddress; // Public Accessors and Mutators public String getAuctionName() { return auctionName; } public void setAuctionName(String newAuctionName) { auctionName = newAuctionName; } public void setAuctionWinner(String newAuctionWinner) { auctionWinner = newAuctionWinner; } public String getAuctionWinner() { return auctionWinner; } public void setAuctionWinPrice(String newAuctionWinPrice) { auctionWinPrice = newAuctionWinPrice; } public String getAuctionWinPrice() { return auctionWinPrice; } public void setNotificationEmailAddress(String emailAddress) { notificationEmailAddress = emailAddress; } public String getNotificationEmailAddress() { return notificationEmailAddress; } public String getNotificationSubject() { // This message should come from an external resource bundle so that // Internationalization can be handled properly return "You have the winning bid!"; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append( "Your bid of " ); buf.append( getAuctionWinPrice() ); buf.append( " has become the winning bid in the Auction " ); buf.append( getAuctionName() ); return buf.toString(); } }
Listing 10.5 Source Code for AuctionTrailingBidNotification.java
/** * Title: AuctionTrailingBidNotification<p> * Description: Contains information to be sent to a user when that user has * a bid on an Auction that has become a trailer.<p> */ package com.que.ejb20.notification; /** * This class encapsulates the information about a bid on an Auction * that has become a trailer. This notification is meant to notify the user * of the trailing bid in case the user wishes to make another bid for the * Auction. */ public class AuctionTrailingBidNotification implements java.io.Serializable, AuctionNotification { /** * Default Constructor */ public AuctionTrailingBidNotification() { super(); } // Private instance references private String auctionName; private String leadingBid; private String usersLastBid; private String notificationEmailAddress; // Public Accessors and Mutators public String getAuctionName() { return auctionName; } public void setAuctionName( String newAuctionName ) { auctionName = newAuctionName; } public void setLeadingBid( String leadingBid ) { this.leadingBid = leadingBid; } public String getLeadingBid() { return leadingBid; } public void setUsersLastBid( String lastBid ) { usersLastBid = lastBid; } public String getUsersLastBid() { return usersLastBid; } public void setNotificationEmailAddress(String emailAddress) {
Listing 10.5 Continued
notificationEmailAddress = emailAddress; } public String getNotificationEmailAddress() { return notificationEmailAddress; } public String getNotificationSubject() { // This message should come from an external resource bundle so that // Internationalization can be handled properly return "Your bid has become a trailing bid"; } public String toString() { // This message should come from an external resource bundle so that // Internationalization can be handled properly StringBuffer buf = new StringBuffer(); buf.append( "Your bid of " ); buf.append( getUsersLastBid() ); buf.append( " in the Auction: " ); buf.append( getAuctionName() ); buf.append( " has become a trailing bid. The new leading bid is " ); buf.append( getLeadingBid() ); return buf.toString(); } }
Listing 10.6 is the e-mail horizontal service that we just stubbed in for now. The sendMail method that is called only prints out the e-mail to the console for now. This service will be developed further in Chapter 21.
' For more information on the horizontal services, see Chapter 21, "Horizontal Services."
Listing 10.6 Source Code for the E-mail Component in the Horizontal Services
/** * Title: EmailService<p> * Description: This class represents the horizontal email service * Component. It contains static methods for generating email * messages.<p> */ package com.que.ejb20.services.email; public class EmailService { // For now, this method will not really generate an email message. Later it // will use the JavaMail API to do so, but for now it will only print out // a message saying that an email has been sent. public static void sendEmail( NotificationEmail email ) { System.out.println( email.toString() ); } }
The horizontal service component in Listing 10.6 uses a class to encapsulate all the information needed to send an e-mail message. That class is shown in Listing 10.7.
Listing 10.7 Source Code for NotificationEmail.java
/** * Title: NotificationEmail * Description: Encapsulate all the states of an Email object */ package com.que.ejb20.services.email; /** * This class encapsulates the data that must be sent in an Email message. * This class does not support attachments. This class implements the * java.io.Serializable interface so that this object can be marshaled * over the network. * */ public class NotificationEmail implements java.io.Serializable{ /** * Default Constructor */ public NotificationEmail() { super(); } // Private instance references private String toAddress; private String fromAddress; private String subject; private String body; // Public Accessors and Mutators public String getToAddress() { return toAddress; } public void setToAddress(String newToAddress) { toAddress = newToAddress; } public void setFromAddress(String newFromAddress) { fromAddress = newFromAddress; } public String getFromAddress() { return fromAddress; } public void setSubject(String newSubject) { subject = newSubject; } public String getSubject() { return subject; } public void setBody(String newBody) { body = newBody; } public String getBody() { return body; }
Listing 10.7 Continued
public String toString() { StringBuffer buf = new StringBuffer(); buf.append( "To: " + getToAddress() ); buf.append( "\n" ); buf.append( "From: " + getFromAddress() ); buf.append( "\n" ); buf.append( "Subject: " + getSubject() ); buf.append( "\n" ); buf.append( "Body: " + getBody() ); buf.append( "\n" ); return buf.toString(); } }
Sending Messages to a Queue
Now we need to create a class that generates the JMS messages that are sent to the queue. For our Auction example, a notification must be sent based on two events. One is when a new bid is placed on an auction and there is an existing bid that becomes a trailing bid. In this case, an AuctionTrailingBidNotification needs to be generated and sent to the user of the previous bid. The second event that triggers a notification is when an auction closes with a winner. In this case, an AuctionWinnerNotification will be generated and sent to the winner of the auction. An auction can close with a winner automatically and also when the auction administrator assigns a winner to an auction. In both cases, the notification should be sent.
To keep things simple for now, we are going to just use a simple Java client program to help test our JMS application. Listing 10.8 shows the class AuctionNotificationProducer that will generate either a winner or trailing auction notification to a particular e-mail address based on the command-line arguments passed into it.
NOTE
Remember that this code is used only to help us test the notification functionality. For a real auction application, this code would be placed in the components that are actually deciding when there is a winner or a trailing bid.
As with the AuctionNotificationConsumer, several steps are taking place in the AuctionNotificationProducer class. Here is the summary of the steps:
Locate the auction_jms.properties file and read the names for the JMS administered objects.
Get the Connection, Destination, and Session.
Generate the JMS message that wraps the AuctionNotification object.
Exit.
Listing 10.8 Source Code for AuctionNotificationProducer.java
/** * Title: AuctionNotificationProducer * Description: This class is used to help test the * AuctionNotificationConsumer class by sending notifications * to a Queue based on the command-line arguments. */ package com.que.ejb20.notification; import javax.jms.*; import java.io.*; import java.util.*; import javax.naming.*; /** * This class is used to test the AuctionNotificationConsumer class. * In a production application, this code would be used by the component * that determines an email should be generated. A JMS ObjectMessage is * created and a com.que.ejb20.notification.NofiticationEmail object * is inserted into the ObjectMessage and then sent to the Queue. */ public class AuctionNotificationProducer { // Administered ConnectionFactory and Queue settings // These values are hard-coded because this is a test class and is not // to be easily configurable. You can make it so by either reading the // jms bundle as the consumer does or pass in these values on the command // line. // Private static names for the Administered JMS Objects // These values will be read from a resource properties file private static String connectionFactoryName = null; private static String queueName = null; // The reference to the JNDI Context private Context ctx = null; // Private instance references private QueueConnectionFactory queueConnectionFactory = null; private QueueSession queueSession = null; private QueueSender queueSender = null; private QueueConnection queueConnection = null; private Queue queue = null; /** * Default Constructor */ public AuctionNotificationProducer() { super(); loadProperties(); } private void initialize() throws JMSException, NamingException { try{ // Look up the jndi factory ctx = new InitialContext(); // Get a connection to the QueueConnectionFactory
Listing 10.8 Continued
queueConnectionFactory = (QueueConnectionFactory)ctx.lookup( getConnectionFactoryName() ); // Create a connection queueConnection = queueConnectionFactory.createQueueConnection(); // Create a session that is non-transacted and is notified automatically queueSession = queueConnection.createQueueSession( false, Session.AUTO_ACKNOWLEDGE ); // Look up a destination queue = (Queue)ctx.lookup( getQueueName() ); }catch( NamingException ex ) { ex.printStackTrace(); System.exit( -1 ); }finally { try { // Close up the JNDI connection since we have found what we needed ctx.close(); }catch ( Exception ex ) { ex.printStackTrace(); } } queueSender = queueSession.createSender( queue ); queueSender.setDeliveryMode( DeliveryMode.NON_PERSISTENT ); // Start the connection because every connection is in the // stopped state when created. It must be started queueConnection.start(); } public void sendMessage( AuctionNotification emailMsg ) { try { // establish the necessary connection references initialize(); Message msg = queueSession.createObjectMessage( emailMsg ); queueSender.send( msg ); // Close the open resources queueSession.close(); queueConnection.close(); }catch( JMSException ex ) { ex.printStackTrace(); }catch( NamingException ex ) { ex.printStackTrace(); } } // Private Accessor for Connection Factory Name private static String getConnectionFactoryName() { return connectionFactoryName; }
Listing 10.8 Continued
// Private mutator for the Connection factory Name private static void setConnectionFactoryName( String name ) { connectionFactoryName = name; } // Private Accessor for the Queue Name private static String getQueueName() { return queueName; } // Private mutator for Queue Name private static void setQueueName( String name ) { queueName = name; } /** * This method is called to load the JMS resource properties */ private void loadProperties() { String connectionFactoryName = null; String queueName = null; // Uses a Properties file to get the properties for the JMS objects Properties props = new Properties(); try { props.load(getClass().getResourceAsStream( "/auction_jms.properties" )); }catch( IOException ex ){ ex.printStackTrace(); }catch( Exception ex ){ System.out.println( "Had a problem locating auction_jms.properties"); ex.printStackTrace(); } connectionFactoryName = props.getProperty( "AUCTION_CONNECTION_FACTORY" ); queueName = props.getProperty( "AUCTION_NOTIFICATION_QUEUE" ); // Set the JMS Administered values for this instance setConnectionFactoryName( connectionFactoryName ); setQueueName( queueName ); } /** * Main Method * * This method is the main entry point for sending a JMS message to the * EmailQueue. This class sends a single Email to a user. * * Usage: java QueueEmailProducer <someEmailAddress> */ public static void main(String[] args) { // An email address must be passed in on the command line if ( args.length < 2 ) { String usageMsg = "Usage: java QueueEmailProducer <winner|trailer> <emailAddress>"; System.out.println( usageMsg ); System.exit( 0 );
Listing 10.8 Continued
} // Create an instance of the EmailProducer AuctionNotificationProducer client = new AuctionNotificationProducer(); try { String notificationType = args[0]; String emailAddress = args[1]; AuctionNotification msg = null; // Create a notification based on the first arg of the command line args if ( notificationType == null || notificationType.equalsIgnoreCase("winner") ) { msg = new AuctionWinnerNotification(); ((AuctionWinnerNotification)msg).setAuctionWinPrice( "$75.00" ); }else{ msg = new AuctionTrailingBidNotification(); ((AuctionTrailingBidNotification)msg).setLeadingBid( "$100.00" ); ((AuctionTrailingBidNotification)msg).setUsersLastBid( "$75.00" ); } // Fill in some details for the Auction Win // Obviously there is no Internationalization supported here. This is // just for testing purposes. msg.setAuctionName( "Tire Auction" ); msg.setNotificationEmailAddress( emailAddress ); // Send the message client.sendMessage( msg ); } catch( Exception ex ) { ex.printStackTrace(); } } }
Running the Queue Example
To run this example, you will need to follow these steps:
Start the JMS service with the administered objects for this example.
Run the AuctionNotificationConsumer client program.
Run the AuctionNotificationProducer client program.
You will need to be sure that you have both the JNDI and JMS services up and running before you run either the consumer or producer programs. Both client programs need to also have the JNDI and JMS JAR files included in the classpath.
To start the AuctionNotificationConsumer, just type the following on a command line:
java com.que.ejb20.notification.AuctionNotificationConsumer
The program will tell you that it's listening on the queue.
To test the AuctionNotificationProducer program, type the following:
java com.que.ejb20.notification.AuctionNotificationProducer winner me@foo.com
The AuctionNotificationProducer will not display any output before exiting. However, on the AuctionNotificationConsumer console, you should see the following output:
To: me@foo.com From: AuctionSite Subject: You have the winning bid! Body: Your bid of $75.00 has become the winning bid in the Auction Tire Auction
If you are having trouble running the example, see the "Troubleshooting" section at the end of this chapter for general JMS troubleshooting tips.