Home > Articles > Programming > Java

This chapter is from the book

This chapter is from the book

MDB EJB Sample Application: RosterMDB

The RosterMDB application consists of four parts: an MDB, which consumes messages and publishes messages; a JMS servlet client, which produces messages; a JMS message subscriber; and two types of messages that are exchanged among them. In the following example, an HTML form is used to submit student and schedule information to the JMS servlet. The servlet extracts the information from the form, creates a message and sends it to a destination. Upon receiving the message, the MDB extracts the fields from the message and inserts them into a database. After that, the MDB selects the studentID field for all the students who have registered for that ScheduleID, creates a text message with the studentID list, and then publishes it to a topic destination. The JMS subscriber receives the persistent messages when it's activated. Figure 13-4 illustrates this interaction.

Figure 13-4 A message-driven bean consuming messages

The client application, MessageSender, creates a JMS message type, ObjectMessage, and then embeds the RosterVO object in the message body and sends it to the Queue destination. When the JMS message arrives, the container selects a RosterMDB instance, executes the onMessage() method, and bypasses the ObjectMessage as an argument to the method. The RosterMDB executes the logic to extract and insert the content of the message to the database using the RosterDAO helper class. The MDB then retrieves the current list of students who are registered for a particular class and publishes persistent messages. Another JMS client program, DurableSubscriber (a JMS subscriber), retrieves messages published by RosterMDB to the topic destination and, with the help of the MessageHandler class, prints them out.

We'll use the following steps to implement the RosterMDB application:

  1. Define and implement a message object—RosterVO.

  2. Implement the MDB class—RosterMDB.

  3. Implement the helper class—RosterDAOand RosterDAOException.

  4. Compile the RosterMDB, RosterVO, and RosterDAO.

  5. Implement a servlet JMS message sender client—MessageSender.

  6. Implement JMS message subscriber client—DurableSubscriberand MessageHandler.

  7. Compile JMS clients—MessageSender, DurableSubscriber, and MessageHandler.

  8. Package the EJB component into the RosterJARfile.

  9. Package the Web component into the RosterWARfile.

  10. Package the client into the clientjarfile.

  11. Package the ejb-jar, client-jar, and warfiles into the RosterApp.earfile.

  12. Deploy the RosterApp.earfile.

  13. Test the application.

Step 1: Defining and Implementing a Message

In this example, we'll send a schedule, a student identification, and registration date using the JMS message (ObjectMessage) type to encapsulate our information. The example objective is to create an object, RosterVO, to hold the information; to encapsulate it as an ObjectMessage message; and, finally, to send it from a servlet to a message consumer. The roster value object class, RosterVO, is serializable and consists of three fields,—schedule, student identification, and date—as well as the corresponding getter methods.

public class RosterVO implements Serializable 
{ 
....private String scheduleID; 
  private String studentID;
  private Date theDateStamp; 

  public RosterVO(String schedID, String studID, Date aDate)
  {
      scheduleID = schedID;
      studentID = studID;
      theDateStamp = aDate; 
  } 

  public String getScheduleID()
  {
      return this.scheduleID; 
  } 

  public String getStudentID()
  {
      return this.studentID;
  }

  public Date getTheDate() 
  { 
      return this.theDateStamp; 
  } 

} //;-) end of RosterVO 

Step 2: Implementing the MDB Class

There are two parts to this class. The first part of RosterMDB receives the message from the queue destination, extracts the schedule, student, and registration date information from the message, and inserts this data into the database table, roster. The roster table is used to track the student class registration. The second part of RosterMDB uses the scheduleID from the previous message to retrieve all the studentID values from the roster table and then publish the list as a persistent message to a topic destination.

The RosterMDB class must implement the javax.ejb.MessageDrivenBean and java.jms.MessageListener interfaces. The empty constructor, RosterMDB(), along with the required setMessageDrivenContext(mdct) is used by the container to pass the bean context reference to the bean instance.

