Sun Java logo     Previous      Contents      Index      Next     

Sun logo
Sun Java System Message Queue 3 2005Q1 Developer's Guide for Java Clients 

Chapter 1
Overview

This chapter provides an overall introduction to Sun Java™ System Message Queue and a quick-start tutorial. You should be familiar with the concepts presented in the Message Queue Technical Overview before you read this chapter.

The chapter covers the following topics:


Message Queue for the Java Developer

This section lists the component files needed for Message Queue client development and provides a summary of the basic steps needed to create applications that produce and consume messages.

Message Queue Java Client Files

The Message Queue files that need to be used in conjunction with the Message Queue Java clients can be found in the lib directory in the installed location for Message Queue on your platform.

Message Queue Java clients need to be able to use several .jar files found in the lib directory when these clients are compiled and run.

JMS Client Setup Operations

The general procedures for producing and consuming messages are introduced below. These procedures have a number of common steps which need not be duplicated if a client is both producing and consuming messages.

For a more detailed presentation of creating, compiling, and running a simple client application, see Quick-Start Tutorial.

    To Set Up a Client to Produce Messages
  1. Look up or instantiate a ConnectionFactory object.
  2. Use the ConnectionFactory object to create a Connection object.
  3. Use the Connection object to create one or more Session objects.
  4. Look up or instantiate one or more Destination objects.
  5. Use a Session object and a Destination object to create any needed MessageProducer objects.
  6. (You can create a MessageProducer object without specifying a Destination object, but then you have to specify a Destination object for each message that you produce.)

    At this point the client has the basic setup needed to produce messages.

  7. Use a Session object to create a message.
  8. Use the Message object to set its contents. Use the Message object or the MessageProducer object to set the message properties.
  9. Use the MessageProducer object to send the message.
    To Set Up a Client to Consume Messages
  1. Look up or instantiate a ConnectionFactory object.
  2. Use the ConnectionFactory object to create a Connection object.
  3. Use the Connection object to create one or more Session objects.
  4. Look up or instantiate one or more Destination objects.
  5. Use a Session object and a Destination object to create any needed MessageConsumer objects.
  6. If you want to receive messages asynchronously, instantiate a MessageListener object and register it with a MessageConsumer object.
  7. Tell the Connection object to start delivery of messages. This allows messages to be delivered to the client for consumption.
  8. If you are using a synchronous receiver, you can now make the call to retrieve messages.

At this point the client has the basic setup needed to consume messages. Note that the consumer can use synchronous or asynchronous consumption, but not both.


Quick-Start Tutorial

This section provides a quick introduction to JMS client programming in a Sun Java System Message Queue environment. It describes the procedures used to create, compile, and run a simple HelloWorldMessage example application.

It covers the following topics:

For the purpose of this tutorial it is sufficient to run the Message Queue server in a default configuration. For instructions on configuring a Message Queue server, please refer to the Message Queue Administration Guide.

The minimum JDK level required to compile and run Message Queue clients is 1.2.

Setting Up Your Environment

You need to set the CLASSPATH environment variable when compiling and running a JMS client. (The IMQ_HOME variable, where used, refers to the directory where Message Queue is installed on Windows platforms and some Sun Java System Application Server platforms.)

The value of CLASSPATH depends on the following factors:

Table 1-1 specifies the directories where jar files are to be found on the different platforms:

Table 1-1  jar File Locations 

Platform

Directory

Solaris™

/usr/share/lib/

Solaris, using the standalone version of Sun Java System Application Server

IMQ_HOME/lib/

Linux

/opt/mq/lib/

Windows

IMQ_HOME\lib\

Table 1-2 lists the jar files you need to compile and run different kinds of code.

Table 1-2  jar Files Needed in CLASSPATH 

Code

To Compile

To Run

Discussion

JMS client

jms.jar
imq.jar
jndi.jar

jms.jar
imq.jar
Directory containing compiled Java app or '.'

See discussion of JNDI jar files, following this table.

