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:
Define and implement a message objectRosterVO.
Implement the MDB classRosterMDB.
Implement the helper classRosterDAOand RosterDAOException.
Compile the RosterMDB, RosterVO, and RosterDAO.
Implement a servlet JMS message sender clientMessageSender.
Implement JMS message subscriber clientDurableSubscriberand MessageHandler.
Compile JMS clientsMessageSender, DurableSubscriber, and MessageHandler.
Package the EJB component into the RosterJARfile.
Package the Web component into the RosterWARfile.
Package the client into the clientjarfile.
Package the ejb-jar, client-jar, and warfiles into the RosterApp.earfile.
Deploy the RosterApp.earfile.
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 dateas 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 clientits 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 applicationall cooperating JMS clientsused 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 sectionsthe 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.
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.
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
Using the deployment tool, click File|New|Enterprise Bean to open the New Enterprise Bean Wizard. Click Next.
Click Create New EJB File in Application (this is the default). Under EJB Display Name, enter RosterJAR.
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.
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.
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
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
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
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.
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
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.
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
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.
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.
Using the deployment GUI, click File|New|Web Component to open a New Web Component Wizard. Click Next.
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.
Click Next. The Web component type is servlet. Select Servlet, and then click Next again.
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
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.
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
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
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
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
Figure 13-14 Packaging the MessageSender.Client into the war .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.
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
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
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
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.
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:
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
Verify the JNDI naming setup and change if needed. (See Figure 13-25.)
Figure 13-25 Verifying the JNDI name setting
Click Next. Set the ContextRoot to /RosterContextRoot as shown in Figure 13-26.
Figure 13-26 Specifying the Web context root for the application
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 passwordenter 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