public class RosterMDB implements MessageDrivenBean, MessageListener 
{ 

The ejbCreate() method is invoked by the container. At its completion, the RosterMDB instance has transitioned to the ready pool state. To create this queue, use the JNDI lookup method to get the initial context reference. Use this context reference to retrieve the Queue Connection factory, java:comp/env/jms/TheQueFactory, and the queue destination, java:comp/env/jms/TheQue. Then create the Queue connection, createQueueConnection(), to enable queue messages acceptance.

public void ejbCreate()
{
    System.out.println(" -- In RosterMDB - ejbCreate() -- "); 

    Context jndictx = null; 
    QueueConnectionFactory queConnFactory = null;
    TopicConnectionFactory topicConnFactory = null; 

    try {
       jndictx = new InitialContext(); 
       //For P2P access administrative objects
       queConnFactory = (QueueConnectionFactory)
jndictx.lookup("java:comp/env/jms/TheQueFactory");
       queue = (Queue) jndictx.lookup("java:comp/env/jms/TheQue");
       queConnection = queConnFactory.createQueueConnection(); 

We also must appropriate administrative objects for the pub/sub messaging model, as shown below. Using the JNDI lookup, retrieve the factory and the destination object and then create the connection and the session objects, as in the following example:

try {
//For Pub/sub access administrative objects
   topicConnFactory = (TopicConnectionFactory)
jndictx.lookup("java:comp/env/jms/TheTopicFactory");
   topic = (Topic) jndictx.lookup("java:comp/env/jms/TheTopic");
   topicConnection = topicConnFactory.createTopicConnection();
   topicSession = topicConnection.createTopicSession(false, Ses-sion.AUTO_ACKNOWLEDGE); 
} catch (NamingException ne) {
    ne.printStackTrace();
} catch ( JMSException je) {
    je.printStackTrace();
} catch (Exception e) {
    e.printStackTrace();
} 

} 

Unlike session and entity beans, MDBs don't have local and remote interfaces. When messages arrive, the container automatically invokes the onMessage(msg) method in the bean instance and passes the message as a parameter. Verify whether the received message is of the ObjectMessage type using the instance of the objMsg.getObject() method. Then, use the getter methods to extract and write out scheduleID, studentID, and the date.

public void onMessage(Message inMessage)
{
    System.out.println(" -- In RosterMDB - onMessage() -- \n\n");
    RosterVO rosterVO = null; 

    try {
       if( inMessage instanceof ObjectMessage)
       { 
          ObjectMessage objMsg = (ObjectMessage) inMessage;
          msgID = objMsg.getJMSMessageID();
          rosterVO = (RosterVO) objMsg.getObject(); 

       } Else {
       // insert into database
       // throws Exception
    rosterDAO = new RosterDAO(); 
    rosterDAO.insert(rosterVO);
    //create a message to publish callPublisher(rosterVO.getScheduleID());
    } catch (MessageFormatException me) 

Using the RosterDAO helper class, invoke insert(), an insert method, to insert the retrieved data into a roster table in the database. (This is discussed further in Step 3 below.) The ejbRemove() method is called by the container before the container ejects the bean instance from memory.

The second part of RosterMDB, the callPublisher() method, retrieves the studentID list with the help of the getStudentList() method, creates a session to connect to the topic destination, and then adds the student list and the previous message's correlation ID to the message "TextMessage message type" and then publishes it. Notice that the publish() method takes TextMessage as an argument, sets the delivery mode to persistent, sends it with default priority and a value of zero to indicate that the message has no expiration date.

public void callPublisher(String scheduleID) 
{
  try {
   if (rosterDAO == null) rosterDAO = new RosterDAO();
   String textList = rosterDAO.selectStudents(schedID);
   publisher = topicSession.createPublisher(topic);
   TextMessage textMessage = topicSession.createTextMessage();
    textMessage.setText("Publishing Search Results :"+textList);
    textMessage.setJMSCorrelationID(msgID); 

  publisher.publish(textMessage,
      javax.jms.DeliveryMode.PERSISTENT,
      javax.jms.Message.DEFAULT_PRIORITY,0
      ); 
  } catch (MessageFormatException me) {
      me.printStackTrace();
  .............................
} 

Step 3: Implementing the Helper Class

We've separated the database access logic from RosterMDB and separated it in the RosterDAO class. JNDI lookup is used to access the datasource in the constructor of the RosterDAO . The RosterDAO methods getConnection(), closeConnection(), closeResultSet(), and closeStatement() are used to manipulate the connection to the data source.

After extracting the RosterVO object from the message, RosterMDB then invokes the insert() method on RosterDAO, which inserts the scheduleID, studentID, and date in the database table, roster. RosterDAO uses the Prepared Statement feature of the JDBC API to create the SQL statement; use executeUpdate() to run the SQL statement.

Let's look at the code fragment showing the implementation of the JNDI lookup and the insert() and selectStudents() methods in the RosterDAO helper class:

//JNDI lookup for datasource 
           InitialContext ictx = new InitialContext();
          dataSource = (DataSource)
ictx.lookup("java:comp/env/jdbc/JCampDS"); 
          System.out.println("RosterDAO jcampDataSource lookup OK!"); 

       } catch (NamingException ne) {
           throw new RosterDAOException("NamingException while

public void insert(RosterVO rosterVO) throws RosterDAOException
   { 

    System.out.println("RosterDAO - insert() ");
    PreparedStatement pstmt = null; 

    Connection conn = this.getConnection(); 

    try 
    { 
//do the actual insert into the roster table.
      pstmt = conn.prepareStatement("Insert into roster(ScheduleID, StudentID, theDate) values(?,?,?)"); 

      pstmt.setString(1, rosterVO.getScheduleID());
      pstmt.setString(2, rosterVO.getStudentID()); 
      System.out.println("after setting scheduleID and studen-tID****\n"); 

      pstmt.setDate(3, rosterVO.getTheDate()); 

          System.out.println(" RosterDAO prepared statment OK"); 

          pstmt.executeUpdate(); 
          System.out.println(" RosterDAO roster inserted"); 

      } catch(SQLException se) {
          throw new RosterDAOException(" Query exception "+se.getMes-
sage()); 
      }  finally {
          closeStatement (pstmt);
          closeConnection(conn);
      } 
     System.out.println("RosterDAO - insert done"); 
} 

The selectStudent() method executes the SQL select and retrieves the studentID and returns it to the RosterMDB. Notice that the query statement (selectStatement) consists of SELECT, which selects from the roster table all studentID values that contain the scheduleID value passed as an argument. The method then creates a String studentIDList (which consists of studentID values retrieved from the roster table) and returns the list to the MDB instance.

public String selectStudents(String schedID) throws RosterDAOException 
 {
  String studentIDList = "List: ";
  PreparedStatement pstmt = null;
  Connection conn = this.getConnection();
  try {
     String selectStatement = "SELECT studentID FROM roster WHERE 
ScheduleID= ?";
       pstmt = conn.prepareStatement(selectStatement); 

       pstmt.setString(1, schedID); 
       ResultSet rset = pstmt.executeQuery();
       while(rset.next())
         {
          studentIDList = studentIDList +", "+rset.getString("studen-tID"); 
         }
       pstmt.close(); 
       conn.close(); 
       } catch(SQLException se) {
           throw new RosterDAOException(" SQL exception while attempt-
ing to open connection ="+se.getMessage()); 
         }

  return studentIDList; 
} 

Step 4: Compiling RosterMDB, RosterVO and RosterDAO

Now, we're ready to compile the MDB application, so change directory to APPHOME \chapter13\roster and run compileMDB to compile and generate the following classes: RosterMDB.class, RosterDAO.class, and RosterDAOException.class. Next, change directory to APPHOME\chapter 13\common and execute compile.bat, which compiles and generates the RosterVO.class file. Before we can package the MDB application, we need to implement the clients.

Step 5: Writing the Servlet JMS Client MessageSender

The MessageSender is a JMS servlet client—its job is to process an HTML form request, create the RosterVO value object, encapsulate the RosterVO in a JMS ObjectMessage, and then send the RosterVO to a queue destination.

The following code snippet shows the JNDI lookup for the TheQueFactory and TheQue in the init() method. Then, the queue connection and the queue session are created. These are the same administrative objects in this application—all cooperating JMS clients—used to send and receive messages. Recall that the RosterMDB also used JNDI lookup to retrieve and use the same java:comp/env/jms/TheQueFactory and java:comp/env/jms/TheQue to create the queue connection and session to read the messages. The MessageSender depends on the very same administrative objects to create the necessary objects to send messages to the queue.

public void init()
{
    QueueConnectionFactory queConnFactory = null;
//look up jndi context
    try {
    jndictx = new InitialContext();

    queConnFactory = (QueueConnectionFactory)
jndictx.lookup("java:comp/env/jms/TheQueFactory");
      que = (Queue) jndictx.lookup("java:comp/env/jms/TheQue"); 

The queConnection is created, followed by the creation of queSession, which is nontransactional but supports auto-acknowledgement, as shown in the code fragment that follows.

//setup for P2P - get the Queue destination and sesssion setup
         queConnection = queConnFactory.createQueueConnection();
         queSession = queConnection.createQueueSession(false, Ses-sion.AUTO_ACKNOWLEDGE);
         } catch (NamingException ne) { 

The doPost() method extracts the ScheduleID and StudentID value from the request object and then creates a current date. The fields are then used to create a RosterVO value object. The sendMessage() method is then invoked.

The sendMessage() method creates a QueueSender object. Next, it creates an ObjectMessage object. Finally, it takes the RosterVO, wraps it within this object message format, and sends it to the queue destination.

public void doPost(HttpServletRequest req, HttpServletResponse resp)
{
    System.out.println("************ RosterClient ************\n");
//extract the schedule and student id from the form
   String schedID = req.getParameter("ScheduleID");
   String studentID = req.getParameter("StudentID");
//convert java.util.Date to java.sql.Date
   Calendar currentTime = Calendar.getInstance();
   java.sql.Date now = new java.sql.Date((currentTime.getTime()).get-Time()); 

rosterVO = new RosterVO(schedID, studentID, now); 

   boolean flag = sendMessage(rosterVO);
         if (flag)
          System.out.println("Message Sent!");
         Else
          System.out.println("Message Not Sent!"); 
} 

public boolean sendMessage(RosterVO obj)
{
    QueueSender queSender = null; 

 try { 
//create the sender object
   queSender = queSession.createSender(que);
//create a ObjectMessage type 
   ObjectMessage objMessage = queSession.createObjectMessage();
//encapsulate the rosterVO in ObjectMessage
   objMessage.setObject(obj);
//now send the ObjectMessage to the destination.
   queSender.send(objMessage); 
 } catch (JMSException je) {
   System.out.println(" Error in sending message: "+je.toString());
   return false;
 } 

//send message
   return true;
} 

Step 6: Implementing the JMS Client DurableSubscriber

The DurableSubscriber is a Java program that implements durable JMS subscriber client logic. It connects to the topic destination, retrieves messages, and prints them out. The program consists of three sections—the first section completes the setup to the administrative objects and creates the connection and session objects in the constructor as in the following code snippet:

try {
   jndictx = new InitialContext();
//setup for pub/sub - get the Topic destination and sesssion setup
   topicConnFactory = (TopicConnectionFactory) jndictx.lookup("java:comp/env/jms/TheTopicFactory");
   topicConnection = topicConnFactory.createTopicConnection();
   topicConnection.setClientID("DurableSubscriber");
   topicSession = topicConnection.createTopicSession(false, Ses-sion.AUTO_ACKNOWLEDGE);
   topic = (Topic) jndictx.lookup("java:comp/env/jms/TheTopic"); 
} catch (NamingException ne) { 

The durable subscriber in the pub/sub model must set the client ID, setClientID(DurableSubscriber), in order for the JMS provider to track the subscribers who have retrieved the messages.

The second section consists of the subscribeToTopic() method, which creates the JMS durable subscriber client by passing the topic destination and the string description as arguments and watches for messages arriving at the Topic destination. The third section directs the message listener and directs message events to the MessageHandler object, which prints the message retrieved from the destination to the terminal.

public void subscribeToTopic ()
{
    try {
      TopicSubscriber topicSubscriber = topicSession.createDurableSub-scriber(topic, "student list");
      topicSubscriber.setMessageListener(new MessageHandler());
      topicConnection.start();
    } catch (JMSException je) { 

The MessageHandler is a simple Java program that implements the MessageListener interface and the logic for the onMessage() method. The onMessage() method extracts the content of the text message and its JMS correlation ID field from the message and is used for tracking messages.

public class MessageHandler implements MessageListener
{
    public static void main(String argv[])
   {
       MessageHandler mh = new MessageHandler();
   }
   public void onMessage(Message message)
   {
   try {
     TextMessage textMessage = (TextMessage) message;
     String text = textMessage.getText(); 
    System.out.println(" Received by Subscriber\n"+text+"\n === after message "+message.getJMSCorrelationID());
     } catch(Exception e) {
     System.out.println("Error receiving message from Topic "+e.get-Message());
     }
   } //onMessage()
} //Message Handler 

Step 7: Compiling JMS Clients

Before we can package the MDB sample application, we need to compile both the MessageSender and DurableSubscriber clients. To compile the servlet client, change directory to APPHOME\chapter13\web\servlet and then run compile.bat, which compiles and generates the MessageSender.class file.

Next, go to the APPHOME\chapter13\client subdirectory and run compile.bat, which compiles and generates DurableSubscriber.class and MessageHandler.class.

The Message.htm is a simple HTML form page which is used to send scheduleID and studentID values for testing purposes.

Step 8: Packaging the EJB Component

Before we can run and deploy our MDB sample application, we must first package our application "parts" into client, ejb, and Web components.

  1. First, create an enterprise archive file to hold the clientjar, ejb-jar, and warfiles. Start the j2sdkee application and the deployment tool as discussed in the appendix.

  2. When the deployment tool GUI comes up, select File|New|Application. A new application window pops up, showing Application File Name and Application Display Name. Use the Browse button to set the location of the destination directory. For this example, select APPHOME\chapter13. For the file name, enter RosterApp.ear, as shown in Figure 13-5. Click OK. A RosterApp file is now created under the Files in the left area of the deployment GUI. Two ear deployment descriptors, application.xml and sun-j2ee-ri.xml, along with a MANIFEST.MF file, are found in the right section of the GUI.

    Figure 13-5 Creating an enterprise archive .le —RosterApp.ear

  3. Using the deployment tool, click File|New|Enterprise Bean to open the New Enterprise Bean Wizard. Click Next.

  4. Click Create New EJB File in Application (this is the default). Under EJB Display Name, enter RosterJAR.

  5. Click Edit. An Edit Content of RosterJARwindow appears. Use the top half of this window to browse the directory tree structure. The bottom half of the window shows all the files currently added to the RosterJARfile.

  6. Click the APPHOME\chapter13\rosterdirectory and highlight the Roster-DAO.class, RosterDAOException.class, and RosterMDB.class, adding them individually. The files should display on the bottom half of the window.

  7. Change the directory to APPHOME\chapter13\commonand add Rost-erVO.class. Figure 13-6 shows the classes added to the RosterJARfile.

    Figure 13-6 Packaging Roster bean into the RosterJAR .le

  8. Click OK. The pop-up window closes, and the added class files are shown on the content section of the Wizard (see Figure 13-7). Click Next.

    Figure 13-7 Contents of RosterJAR .le

  9. Select Message-Driven under the Bean Type option. Using the Enterprise Bean Class pull-down menu, select RosterMDB.class. Enter RosterEJB as the Enterprise Bean Name. The Enterprise Bean Display Name should display RosterEJBas shown in Figure 13-8. Click Next, as the MDB doesn't have any local or remote interfaces.

    Figure 13-8 Specifying the bean type and class

  10. Under Transaction Management, select Container Managed. This will show the onMessage(arg)method and the default transaction attribute as Required. Leave as is and click Next.

  11. Next, select the destination type, the destination queue name, and the connection factory name. Click Queue. Using the pull-down menu, select MyQue under Destination and MyQueFactory under Connection Factory. The destination, MyQue, and the connection factory, MyQueFactory, were previously created using the Tool|Server Configuration and then selecting the JMS option to add both MyQue and MyQueFactory, as shown in Figure 13-9. (These administrative objects were precreated by the administrator and are discussed in the Appendix.)

    Figure 13-9 Specifying the destination type,destination queue,and connection factory

  12. Click Next twice, as we are not setting any Environment Entries Reference in the code and there are no references to EJBs in the code.

  13. Use the tool to map the resource referenced in the code to resource factories. In the ejb-jarfile, map the data source, the destination, and the queue factory. Under Coded Name, enter jdbc/JcampDS; select Type from the pull-down menu, and enter javax.sql.DataSource. Under Authentication, select Container and check the Sharable option. Under Deployment Setting, set the JNDI Name and enter jdbc/Cloudscape. Enter j2ee as both the user name and password, as shown in Figure 13-10, and click Next.

    Figure 13-10 Specifying the data source

  14. Now, map the queue connection factory and topic connection factory. Under Coded Name, enter jms/TheQueFactory. Under Type, select javax.jms.QueueConnectionFactoryfrom the pull-down menu. Set the Authentication to Container and check the Sharable option. Under JNDI Name enter MyQueFactory. Use j2ee as both user name and password, and then enter jms/TheTopicFactory as the Coded Name. Select javax.jmx.TopicConnectionFactoryfrom the pull-down menu and enter MyTopicFactory as the JNDI name, with j2ee as the user name and password (as shown in Figure 13-11).

    Figure 13-11 Specifying resource factories references and JNDI name

    The coded names, jdbc/JcampDS, jms/TheTopicFactory, and jms/TheQue-Factory, are the names the JNDI lookup uses to find objects in code. During deployment, these virtual names are mapped to real objects such as jdbc/Cloudscape, MyTopicFactory, and MyQueFactory, which are defined in the target application environment. At runtime, the application is able to access the actual data source object and the QueueConnectionFactory defined in the deployment environment.

  15. Click Next. Click Add and, under Coded Name, enter jms/TheQue. For Type, select javax.jms.Queuefrom the pull-down menu and enter jms/TheTopic. Select javax.jms.Topic from the pull-down menu. Under the JNDI name, enter MyQue for jms/TheQue and MyTopic for jms/TheTopic, as shown in Figure 13-12. Click Next. As there are no security options being set, click Next again. Click Finish to complete the ejb-jar file packaging The deployment tool should display a RosterJAR under the RosterApp on the left hand side of the GUI. The Content section to the right should display the ejb-jar-ic.jar file as shown in Figure 13-13.

    Figure 13-12 Specifying resource environment references

    Figure 13-13 Content of RosterApp

Creating the Deployment Descriptor

The wizard has collected the input and created a deployment descriptor for the ejb-jar file for the RosterMDB EJB application. Notice the destination type, the factory, and the resource references such as the JCampDS, TheQueFactory, TheTopicFactory, TheQue, TheTopic, and the onMessage() business method are specified in the deployment descriptor.

<ejb-jar>
    <display-name>RosterJAR</display-name>
    <enterprise-beans>
    <message-driven>
<display-name>RosterEJB</display-name>
     <ejb-name>RosterEJB</ejb-name>
     <ejb-class>j2eebootcamp.developingEJB.chapter13.roster.Roster-MDB</ejb-class>
      <transaction-type>Container</transaction-type>
   <message-driven-destination>
    <destination-type>javax.jms.Queue</destination-type>
   </message-driven-destination>
   <security-identity>
     <description></description>
       <run-as>
        <description></description>
        <role-name></role-name>
       </run-as>
     </security-identity>
     <resource-ref>
       <res-ref-name>jdbc/JCampDS</res-ref-name>
       <res-type>javax.sql.DataSource</res-type>
       <res-auth>Container</res-auth>
       <res-sharing-scope>Shareable</res-sharing-scope>
     </resource-ref>
     <resource-ref>
       <res-ref-name>jms/TheQueFactory</res-ref-name>
       <res-type>javax.jms.QueueConnectionFactory</res-type>
       <res-auth>Container</res-auth>
       <res-sharing-scope>Shareable</res-sharing-scope>
      </resource-ref>
      <resource-ref>
       <res-ref-name>jms/TheTopicFactory</res-ref-name>
       <res-type>javax.jms.TopicConnectionFactory</res-type>
       <res-auth>Container</res-auth>
       <res-sharing-scope>Shareable</res-sharing-scope>
      </resource-ref>
      <resource-env-ref>
       <resource-env-ref-name>jms/TheQue</resource-env-ref-name>
       <resource-env-ref-type>javax.jms.Queue</resource-env-ref-type>
      </resource-env-ref>
      <resource-env-ref>
       <resource-env-ref-name>jms/TheTopic</resource-env-ref-name>
       <resource-env-ref-type>javax.jms.Topic</resource-env-ref-type>
      </resource-env-ref>
     </message-driven>
   </enterprise-beans>
   <assembly-descriptor>
    <container-transaction>
      <method>
        <ejb-name>RosterEJB</ejb-name>
        <method-intf>Bean</method-intf>
        <method-name>onMessage</method-name>
        <method-params>
           <method-param>javax.jms.Message</method-param>
        </method-params>
      </method>
      <trans-attribute>Required</trans-attribute>
     </container-transaction>
   </assembly-descriptor>
</ejb-jar>

Step 9: Packaging the Web Component

Now, we're ready to package the servlet, JSP, and HTML files as Web components for the MDB application.

  1. Using the deployment GUI, click File|New|Web Component to open a New Web Component Wizard. Click Next.

  2. Select Create New WAR File in Application. Ensure that RosterAppis selected in the pull-down menu. Under WAR Display Name, enter Roster-WAR. Click Edit. An Edit Content of RosterWAR window appears. Use the top part of this window to navigate to APPHOME\chapter13\web\servlet, and highlight the MessageSender.class. Click Add. The Content of Ros-terWAR window should display the added class. Go up a directory and add the Message.htmfile. Now go back to APPHOME\chapter13\commonand add RosterVO.classto the RosterWARfile. This is shown in Figure 13-14. Click OK.

  3. Click Next. The Web component type is servlet. Select Servlet, and then click Next again.

  4. Figure 13-14 Packaging the MessageSender.Client into the war .le

  5. Use the pull-down menu to select MessageSenderas the Servlet Class. MessageSendershould automatically appear as the Web Component Name. Leave the startup load sequence position to the default load at any time, as shown in Figure 13-15.

    Figure 13-15 Specifying the client name and type

  6. Click Next twice, as there are no initialization parameters being set. Click Add and enter RosterAlias. The alias is useful because it enables the developer to give a virtual name and map it to the actual Web component on the server. Click Next until Resource References appears.

  7. Click Add. Under Coded Name, enter jms/TheQueFactory. Under the Type pull-down menu, select javax.jms.QueueConnectionFactory. Under Authentication, select Container. Check the Shareable option. Under the JNDI Name, enter MyQueFactory with j2ee for both the user name and password. See Figure 13-16 for an example.

    Figure 13-16 Specifying the resource factory reference and JNDI name

  8. Click Next. Enter jms/TheQue under Coded Name and take the default value, javax.jms.Queueas the Type, and for JNDI name enter MyQue, as shown in Figure 13-17.

    Figure 13-17 Specifying the queue destination and JNDI name

  9. Click Add on the Welcome Files area. Using the pull-down menu, select the Message.htmfile as illustrated in Figure 13-18. Click Next twice.

    Figure 13-18 Specifying the default home page

  10. Click Finish. Note the RosterWARfile under the RosterAppon the left hand side of the deployment GUI as well as the JNDI Names and references (as shown in Figure 13-19).

    Figure 13-19 RosterWAR .le

Deployment Descriptor for the Web Component

The deployment tool has recorded the inputs and created a deployment descriptor file (web.xml) for the Web component (as listed below).

<web-app>
     <display-name>RosterWAR</display-name>
     <servlet>
     <servlet-name>MessageSender</servlet-name>
     <display-name>MessageSender</display-name>
     <servlet-class>j2eebootcamp.developingEJB.chapter13.web.servlet.Mes-sageSender</servlet-class>
     </servlet>
     <servlet-mapping>
     <servlet-name>MessageSender</servlet-name>
     <url-pattern>/RosterAlias</url-pattern>
     </servlet-mapping>
     <session-config>
     <session-timeout>30</session-timeout>
     </session-config>
     <welcome-file-list>
    <welcome-file>Message.htm</welcome-file>
     </welcome-file-list>
     <resource-env-ref>
     <resource-env-ref-name>jms/TheQue</resource-env-ref-name>
     <resource-env-ref-type>javax.jms.Queue</resource-env-ref-type>
     </resource-env-ref>
     <resource-ref>
     <res-ref-name>jms/TheQueFactory</res-ref-name>
     <res-type>javax.jms.QueueConnectionFactory</res-type>
     <res-auth>Container</res-auth>
     </resource-ref>
</web-app>

Step 10: Packaging the Client into a Jar File

Next, we need to package DurableSubscriber and MessageHandler as a client jar file.

  1. On the deployment tool, select File|New|Application Client, and click Next. Then click the Edit button that appears. Select the client icon and then add DurableSubscriber.classand MessageHandler.classas shown in Figure 13-20.

    Figure 13-20 Packaging the client application

  2. Click OK and then click Next. Use the pull-down menu to select Durable-Subscriber under the Main class heading. The display name should also show DurableSubscriber as shown in Figure 13-21.

    Figure 13-21 Specifying the client 's class and display name

  3. Click Next several times until the Resource Factory window appears. Click the Add button and enter jms/TheTopicFactory under Coded Name. Select the javax.jms.TopicConnectionFactoryunder Type; then select Sharable. For JNDI name, enter MyTopicFactory with j2ee as the user name and password, as shown in Figure 13-22.

    Figure 13-22 Specifying resource factory and the JNDI name

  4. Click Next, and then click the Add button. Enter jms/TheTopic under Coded Name and select javax.jmx.Topicfrom the Type pull-down menu. As the JNDI name, enter MyTopic and click Next, which displays the deployment descriptor. Then click Finish, and you're done with packaging the Roster application.

  5. Select the General tab on the right hand side of the GUI to see ejb-jar-ic.jar, app-client-ic.jar, and war-ic.waras well as sun-j2ee-ri.xml, application.xml, and MANIFEST.MFunder the META-INF directory in the Content section of the GUI. This is shown in Figure 13-23.

    Figure 13-23 Content of RosterApp.ear .le —DurableSubscriber, RosterWAR,and RosterJAR

    The client-jar deployment descriptor is shown next.

    <application-client>
        <display-name>DurableSubscriber</display-name>
        <resource-ref>
        <res-ref-name>jms/TheTopicFactory</res-ref-name>
        <res-type>javax.jms.TopicConnectionFactory</res-type>
        <res-auth>Container</res-auth>
        <res-sharing-scope>Shareable</res-sharing-scope>
        </resource-ref>
        <resource-env-ref>
        <resource-env-ref-name>jms/TheTopic</resource-env-ref-name>
        <resource-env-ref-type>javax.jms.Topic</resource-env-ref-type>
        </resource-env-ref>
    </application-client>

Step 11: Deploying the Application

To deploy the RosterApp.ear file, do the following:

  1. Select Tools|Deploy and the Deploy RosterApp window appears. Under Object to Deploy, RosterAppshould display. If not, use the pull-down menu to select it. Under Target Server, select the local host. Check Save Object before deploying. Then click Next. (See Figure 13-24.)

    Figure 13-24 Specifying the application and host for deployment

  2. Verify the JNDI naming setup and change if needed. (See Figure 13-25.)

    Figure 13-25 Verifying the JNDI name setting

  3. Click Next. Set the ContextRoot to /RosterContextRoot as shown in Figure 13-26.

    Figure 13-26 Specifying the Web context root for the application

  4. Click Next twice and then click Finish. The deployment tool starts the deployment process. See Figure 13-27.

    Figure 13-27 Successful deployment

Step 12: Testing the Application

Test the Roster application by opening a browser and entering the URL http://localhost:8000/RosterContextRoot. This brings up the Message.htm file as shown in Figure 13-28. Use it to submit a schedule and student user name identification. The RosterMDB accepts the message, writes the content of the user input to the window terminal, and then inserts the schedule and student identification along with a date into a roster database table.

Figure 13-28 depicts the Message.htm page with the user input ScheduleID set to EJB-300 and StudentID set to pvt@javacamp.com before the form is submitted.

Figure 13-28 HTML form to send message to the MDB

Figure 13-27 shows the output from a RosterMDB to the Windows terminal. Keep the ScheduleID set to EJB-300 and change the StudentID to a different e-mail address and submit the form several times (for example, submit another form with studentID set to tom@sun.com). According to the design, the RosterMDB should be publishing a list of students who have registered for EJB-300 as a persistent message. Now, we'll execute DurableSubscriber and see whether we can retrieve any of those messages.

Change the directory to APPHOME\chapter13 and run the client application as follows:

APPHOME\chapter13\runclient –client RosterApp.ear –name DurableSub-scriber GetMessage –textauth 

and then click Enter. You'll be asked to enter user name and password—enter j2ee for both, and the subscriber client retrieves the messages and displays them on the terminal as shown in Figure 13-29. Notice that the list in the message gets longer as new users are being added to the roster.

Figure 13-29 JMS client DurableSubscriber receiving messages

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020