SOAP Client

saaj-api.jar
activation.jar

saaj-api.jar
Directory containing compiled Java app or '.'

See Chapter 5, "Working with SOAP Messages"

SOAP Servlet

jaxm-api.jar
saaj-api.jar
activation.jar

 

Sun Java System App Server already includes these jar files for SOAP servlet support.

code using SOAP/JMS transformer utilities

imqxm.jar
(and jars for JMS and SOAP clients)

imqxm.jar

Also add the appropriate jar files mentioned in this table for the kind of code you are writing.

A client application must be able to access JNDI jar files (jndi.jar) even if the application does not use JNDI directly to look up Message Queue administered objects. This is because JNDI is referenced by Destination and ConnectionFactory classes.

JNDI jar files are bundled with JDK 1.4. Thus, if you are using this JDK, you do not have to add jndi.jar to your CLASSPATH setting. However, if you are using an earlier version of the JDK, you must include jndi.jar in your classpath.

If you are using JNDI to look up Message Queue administered objects, you must also include the following files in your CLASSPATH setting:

Starting and Testing the Message Server

This tutorial assumes that you do not have a Message Queue server currently running. A message server consists of one or more brokers—the software component that routes and delivers messages.

(If you run the broker as a UNIX startup process or Windows service, then it is already running and you can skip to To Test a Broker below.)

    To Start a Broker
  1. In a terminal window, change to the directory containing Message Queue executables:
  2. Table 1-3  Location of Message Queue Executables 

    Platform

    Location

    Solaris

    /usr/bin/

    Linux

    /opt/sun/mq/bin/

    Windows

    IMQ_HOME/bin/

  3. Run the broker startup command (imqbrokerd) as shown below.
  4. imqbrokerd -tty

    The -tty option causes all logged messages to be displayed to the terminal console (in addition to the log file).

    The broker will start and display a few messages before displaying the message, “imqbroker@host:7676 ready.” It is now ready and available for clients to use.

    To Test a Broker

One simple way to check the broker startup is by using the Message Queue Command (imqcmd) utility to display information about the broker.

  1. In a separate terminal window, change to the directory containing Message Queue executables (see Table 1-3).
  2. Run imqcmd with the arguments shown below. (Supply the default password of admin whenprompted to do so.)
  3. imqcmd query bkr -u admin

    The output displayed should be similar to what is shown below.

    % imqcmd query bkr -u admin

    Querying the broker specified by:

    -------------------------

    Host         Primary Port

    -------------------------

    localhost    7676

    Version                                            3.6

    Instance Name                                      imqbroker

    Primary Port                                       7676

    Current Number of Messages in System               0

    Current Total Message Bytes in System              0

    Max Number of Messages in System                   unlimited (-1)

    Max Total Message Bytes in System                  unlimited (-1)

    Max Message Size                                   70m

    Auto Create Queues                                 true

    Auto Create Topics                                 true

    Auto Created Queue Max Number of Active Consumers  1

    Auto Created Queue Max Number of Backup Consumers  0

    Cluster Broker List (active)                        

    Cluster Broker List (configured)                   

    Cluster Master Broker                               

    Cluster URL                                         

    Log Level                                          INFO

    Log Rollover Interval (seconds)                    604800

    Log Rollover Size (bytes)                          unlimited (-1)

    Successfully queried the broker.

    Current Number of Messages in System        0

Developing a Simple Client Application

This section leads you through the steps used to create a simple “Hello World” client application that sends a message to a queue destination and then retrieves the same message from the queue. You can find this example, named HelloWorldMessage in the IMQ_HOME/demo/helloworld/helloworldmessage directory.

