Wednesday November 23, 2005
Developing Message Driven beans in NetBeans Today, I would like to start develop application that uses MDB bean in application tier. I hope that everyone knows Message Driven beans. If not, I shortly describe it. MDB is an enetrprise bean that enables J2EE applications to process messages asynchronously. JMS API provides two different approach for messaging:
Point-to-point messaging: Each message is addressed to a specific queue, and receiving clients extract messages from the queues established to hold their messages. Queues retain all messages sent to them until the messages are consumed or until the messages expire.
Publish/Subscribe: Clients address messages to a topic, which functions somewhat like a bulletin board. Publishers and subscribers are generally anonymous and can dynamically publish or subscribe to the content hierarchy. The system takes care of distributing the messages arriving from a topic's multiple publishers to its multiple subscribers. Topics retain messages only as long as it takes to distribute them to current subscribers.
Now, we know basic approach and I will describe other terminology. We need connection factory and destination for sending/receiving messages. A connection factory is the object a client uses to create a connection to a provider. A connection factory encapsulates a set of connection configuration parameters that has been defined by an administrator JMS server. A destination is the object a client uses to specify the target of messages it produces and the source of messages it consumes. In the PTP messaging domain, destinations are called queues. In the pub/sub messaging domain, destinations are called topics.
This application will send orders from J2SE client in application tier. Order's parameters are encapsulated in Order class. The class is shared between client and EJB module, therefore creation of library module with this class is helpfulness.
public void onMessage(Message aMessage) {
try{
if (aMessage instanceof ObjectMessage){
// process message
Order order = (Order)((ObjectMessage) aMessage).getObject();
logger.log(Level.SEVERE,order.toString());
}else{
logger.log(Level.SEVERE,
"Get message that isn't supported, only ObjectMessage is supported");
}
}catch(JMSException ex){
logger.log(Level.SEVERE, ex.getMessage());
}
}
We support only Object messages in this MDB. JMS API defines many types of messages, e.g. Text, Map, Stream and Byte messages. Different between bytes and stream messages is that stream messages are a stream of primitive values
in Java. BytesMessage allows data to be read using any type. Thus even if your payload contains a long value, you can invoke a method to read a short and it will return you something. It will not give you a semantically correct data but the call will succeed in reading the first two bytes of data. In the code above message is typed to ObjectMessage that Order object is obtained and then printed in log.