Skip Headers
Oracle® Containers for J2EE Enterprise JavaBeans Developer's Guide
10g (10.1.3.5.0)

Part Number E13981-01
Go to Documentation Home
Home
Go to Book List
Book List
Go to Table of Contents
Contents
Go to Index
Index
Go to Feedback page
Contact Us

Go to previous page
Previous
Go to next page
Next
View PDF

Sending a Message to a JMS Destination Using EJB 3.0

A client never accesses an MDB directly: rather, the client accesses an MDB by sending a message through the JMS destination (queue or topic) associated with the MDB.

To send a message to a JMS destination using EJB 3.0, do the following:

  1. Inject both the JMS destination (queue or topic) and its connection factory.

    You can inject these resources using a predefined logical name or the explicit JNDI name you defined when you configured your JMS provider. Oracle recommends that you use logical names as shown in this procedure and its examples.

    For more information, see the following:

  2. Use the connection factory to create a connection.

    If you are receiving messages for a queue, then start the connection.

  3. Create a session over the connection.

  4. Use the retrieved JMS destination to create a sender for a queue or a publisher for a topic.

  5. Create the message.

  6. Send the message using either the queue sender or the topic publisher.

  7. Close the queue session.

  8. Close the connection.

Example 29-31 shows how a servlet client sends a message to a queue.

Example 29-31 Servlet Client Sends Message to a Queue

public final class testResourceProvider extends HttpServlet {

  private String resProvider = "myResProvider";
  private HashMap msgMap = new HashMap();

  // 1a. Rely on Servlet container to inject queue connection factory
  @Resource(name=resProvider+"QueueConnectionFactories/myQCF")
  private QueueConnectionFactory qcf;

  // 1b. Rely on Servlet container to inject queue
  @Resource(name=resProvider+"/Queues/rpTestQueue")
  private Queue queue;

  public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
    doPost(req, res);
 }

  public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
   // Retrieve the name of the JMS provider from the request, 
   // which is to be used in creating the JNDI string for retrieval
    String rp = req.getParameter ("provider");
    if (rp != null) resProvider = rp;

    try {
      // 2a. Create queue connection using the connection factory
      QueueConnection qconn = qcf.createQueueConnection();
      // 2b. You are receiving messages, so start the connection
      qconn.start();

      // 3. Create a session over the queue connection
      QueueSession sess = qconn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

       // 4. Since this is for a queue, create a sender on top of the session 
       // This is used to send out the message over the queue
      QueueSender snd = sess.createSender (q);

    drainQueue (sess, q);
    TextMessage msg = null;

    // Send messages to queue
    for (int i = 0; i < 3; i++) {
      // 5. Create message
      msg = sess.createTextMessage();
      msg.setText ("TestMessage:" + i);

      // Set property of the recipient to be the MDB
      // and set the reply destination.
      msg.setStringProperty ("RECIPIENT", "MDB");
      msg.setJMSReplyTo(q);
      
      // 6. Send the message using the sender
      snd.send (msg);

      // You can store the messages IDs and sent-time  in a map (msgMap),
      // so that when messages are received, you can verify if you 
      // *only* received those messages that you were
      // expecting. See receiveFromMDB() method where msgMap gets used
      msgMap.put( msg.getJMSMessageID(), new Long (msg.getJMSTimestamp()));
    }

    // receive a reply from the MDB
    receiveFromMDB (sess, q);

     // 7. Close sender, session, and connection for queue
     snd.close();
     sess.close();
     qconn.close();
    }
    catch (Exception e) {
      System.err.println ("** TEST FAILED **"+ e.toString());
      e.printStackTrace();
    }
    finally {
    }
 }

  // Receive any messages sent to you through the MDB
  private void receiveFromMDB (QueueSession sess, Queue q)
    throws Exception {
    // The MDB sends out a message (as a reply) to this client. The MDB sets
    // the receipient as CLIENT. Thus, You will only receive messages that have 
    // RECIPIENT set to 'CLIENT'
    QueueReceiver rcv = sess.createReceiver (q, "RECIPIENT = 'CLIENT'");

    int nrcvd = 0;
    long trtimes = 0L;
    long tctimes = 0L;
    // First message needs to come from MDB.
    // May take  a little while receiving messages
    for (Message msg = rcv.receive (30000); msg != null; msg = rcv.receive (30000)) {
      nrcvd++;
      String rcp = msg.getStringProperty ("RECIPIENT");

      // Verify if message is in message Map  
      // Check the msgMap to see if this is the message that you are expecting
      String corrid = msg.getJMSCorrelationID();
      if (msgMap.containsKey(corrid)) {
        msgMap.remove(corrid);
      }
      else {
        System.err.println ("** received unexpected message [" + corrid + "] **");
      }
    }
    rcv.close();
  }

  // Drain messages from queue
  private int drainQueue (QueueSession sess, Queue q)
    throws Exception {
    QueueReceiver rcv = sess.createReceiver (q);
    int nrcvd = 0;

    // First drain any old messages from queue
    for (Message msg = rcv.receive(1000); msg != null; msg = rcv.receive(1000))
      nrcvd++;

    rcv.close();

    return nrcvd;
  }
}