Movatterモバイル変換


[0]ホーム

URL:


Document Information

Preface

Part I Introduction

1.  Overview

2.  Using the Tutorial Examples

Part II The Web Tier

3.  Getting Started with Web Applications

4.  Java Servlet Technology

5.  JavaServer Pages Technology

6.  JavaServer Pages Documents

7.  JavaServer Pages Standard Tag Library

8.  Custom Tags in JSP Pages

9.  Scripting in JSP Pages

10.  JavaServer Faces Technology

11.  Using JavaServer Faces Technology in JSP Pages

12.  Developing with JavaServer Faces Technology

13.  Creating Custom UI Components

14.  Configuring JavaServer Faces Applications

15.  Internationalizing and Localizing Web Applications

Part III Web Services

16.  Building Web Services with JAX-WS

17.  Binding between XML Schema and Java Classes

18.  Streaming API for XML

19.  SOAP with Attachments API for Java

Part IV Enterprise Beans

20.  Enterprise Beans

21.  Getting Started with Enterprise Beans

22.  Session Bean Examples

23.  A Message-Driven Bean Example

Part V Persistence

24.  Introduction to the Java Persistence API

25.  Persistence in the Web Tier

26.  Persistence in the EJB Tier

27.  The Java Persistence Query Language

Part VI Services

28.  Introduction to Security in the Java EE Platform

29.  Securing Java EE Applications

30.  Securing Web Applications

31.  The Java Message Service API

32.  Java EE Examples Using the JMS API

A Java EE Application That Uses the JMS API with a Session Bean

Writing the Application Components for theclientsessionmdb Example

Coding the Application Client:MyAppClient.java

Coding the Publisher Session Bean

Coding the Message-Driven Bean:MessageBean.java

Creating Resources for theclientsessionmdb Example

Building, Deploying, and Running theclientsessionmdb Example Using NetBeans IDE

Building, Deploying, and Running theclientsessionmdb Example Using Ant

A Java EE Application That Uses the JMS API with an Entity

Overview of theclientmdbentity Example Application

Writing the Application Components for theclientmdbentity Example

Coding the Application Client:HumanResourceClient.java

Coding the Message-Driven Beans for theclientmdbentity Example

Coding the Entity Class for theclientmdbentity Example

Creating Resources for theclientmdbentity Example

Building, Deploying, and Running theclientmdbentity Example Using NetBeans IDE

Building, Deploying, and Running theclientmdbentity Example Using Ant

An Application Example That Consumes Messages from a Remote Server

Overview of theconsumeremote Example Modules

Writing the Module Components for theconsumeremote Example

Creating Resources for theconsumeremote Example

Using Two Application Servers for theconsumeremote Example

Building, Deploying, and Running theconsumeremoteModules Using NetBeans IDE

Building, Deploying, and Running theconsumeremote Modules Using Ant

An Application Example That Deploys a Message-Driven Bean on Two Servers

Overview of thesendremote Example Modules

Writing the Module Components for thesendremote Example

Coding the Application Client:MultiAppServerClient.java

Coding the Message-Driven Bean:ReplyMsgBean.java

Creating Resources for thesendremote Example

Using Two Application Servers for thesendremote Example

Building, Deploying, and Running thesendremote Modules Using NetBeans IDE

Building, Deploying, and Running thesendremote Modules Using Ant

33.  Transactions

34.  Resource Connections

35.  Connector Architecture

Part VII Case Studies

36.  The Coffee Break Application

37.  The Duke's Bank Application

Part VIII Appendixes

A.  Java Encoding Schemes

B.  About the Authors

Index

 

The Java EE 5 Tutorial

Java Coffee Cup logo
PreviousContentsNext

A Java EE Application That Uses the JMS API with an Entity

This section explains how to write, compile, package, deploy, and run a JavaEE application that uses the JMS API with an entity. The application usesthe following components:

  • An application client that both sends and receives messages

  • Two message-driven beans

  • An entity class

This section covers the following topics:

You will find the source files for this section in the directorytut-install/javaeetutorial5/examples/jms/clientmdbentity/. Path names in this section are relative to this directory.

