J2EE Messaging
901
private Topic stockQuotesTopic = null;
private TopicSubscriber stockQuotesSubscriber = null;
private QueueConnection queueConnection = null;
private QueueSession queueSession = null;
private String stockSelector = null;
private boolean quit = false;
private void setup() throws NamingException, JMSException
{
// Obtain an initial context - JMS Vendor Specific
InitialContext ctx = WeblogicJMSDetails.getInitialContext();
// Get a queue connection
QueueConnectionFactory queueConFactory = (QueueConnectionFactory)
ctx.lookup(WeblogicJMSDetails.JMS_CONNECTION_FACTORY);
queueConnection = queueConFactory.createQueueConnection();
// Create a queue session
queueSession =
queueConnection.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);
// Get a topic connection
TopicConnectionFactory topicConFactory = (TopicConnectionFactory)
ctx.lookup(WeblogicJMSDetails.JMS_CONNECTION_FACTORY);;
topicConnection = topicConFactory.createTopicConnection();
// Look up the topic
topicSession =
topicConnection.createTopicSession(false,Session.AUTO_ACKNOWLEDGE);
stockQuotesTopic = (Topic)ctx.lookup("StockQuotesTopic");
Notice that when the PurchaserGuy creates a subscription to the StockQuotesTopic it sends in the
message filter, which indicates that it is only interested in receiving certain stocks. Once the
initialization has been done, the PurchaserGuy enters a loop in which it waits for stock quotes. It only
receives quotes that it requested to receive:
// Create a subsciber. The stockSelector filters received messages
stockQuotesSubscriber = topicSession.createSubscriber(stockQuotesTopic,
stockSelector, false);
// Set ourselves as the listener for the messages
stockQuotesSubscriber.setMessageListener(this);
}
When a stock quote arrives, the user has an option to buy. If they choose to buy, the PurchaserGuy
retrieves the queue to reply to from the message and replies with a buy order:
public void onMessage(Message message)
{
try{
// Get the stock symbol
String stockSymbol = message.getStringProperty("symbol");