DevPortal

How do I access Embedded Message Servers from MDBs?


Writing an MDB involves:

The StockMarket sample demonstrates the steps involved in writing an MDB. We will be using the SubscriberBean.java. This class is an MDB which simulates a subscriber to the StockServer that continuously sends messages with the CompanyName and the corresponding fluctuation in the price so that the subscriber can decide what to do with it.

This class implements javax.ejb.MessageDrivenBean and javax.jms.MessageListener. Destination - onMessage(..) of this class - will be invoked. It has resource-reference as the QueueConnectionFactory.

This bean has resource-env-ref as BuyQueue and SellQueue since it decides whether to buy or sell the Stock-Option. It provides a private method buy() that takes two arguments: a double value that holds the price and a string stockSymbol that holds the stock symbol.

public void
onMessage(Message msg)
{
this.message = (TextMessage)msg;
try{String stockSymbol = message.getText();
double decision=Double.parseDouble(message.getStringProperty(stockSymbol));
if(decision>0)
sell(message.getDoubleProperty(stockSymbol),stockSymbol);
elseif(decision<0)buy(message.getDoubleProperty(stockSymbol),stockSymbol));
}
catch(Exception ex){ex.printStackTrace();
}
}
The above is the implementation of the business logic (onMessage()) by the SubscriberBean. Based on the decision taken, it sends the buy or sell instructions to the StockMarket. The code for looking up the BuyQueue and sending the message to the StockMarket is as shown below:

private void
buy(double val,String stockSymbol)
{
try{Context ic = new InitialContext();
Queue someQ = (Queue)ic.lookup("java:comp/env/jms/BuyQueue");
QueueSender sender = session.createSender(someQ);
TextMessage message = session.createTextMessage();
message.setStringProperty("companyName",stockSymbol);
message.setStringProperty("tradingPersonName",stockSymbol);
}
The BuyQueue acts like a normal client for the Message Server. It looksup and sends the buying details. But the message to be sent (the name of the company and the stock symbol, the person's name) are to be passed as an argument when called. The SellQueue acts similar to the BuyQueue, but sends the details required for selling the stock.

The code below is an example of implementing the setMessageDrivenContext:

public void setMessageDrivenContext(MessageDrivenContext messageDrivenContext)
throws EJBException{}

Pramati Message Server can also be accessed by the following clients:


© Pramati Technologies 2007 Runs on Pramati Server | Feedback | Legal