Java Q&A: Message-Driven Beans & EJB 2.0
by Surla Rao

Listing One 
package example.MDBean;

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;

/** @author Surlu M. Rao */
public class MessagePipeBean implements MessageDrivenBean, MessageListener {
  private MessageDrivenContext m_context;
  /** This method is required by the EJB Specification */
  public void ejbActivate() {
  }
  /** This method is required by the EJB Specification */
  public void ejbRemove() {
    m_context = null;
  }
  /** This method is required by the EJB Specification */
  public void ejbPassivate() {
  }
  /** Sets the session context. 
   * @param ctx     MessageDrivenContext Context for session
   */
  public void setMessageDrivenContext(MessageDrivenContext ctx) {
    m_context = ctx;
  }
  /** ejbCreate() with no arguments is required by EJB 2.0 specification */
  public void ejbCreate () throws CreateException {
  }
  /** MessageListener implementation
   * This method just takes the message and pipes to the system output.
   * @exception  completely handles all exceptions
   */
  public void onMessage(Message msg) {
    TextMessage tm = (TextMessage) msg;
    try {
      String text = tm.getText();
      System.out.println("MessagePipeBean piped : " + text);
    }
    catch(Exception ex) {
      ex.printStackTrace();
    }
  }
}

Listing Two 
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise 
JavaBeans 2.0//EN" "http://java.sun.com/j2ee/dtds/ejb-jar_2_0.dtd">

<ejb-jar>
 <enterprise-beans>
    <message-driven>
      <ejb-name>MessagePipeBean</ejb-name>
      <ejb-class>example.MDBean.MessagePipeBean</ejb-class>
      <transaction-type>Container</transaction-type>
      <message-driven-destination>
        <jms-destination-type>javax.jms.Topic</jms-destination-type>
      </message-driven-destination>
      <security-identity>
        <run-as-specified-identity>
          <role-name>everyone</role-name>
        </run-as-specified-identity>
      </security-identity>
    </message-driven>
 </enterprise-beans>
</ejb-jar>


Listing Three 
<?xml version="1.0"?>
<!DOCTYPE weblogic-ejb-jar PUBLIC "-//BEA Systems, Inc.
//DTD WebLogic 6.0.0 EJB//EN" "http://cool.mdb.bean">

<!-- MessageDriven bean Weblogic deployment descriptor -->
<weblogic-ejb-jar>
  <weblogic-enterprise-bean>
    <ejb-name>MessagePipeBean</ejb-name>
    <message-driven-descriptor>
      <pool>
        <max-beans-in-free-pool>100</max-beans-in-free-pool>
        <initial-beans-in-free-pool>10</initial-beans-in-free-pool>
      </pool>
      <destination-jndi-name>MsgPipeTopic</destination-jndi-name>
    </message-driven-descriptor>
    <jndi-name>MessagePipeBean</jndi-name>
  </weblogic-enterprise-bean>
</weblogic-ejb-jar>







1