The following steps describe the HelloWorldMessage example

  1. Import the interfaces and Message Queue implementation classes for the JMS API. (The javax.jms package defines all the JMS interfaces necessary to develop a JMS client.)
  2. import javax.jms.QueueConnectionFactory;
    import javax.jms.QueueConnection;
    import javax.jms.QueueSession
    import javax.jms.QueueSender;
    import javax.jms.QueueReceiver;
    import javax.jms.Queue;
    import javax.jms.Session;
    import javax.jms.Message;
    import javax.jms.TextMessage;

    Note: To prevent compilation errors, especially when using JDK 1.5 and above, do not use the wildcard character to specify the files to be imported. For example,

    import javax.jms.*;  \\ DO NOT USE

    import java.util.*; \\ DO NOT USE

  3. Instantiate a Message Queue QueueConnectionFactory administered object.
  4. A QueueConnectionFactory object encapsulates all the Message Queue-specific configuration properties for creating QueueConnection connections to a Message Queue server.

    QueueConnectionFactory myQConnFactory =
      new com.sun.messaging.QueueConnectionFactory();

    ConnectionFactory administered objects can also be accessed through a JNDI lookup (see Looking Up ConnectionFactory Objects). This approach makes the client code JMS-provider independent and also allows for a centrally administered messaging system.

  5. Create a connection to the message server.
  6. A QueueConnection object is the active connection to the message server in the Point-To-Point programming domain.

    QueueConnection myQConn =
      myQConnFactory.createQueueConnection();

  7. Create a session within the connection.
  8. A QueueSession object is a single-threaded context for producing and consuming messages. It enables clients to create producers and consumers of messages for a queue destination.

    QueueSession myQSess = myQConn.createQueueSession(false,
      Session.AUTO_ACKNOWLEDGE);

    The myQSess object created above is non-transacted and automatically acknowledges messages upon consumption by a consumer.

  9. Instantiate a Message Queue queue administered object that corresponds to a queue destination in the message server.
  10. Destination administered objects encapsulate provider-specific destination naming syntax and behavior. The code below instantiates a queue administered object for a physical queue destination named “world”.

    Queue myQueue = new com.sun.messaging.Queue("world");

    Destination administered objects can also be accessed through a JNDI lookup (see Looking Up Destination Objects). This approach makes the client code JMS-provider independent and also allows for a centrally administered messaging system.

  11. Create a QueueSender message producer.
  12. This message producer, associated with myQueue, is used to send messages to the queue destination named “world”.

    QueueSender myQueueSender = myQSess.createSender(myQueue);

  13. Create and send a message to the queue.
  14. You create a TextMessage object using the QueueSession object and populate it with a string representing the data of the message. Then you use the QueueSender object to send the message to the “world” queue destination.

    TextMessage myTextMsg = myQSess.createTextMessage();
    myTextMsg.setText("Hello World");
    System.out.println(“Sending Message: “ + myTextMsg.getText());
    myQueueSender.send(myTextMsg);

  15. Create a QueueReceiver message consumer.
  16. This message consumer, associated with myQueue, is used to receive messages from the queue destination named “world”.

    QueueReceiver myQueueReceiver =
      myQSess.createReceiver(myQueue);

  17. Start the QueueConnection you created in Step 3.
  18. Messages for consumption by a client can only be delivered over a connection that has been started (while messages produced by a client can be delivered to a destination without starting a connection, as in Step 7.

    myQConn.start();

  19. Receive a message from the queue.
  20. You receive a message from the “world” queue destination using the QueueReceiver object. The code, below, is an example of a synchronous consumption of messages.

    Message msg = myQueueReceiver.receive();

  21. Retrieve the contents of the message.
  22. Once the message is received successfully, its contents can be retrieved.

    if (msg instanceof TextMessage) {
      TextMessage txtMsg = (TextMessage) msg;
      System.out.println("Read Message: " + txtMsg.getText());
    }

  23. Close the session and connection resources.
  24. myQSess.close();
    myQConn.close();

Compiling and Running a Client Application

To compile and run Java clients in a Message Queue environment, it is recommended that you use the Java2 SDK Standard Edition v1.4 or later, though version 1.2 is also supported. The recommended SDK can be downloaded from the following location:

Be sure that you have set the CLASSPATH environment variable correctly, as described in Setting Up Your Environment, before attempting to compile or run a client application.

Note: Users of JDK 1.5 may get compiler errors if they use the unqualified JMS Queue class along with the following import statement

import java.util.*

This is because both the java.util package and the javax.jms package contain a Queue class. To avoid the compilation error in this situation, you need either to fully qualify references to the JMS Queue class as javax.jms.Queue or to correct your import statements to refer to explicit classes in order to eliminate the ambiguity for the compiler.

The following instructions are based on the HelloWorldMessage application, as created in Developing a Simple Client Application, and located in the Message Queue 3.6 JMS example applications directory (see Table 1-4). Please note that these instructions are furnished as an example. You do not actually need to compile the example; it is shipped precompiled. Of course, if you modify the source for the example, you will need to recompile.

    To Compile and Run the HelloWorldMessage Application
  1. Make the directory containing the application your current directory.
  2. The Message Queue 3.6 example applications directory on Solaris is not writable by users, so copy the HelloWorldMessage application to a writable directory and make that directory your current directory.

  3. Compile the HelloWorldMessage application as shown below.
  4. javac HelloWorldMessage.java

    This step results in the HelloWorldMessage.class file being created in the current directory.

  5. Run the HelloWorldMessage application:
  6. java HelloWorldMessage

    The following output is displayed when you run HelloWorldMessage.

      Sending Message: Hello World

      Read Message: Hello World

Example Application Code

The example applications provided by Message Queue 3.6 consist of both JMS messaging applications as well as JAXM messaging examples (see Working with SOAP Messages for more information).

Directories containing example application code are set as follows:

Each directory (except for the JMS directory) contains a README file that describes the source files included in that directory. Table 1-4 lists and describes the contents of the directories of interest to Message Queue Java clients.

Table 1-4  Example Programs 

Directory

Contents

helloworld

Simple programs that show how a JMS client is created and deployed in Message Queue. These examples include the steps required to create administered objects in Message Queue, and show to use JNDI in the client to look up and use those objects.

jms

Sample programs that demonstrate the use of the JMS API with Message Queue.

jaxm

Sample programs that demonstrate how to use SOAP messages in conjunction with JMS in Message Queue.

applications

Four directories:

  • One contains source for a GUI application that uses the Message Queue JMS monitoring API to get the list of queues from a Message Queue broker and browse their contents using a JMS queue browser.
  • One contains source for a GUI application that uses the JMS API to implement a simple chat application.
  • One contains the MQ Ping demo program.
  • One contains the MQ Applet program.

monitoring

Sample programs that demonstrate how to use the JMS API for monitoring the broker.

jdbc

Examples for plugging in a PointBase and an Oracle database.

imqobjmgr

Examples of imqobjmgr command files.


Client Application Deployment Considerations

When you are ready to deploy your client application, you should make sure the administrator knows your application’s needs. The checklist in Table 1-5 shows the basic information required. Consult with your administrator to determine the exact information needed. In some cases, it might be useful to provide a range of values rather than a specific value. For details on configuration and on attribute names and default values for administered objects, refer to the Message Queue Administration Guide.

Table 1-5  Checklist for the Message Queue Administrator  

Configuring administered objects:

 

Connection factories to be created
          Type:
          JNDI lookup name:
          Other attributes:

 

Destination objects to be created
          Type (queue or topic):
          JNDI lookup name:
          Physical destination name (if your administrator wants it):

Configuring a broker or broker cluster:

 

          Name:
          Port
          Properties

Configuring physical destinations:

 

          Type:
          Name:
          Attributes:
          Maximum number of messages expected:
          Maximum size of messages expected:
          Maximum message bytes expected:

Configuring Dead Message Queue

 

          Place dead messages on Dead Message Queue
          Log the placement of messages on the Dead Message Queue
          Discard the body of messages placed on the Dead Message Queue



Previous      Contents      Index      Next     


Part No: 819-0068-10.   Copyright 2005 Sun Microsystems, Inc. All rights reserved.