Implementing an Asynchronous Message Listener
The ServerApplication class implements a single asynchronous message listener to receive customer inquiries. The message listener is implemented through the JMS MessageListener and MessageConsumer interfaces.
import javax.jms.MessageListener;
import javax.jms.MessageConsumer;
public class ServerApplication extends SimpleApplication implements
MessageListener
...
receiver.setMessageListener(this);
The MessageListener object receives the incoming customer request messages asynchronously from the requestor application. The MessageConsumer's setMessageListener() method is necessary to activate the listener so that it is able to receive messages.
In JMS, each message listener supports a single onMessage() method. In this example, the method is called whenever the server receives a customer request message. This implementation of onMessage() copies, from the request message, the customer information needed to make the database query. It then issues the query and builds the reply message, calling constructReplyMessage() to map data from the customer record to the reply message fields. The following code from onMessage() shows these steps.
public void onMessage(Message message)
{
try {
Message reply;
String command =
message.getStringProperty(AppConstants.CMD_PROP);
if (command.equals(AppConstants.CUSTOMER_QUERY_CMD)) {
try {
if (message instanceof MapMessage) {
MapMessage queryMsg = (MapMessage) message;
String firstName =
queryMsg.getString(AppConstants.FIRST_NAME_FIELD);
String lastName =
queryMsg.getString(AppConstants.LAST_NAME_FIELD);
String location =
queryMsg.getString(AppConstants.LOCATION_PROP);
CustDB.CustRecord customer = custDB.lookup(firstName,
lastName, location);
reply = constructReplyMsg(customer);