Overview of theclientmdbentity Example Application

This application simulates, in a simplified way, the work flow of a company’shuman resources (HR) department when it processes a new hire. This application alsodemonstrates how to use the Java EE platform to accomplish a task thatmany JMS client applications perform.

A JMS client must often wait for several messages from various sources. Itthen uses the information in all these messages to assemble a messagethat it then sends to another destination. The common term for this processisjoining messages. Such a task must be transactional, with all the receives andthe send as a single transaction. If not all the messages are receivedsuccessfully, the transaction can be rolled back. For a client example that illustratesthis task, seeA Local Transaction Example.

A message-driven bean can process only one message at a time ina transaction. To provide the ability to join messages, a Java EE applicationcan have the message-driven bean store the interim information in an entity. Theentity can then determine whether all the information has been received; when it has,the entity can report this back to one of the message-driven beans,which then creates and sends the message to the other destination. After ithas completed its task, the entity can be removed.

The basic steps of the application are as follows.

  1. The HR department’s application client generates an employee ID for each new hire and then publishes a message (M1) containing the new hire’s name, employee ID, and position. The client then creates a temporary queue,ReplyQueue, with a message listener that waits for a reply to the message. (SeeCreating Temporary Destinations, for more information.)

  2. Two message-driven beans process each message: One bean,OfficeMDB, assigns the new hire’s office number, and the other bean,EquipmentMDB, assigns the new hire’s equipment. The first bean to process the message creates and persists an entity namedSetupOffice, then calls a business method of the entity to store the information it has generated. The second bean locates the existing entity and calls another business method to add its information.

  3. When both the office and the equipment have been assigned, the entity business method returns a value oftrue to the message-driven bean that called the method. The message-driven bean then sends to the reply queue a message (M2) describing the assignments. Then it removes the entity. The application client’s message listener retrieves the information.

Figure 32-2 illustrates the structure of this application. Of course, an actual HR applicationwould have more components; other beans could set up payroll and benefits records, scheduleorientation, and so on.

Figure 32-2 assumes thatOfficeMDB is the first message-driven bean to consume themessage from the client.OfficeMDB then creates and persists theSetupOffice entity andstores the office information.EquipmentMDB then finds the entity, stores the equipmentinformation, and learns that the entity has completed its work.EquipmentMDB then sends themessage to the reply queue and removes the entity.

Figure 32-2 A Java EE Application: Client to Message-Driven Beans to Entity

Diagram of application showing an application client, two message-driven beans, and an entity

Writing the Application Components for theclientmdbentity Example

Writing the components of the application involves the following:

Coding the Application Client:HumanResourceClient.java

The application client program,clientmdbentity-app-client/src/java/HumanResourceClient.java, performs the following steps:

  1. InjectsConnectionFactory andTopic resources

  2. Creates aTemporaryQueue to receive notification of processing that occurs, based on new-hire events it has published

  3. Creates aMessageConsumer for theTemporaryQueue, sets theMessageConsumer’s message listener, and starts the connection

  4. Creates aMessageProducer and aMapMessage

  5. Creates five new employees with randomly generated names, positions, and ID numbers (in sequence) and publishes five messages containing this information

The message listener,HRListener, waits for messages that contain the assigned office andequipment for each employee. When a message arrives, the message listener displays theinformation received and determines whether all five messages have arrived. When they have,the message listener notifies the main program, which then exits.

Coding the Message-Driven Beans for theclientmdbentity Example

This example uses two message-driven beans:

  • clientmdbentity-ejb/src/java/EquipmentMDB.java

  • clientmdbentity-ejb/src/java/OfficeMDB.java

