Thursday, 21 May 2009

3-How to Develop Message-Driven Beans

Files located in the package src/mdbex;
FILE : OrderVerifierHome.java
package mdbex;

import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;

public interface OrderVerifierHome extends EJBHome{
OrderVerifier create() throws CreateException, RemoteException;
}

FILE: OrderVerifier.java
package mdbex;

import java.rmi.RemoteException;

public interface OrderVerifier extends javax.ejb.EJBObject{
}

FILE: OrderVerifierMDB.java
package mdbex;

import java.util.*;
import java.io.*;
import java.rmi.*;
import javax.naming.*;
import javax.ejb.*;

import javax.jms.MessageListener;

import javax.ejb.CreateException;
import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import javax.naming.InitialContext;
import javax.naming.NamingException;

public class OrderVerifierMDB implements MessageDrivenBean, MessageListener
{

private MessageDrivenContext mdbContext;

/**
* this method is invoked by the container. it gives the MDB instance a reference to its context.
* this can be empty also.
* @param ctx MessageDrivenContext for this instance
*/
public void setMessageDrivenContext(MessageDrivenContext ctx) {
mdbContext = ctx;
}

/**
* @exception javax.ejb.CreateException if there is
* a communications or systems failure
*/
public void ejbCreate () throws CreateException {
System.out.println("****ARSSSSSSSSSSssssssss********");
}

/**
*/
public void ejbRemove() {
mdbContext = null;
}

// Implementation of MessageListener
/**
*@param msg The Message from the JMS-Server
*/
public void onMessage(Message msg) {
TextMessage orderMessage = (TextMessage) msg;
try {
String orderId = orderMessage.getText();

System.out.println("************ Order Information ************");
System.out.println("****ARSSSSSSSSSSssssssss Order Id is : "+orderId);
System.out.println("************ Order Information Ends ************");
System.out.println();

try {
System.out.println("Creating an order with status:Submitted");
Context initialContext = new InitialContext();
Object object = initialContext.lookup("mdbex/OrderARS");
OrderARSHome orderHome =
(OrderARSHome)javax.rmi.PortableRemoteObject.narrow(object,
OrderARSHome.class);
// OrderARS order = (OrderARS)orderHome.create("1", "Submitted", 100);
OrderARS order = orderHome.findByPrimaryKey(orderId);
order.setStatus("Verified");

} catch (Exception ex) {
System.err.println(ex);
ex.printStackTrace();
}
}
catch(JMSException ex) {
ex.printStackTrace();
}
}

//
// Implementation of MessageListener
/////
}