Create our Message Driven Bean
MessageDrivenBean is just like our stateless bean in the sense it does not retain state. For you and I this means, do not write any code like transaction related code. In the event of any exception you will not be able to recover from this. Little bit confused? Simply understand that it is not your shopper who will have started this transaction for the exception to be returned to the client to handle it. Maybe I should have an article on Transactions. :)
The first thing to do is Annotate the Class with @MessageDriven which tells the AS that this bean is an MDB. You will also have to specify that you want to use the destination "jms/InvoiceQueue". Refer to the source below. You can then implement MessageListener interface and when you do that you implement void onMessage(Message message) method. Basically, this method encapsulates your business logic or what type of and what message to consume. As with any EJB, you will need an associated EntityManager context to do your CRUDing. But that really is not where I want to focus. What you should get from the code below is that we know we are consuming an ObjectMessage that was sent originally from the producer app. And I'd pointed out that we need an object similar to or at least capable of storing the properties of the Object (Item). We have ItemOrder in this client app to do so.
import com.factory.entities.ItemOrder;
import java.util.ArrayList;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@MessageDriven(mappedName = "jms/InvoiceQueue", activationConfig = {
@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
public class InvoiceMessageBean implements MessageListener {
@PersistenceContext
EntityManager em;
public InvoiceMessageBean() {
}
public void onMessage(Message message) {
try {
ObjectMessage objectMessage = (ObjectMessage) message;
ArrayList list = (ArrayList)objectMessage.getObject();
ItemOrder itemOrder = new ItemOrder();
itemOrder.setBarcode(Integer.parseInt(list.get(0).toString()));
itemOrder.setTotalItemsToOrder(Integer.parseInt(list.get(1).toString()));
itemOrder.setCompanyID(19284);
em.persist(itemOrder);
} catch (JMSException jmse) {
jmse.printStackTrace();
}
}
}
So that's it. You're now ready to create and consume your EJB 3 MDB. You should be able to appreciate all the asynchronous nature of MDB! Enterprise JAVA rules!
Nice article and the code. Helpful for many programmer. Keep it up!
ReplyDelete