The beans take the following steps:

  1. They injectMessageDrivenContext andConnectionFactory resources.

  2. TheonMessage method retrieves the information in the message. TheEquipmentMDB’sonMessage method chooses equipment, based on the new hire’s position; theOfficeMDB’sonMessage method randomly generates an office number.

  3. After a slight delay to simulate real world processing hitches, theonMessage method calls a helper method,compose.

  4. Thecompose method takes the following steps:

    1. It either creates and persists theSetupOffice entity or finds it by primary key.

    2. It uses the entity to store the equipment or the office information in the database, calling either thedoEquipmentList or thedoOfficeNumber business method.

    3. If the business method returnstrue, meaning that all of the information has been stored, it creates a connection and a session, retrieves the reply destination information from the message, creates aMessageProducer, and sends a reply message that contains the information stored in the entity.

    4. It removes the entity.

Coding the Entity Class for theclientmdbentity Example

TheSetupOffice class,SetupOffice.java, is an entity class. The entity and the message-drivenbeans are packaged together in an EJB JAR file. The entity class isdeclared as follows:

@Entitypublic class SetupOffice implements Serializable {

The class contains a no-argument constructor and a constructor that takes two arguments,the employee ID and name. It also contains getter and setter methods forthe employee ID, name, office number, and equipment list. The getter method forthe employee ID has the@Id annotation to indicate that this field isthe primary key:

@Id public String getEmployeeId() {    return id;}

The class also implements the two business methods,doEquipmentList anddoOfficeNumber, andtheir helper method,checkIfSetupComplete.

The message-driven beans call the business methods and the getter methods.

Thepersistence.xml file for the entity specifies the most basic settings:

<persistence>    <persistence-unit name="clientmdbentity">        <jta-data-source>jdbc/__default</jta-data-source>        <class>eb.SetupOffice</class>        <properties>            <property name="toplink.ddl-generation"                 value="drop-and-create-tables"/>        </properties>    </persistence-unit></persistence>

Creating Resources for theclientmdbentity Example

This example uses the connection factoryjms/ConnectionFactory and the topicjms/Topic, both ofwhich you used inA Java EE Application That Uses the JMS API with a Session Bean. It also uses the JDBC resource namedjdbc/__default, which is enabled by default when you start the Application Server.

If you deleted the connection factory or topic, you can create them againusing targets in thebuild.xml file for this example. Use the following commandsto create the resources:

ant create-cf ant create-topic

Building, Deploying, and Running theclientmdbentity Example Using NetBeans IDE

To build, deploy, and run the application using NetBeans IDE, do the following:

  1. Start the Application Server, if it is not already running.

  2. Start the database server as described inStarting and Stopping the Java DB Database Server, if it is not already running.

  3. In NetBeans IDE, choose Open Project from the File menu.

  4. In the Open Project dialog, navigate totut-install/javaeetutorial5/examples/jms/.

  5. Select theclientmdbentity folder.

  6. Select the Open as Main Project check box and the Open Required Projects check box.

  7. Click Open Project.

  8. Right-click theclientmdbentity project and choose Build.

    This task creates the following:

    • An application client JAR file that contains the client class and listener class files, along with a manifest file that specifies the main class

    • An EJB JAR file that contains the message-driven beans and the entity class, along with thepersistence.xml file

    • An application EAR file that contains the two JAR files along with anapplication.xml file

  9. Right-click the project and choose Undeploy and Deploy.

  10. Right-click the project and choose Run.

    This command returns a JAR file namedclientmdbentityClient.jar and then executes it.

The output of the application client in the Output pane looks something likethis:

PUBLISHER: Setting hire ID to 25, name Gertrude Bourbon, position Senior ProgrammerPUBLISHER: Setting hire ID to 26, name Jack Verdon, position ManagerPUBLISHER: Setting hire ID to 27, name Fred Tudor, position ManagerPUBLISHER: Setting hire ID to 28, name Fred Martin, position ProgrammerPUBLISHER: Setting hire ID to 29, name Mary Stuart, position ManagerWaiting for 5 message(s)New hire event processed:  Employee ID: 25  Name: Gertrude Bourbon  Equipment: Laptop  Office number: 183Waiting for 4 message(s)New hire event processed:  Employee ID: 26  Name: Jack Verdon  Equipment: Pager  Office number: 20Waiting for 3 message(s)New hire event processed:  Employee ID: 27  Name: Fred Tudor  Equipment: Pager  Office number: 51Waiting for 2 message(s)New hire event processed:  Employee ID: 28  Name: Fred Martin  Equipment: Desktop System  Office number: 141Waiting for 1 message(s)New hire event processed:  Employee ID: 29  Name: Mary Stuart  Equipment: Pager  Office number: 238

The output from the message-driven beans and the entity class appears in theserver log, wrapped in logging information.

For each employee, the application first creates the entity and then finds it.You may see runtime errors in the server log, and transaction rollbacks mayoccur. The errors occur if both of the message-driven beans discover at thesame time that the entity does not yet exist, so they bothtry to create it. The first attempt succeeds, but the second fails becausethe bean already exists. After the rollback, the second message-driven bean tries againand succeeds in finding the entity. Container-managed transactions allow the application to run correctly,in spite of these errors, with no special programming.

You can run the application client repeatedly.

Undeploy the application after you finish running the client. To undeploy the application,follow these steps:

