MESSAGE DRIVEN BEAN
The message-driven beans perform one specific function – retrieve messages from a messageoriented middleware(MOM). As opposed to session or entity beans, client programs do not accessthese eans directly. These beans use message listeners and are activated by the EJB container when the message arrives. The client programs could be written using Java or any other language that can send messages to the MOM of our choice, which makes messaging in general and MDB in particular a good component for integration of the J2EE systems with the legacy applications.
A sample scenario of ticket reservations system that uses MDB is shown Figure:
A sample scenario of ticket reservations system that uses MDB is shown Figure:
An MDB has neither home nor remote interface, because its clients do not need to access the bean.
Code samples for BMP entity bean using weblogic server:-
Client Program: QSender.java
import javax.jms.*;
import javax.naming.*;
import java.util.*;
public class QSender {
public static void main (String arg []) {
Context ctx=null;
Hashtable ht= new Hashtable();
QueueConnectionFactory qcf=null;
QueueConnection qc=null;
QueueSession qs=null;
QueueSender qsen=null;
Queue q=null;
TextMessage tm=null;
String msg;
try {
ht.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialCo
ntextFactory");
ht.put(Context.PROVIDER_URL,"t3://localhost:7001");
ctx=new InitialContext(ht);
qcf=(QueueConnectionFactory)ctx.lookup("dinesh_jndi");
qc=qcf.createQueueConnection();
qs=qc.createQueueSession(false,javax.jms.QueueSession.AUTO_ACKNOW
LEDGE);
q=(Queue)ctx.lookup("dinesh_queue_jndi");
qsen=qs.createSender(q);
System.out.println("\nSending message to q....\n");
tm=qs.createTextMessage();
for(int i=1;i<=10;i++){
msg="Message #"+ i +"to queue";
tm.clearBody();
tm.setIntProperty("severity",i);
tm.setText(msg);
System.out.println("\nSending message....:"+msg);
qsen.send(tm);
}
msg="Stop";
tm.clearBody();
tm.setIntProperty("severity",0);
tm.setText(msg);
System.out.println("Sending message...:"+msg);
qsen.send(tm);
}
catch(Exception e) {
e.printStackTrace();
}
finally{
try{
qs.close();
qsen.close();
qc.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
Bean Class: mymdb.java
import javax.ejb.*;
import javax.jms.*;
import javax.naming.*;
public class mymdb implements MessageDrivenBean, MessageListener {
private MessageDrivenContext ctx;
public void setMessageDrivenContext(MessageDrivenContext ctx) {
this.ctx=ctx;
}
public void ejbCreate() {
}
public void ejbRemove() {
}
public void onMessage(Message msg) {
TextMessage m=(TextMessage)msg;
try {
System.out.println(m.getText());
}catch (Exception e) {}
}
}

No comments:
Post a Comment