10.12.2012 Views

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Writing Simple JMS Client Applications<br />

916<br />

Writing the Client Programs for the Asynchronous Receive Example<br />

<strong>The</strong> sending program is producer/src/java/Producer.java, the same program used in the<br />

example in “A Simple Example of Synchronous Message Receives” on page 907.<br />

An asynchronous consumer normally runs indefinitely. This one runs until the user types the<br />

letter q or Q to stop the program.<br />

<strong>The</strong> receiving program, asynchconsumer/src/java/AsynchConsumer.java, performs the<br />

following steps:<br />

1. Injects resources for a connection factory, queue, and topic.<br />

2. Assigns either the queue or topic to a destination object, based on the specified destination<br />

type.<br />

3. Creates a Connection and a Session.<br />

4. Creates a MessageConsumer.<br />

5. Creates an instance of the TextListener class and registers it as the message listener for the<br />

MessageConsumer:<br />

listener = new TextListener();consumer.setMessageListener(listener);<br />

6. Starts the connection, causing message delivery to begin.<br />

7. Listens for the messages published to the destination, stopping when the user types the<br />

character q or Q:<br />

System.out.println("To end program, type Q or q, " + "then ");<br />

inputStreamReader = new InputStreamReader(System.in);<br />

while (!((answer == ’q’) || (answer == ’Q’))) {<br />

try {<br />

answer = (char) inputStreamReader.read();<br />

} catch (IOException e) {<br />

System.out.println("I/O exception: " + e.toString());<br />

}<br />

}<br />

8. Closes the connection, which automatically closes the session and MessageConsumer.<br />

<strong>The</strong> message listener, asynchconsumer/src/java/TextListener.java, follows these steps:<br />

1. When a message arrives, the onMessage method is called automatically.<br />

2. <strong>The</strong> onMessage method converts the incoming message to a TextMessage and displays its<br />

content. If the message is not a text message, it reports this fact:<br />

public void onMessage(Message message) {<br />

TextMessage msg = null;<br />

try {<br />

if (message instanceof TextMessage) {<br />

msg = (TextMessage) message;<br />

System.out.println("Reading message: " + msg.getText());<br />

<strong>The</strong> <strong>Java</strong> <strong>EE</strong> 5<strong>Tutorial</strong> • June 2010

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!