  1. Click the Services tab.

  2. Expand the Servers node.

  3. Expand the Application Server node.

  4. Expand the Applications node.

  5. Expand the Enterprise Applications node.

  6. Right-clickclientmdbentity and choose Undeploy.

To remove the generated files, right-click theclientmdbentity project and choose Clean.

Building, Deploying, and Running theclientmdbentity Example Using Ant

To create and package the application using Ant, perform these steps:

  1. Start the Application Server, if it is not already running.

  2. Start the database server as described inStarting and Stopping the Java DB Database Server.

  3. Go to the following directory:

    tut-install/javaeetutorial5/examples/jms/clientmdbentity/
  4. To compile the source files and package the application, use the following command:

    ant

Theant command creates the following:

  • An application client JAR file that contains the client class and listener class files, along with a manifest file that specifies the main class

  • An EJB JAR file that contains the message-driven beans and the entity class, along with thepersistence.xml file

  • An application EAR file that contains the two JAR files along with anapplication.xml file

To deploy the application and run the client, use the following command:

ant run

Ignore the message that states that the application is deployed at a URL.

The program output in the terminal window looks something like this:

running application client container.PUBLISHER: Setting hire ID to 25, name Gertrude Bourbon, position Senior ProgrammerPUBLISHER: Setting hire ID to 26, name Jack Verdon, position ManagerPUBLISHER: Setting hire ID to 27, name Fred Tudor, position ManagerPUBLISHER: Setting hire ID to 28, name Fred Martin, position ProgrammerPUBLISHER: Setting hire ID to 29, name Mary Stuart, position ManagerWaiting for 5 message(s)New hire event processed:  Employee ID: 25  Name: Gertrude Bourbon  Equipment: Laptop  Office number: 183Waiting for 4 message(s)New hire event processed:  Employee ID: 26  Name: Jack Verdon  Equipment: Pager  Office number: 20Waiting for 3 message(s)New hire event processed:  Employee ID: 27  Name: Fred Tudor  Equipment: Pager  Office number: 51Waiting for 2 message(s)New hire event processed:  Employee ID: 28  Name: Fred Martin  Equipment: Desktop System  Office number: 141Waiting for 1 message(s)New hire event processed:  Employee ID: 29  Name: Mary Stuart  Equipment: Pager  Office number: 238

The output from the message-driven beans and the entity class appears in theserver log, wrapped in logging information.

For each employee, the application first creates the entity and then finds it.You may see runtime errors in the server log, and transaction rollbacks mayoccur. The errors occur if both of the message-driven beans discover at thesame time that the entity does not yet exist, so they bothtry to create it. The first attempt succeeds, but the second fails becausethe bean already exists. After the rollback, the second message-driven bean tries againand succeeds in finding the entity. Container-managed transactions allow the application to run correctly,in spite of these errors, with no special programming.

Undeploy the application after you finish running the client:

ant undeploy

To remove the generated files, use the following command in theclientmdbentity,clientmdbentity-app-client, andclientmdbentity-ejb directories:

ant clean
PreviousContentsNext

Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices


[8]ページ先頭

©2009-2025 Movatter.jp