How to Develop Message-Driven Beans p.20
written by Jason Westra

Download files assoicated with this article

Listing 1: MessageLogBean.java source
package jdj.january;
import javax.ejb.CreateException;
import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;

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

/**
 * @author jwestra  Verge Technologies Group, Inc. 2000
 */
public class MessageLogBean implements MessageDrivenBean, MessageListener {

  private MessageDrivenContext m_context;

  /**
  * Public, no argument constructor
  */
  public MessageLogBean() {}

  /**
   * ejbActivate is required by the EJB Specification
   */
  public void ejbActivate() { }

  /**
   * ejbRemove is required by the EJB Specification
   */
  public void ejbRemove() {
    m_context = null;
  }

  /**
   * ejbPassivate is required by the EJB Specification
   */
  public void ejbPassivate() { }

  /**
   * Sets the MessageDrivenContext.
   *
   * @param ctx               MessageDrivenContext Context for session
   */
  public void setMessageDrivenContext(MessageDrivenContext ctx) {
    m_context = ctx;
  }

  /**
   * ejbCreate() with no arguments is required by the EJB 2.0 specification
   */
  public void ejbCreate () throws CreateException {}

  /**
   * Implementation of MessageListener.
   *
   * onMessage logs to sysout.  Using an asynchronous, message-driven bean
   * to log eliminates the bottleneck of a synchronized log manager in
   * your application and enables distributed logging from remote clients.
   */
  public void onMessage(Message msg) {
    // everything is within a try block to ensure no exceptions are thrown
    // from within this method
    try {
      TextMessage tm = (TextMessage) msg;
      String text = tm.getText();
      System.out.println("MessageLogBean : " + text);
    }
    catch(Exception ex) {
      // catch all exceptions
      ex.printStackTrace();
    }
  }
}

Listing 2: Excerpt from ejb-jar.xml deployment descriptor
<message-driven>
      <ejb-name>MessageLogBean</ejb-name>
      <ejb-class>jdj.january.MessageLogBean</ejb-class>
      <transaction-type>Container</transaction-type>

      <message-driven-destination>
        <jms-destination-type>javax.jms.Topic</jms-destination-type>
      </message-driven-destination>
</message-driven>

Listing 3: Weblogic Server config.xml entries
<JMSServer Name="myJMSServer" Targets="myServer">
    <JMSTopic JNDIName="LogMgrTopic" Name="LogMgrTopic"/>
</JMSServer>