Previous Contents Index Next |
Sun Java System Application Server Standard and Enterprise Edition 7 2004Q2 Developer's Guide to J2EE Services and APIs

> ## Chapter 5
> Using the Java Message Service

> This chapter describes how to use the Java™ Message Service (JMS) API. The Sun Java™ System Application Server has a fully integrated JMS provider: the Sun Java™ System Message Queue software.

> This chapter contains the following sections:

> - Introducing the JMS API
> - Administration of the JMS Service
> - Creating Applications That Use the JMS API
> - Delivering SOAP Messages Using the JMS API
> - Sample Applications

> ##

> Introducing the JMS API

> The Sun Java System Application Server provides support for applications that use the JMS API. The JMS API is a set of programming interfaces that provide a common way for Java applications to create, send, receive, and read messages in a distributed environment.

> In particular, the JMS API is the standards-based way that J2EE™ applications perform asynchronous messaging. Accordingly, J2EE components (web or EJB™ components) can use the JMS API to send messages that can be consumed asynchronously by a specialized EJB, called a message-driven bean.

> For more detailed information about JMS concepts and JMS support in Sun Java System Application Server, see the Sun Java System Application Server Administrator’s Guide.

> The rest of this section includes these topics:

> - JMS Provider
> - JMS Clients
> - JMS Messaging Models and Interfaces

> ### JMS Provider

> Sun Java System Application Server support for JMS messaging, in general, and for message-driven beans, in particular, requires messaging middleware that implements the JMS specification: a JMS provider. Sun Java System Application Server uses the Sun Java System Message Queue software as its native JMS provider. The Sun Java System Message Queue software is tightly integrated into Sun Java System Application Server, providing transparent JMS messaging support. This support (known within Sun Java System Application Server as the JMS Service) requires only minimal administration.

> For more information about the Sun Java System Message Queue, refer to the following documentation:

> http://docs.sun.com/db/prod/s1.s1msgqu#hic

> For general information about the JMS API, see the JMS web page at:

> http://java.sun.com/products/jms/index.html

> Note | The Sun Java System Message Queue software supports the JMS 1.1 API. However, Sun Java System Application Server supports the JMS 1.0.2 API in its application components (application client container included) When the JMS API is used inside web components and EJB components, certain restrictions are placed on its use, which are outlined in the J2EE specification.

> ### JMS Clients

> JMS clients (components or applications) exchange messages by way of the JMS provider. Message producers send messages to the JMS provider, from which message consumers receive them.

> A JMS client can be any type of J2EE application component: a web application, an EJB component, an Application Client Container client, and so on. To set up a JMS client, see Creating Applications That Use the JMS API.

> A specialized JMS client called a message-driven bean is one of a family of EJB components. Unlike other EJB components (session beans and entity beans) message-driven beans are invoked asynchronously. For more information about message-driven beans, see the EJB 2.0 Specification (http://java.sun.com/products/ejb/docs.html) and the Sun Java System Application Server Developer’s Guide to Enterprise JavaBeans Technology.

> ### JMS Messaging Models and Interfaces

> The JMS API supports two messaging models:

> - Point-to-point: allows two applications to communicate by sending and receiving messages through a Destination called a Queue.
> - Publish-subscribe: allows several messaging applications to communicate through a Destination called a Topic. Messages are sent by publishing to a Topic. Messages are received by subscribers.

> Regardless of the messaging model, the link between applications and the JMS provider is the Connection object. Applications get their Connection objects from ConnectionFactory objects.

> To maximize the portability of an application between JMS providers, provider-specific messaging features are encapsulated in administered objects. A JMS administered object implements one of four JMS interfaces, two for each messaging model.

> The following table lists the JMS administered object interfaces.

> Table 5-1 JMS Interfaces

> JMS Parent | Point-to-Point | Publish-Subscribe
> --- | --- | ---
> ConnectionFactory | QueueConnectionFactory | TopicConnectionFactory
> Destination | Queue | Topic

> JMS providers supply:

> - Classes that implement the Queue, Topic, QueueConnectionFactory, and TopicConnectionFactory interfaces.
> - Tools to create and configure the administered object class instances according to the deployment requirements. Administrators use these tools to set provider-specific parameters. These tools can also store the administered objects in a Java Naming and Directory Interface™ (JNDI) repository.

> This programming model lets you write JMS programs that are provider- independent. Applications look up administered objects using the JNDI API.

> ##

> Administration of the JMS Service

> To configure the JMS Service and prepare JMS resources for use in applications deployed to the Sun Java System Application Server, you must perform these tasks:

> - Configuring the JMS Service
> - Checking Whether the JMS Provider Is Running
> - Creating Physical Destinations
> - Creating JMS Resources: Destinations and Connection Factories

> For information about other JMS administration tasks, see the Sun Java System Application Server Administrator’s Guide and the Sun Java System Message Queue documentation at:

> http://docs.sun.com/db/prod/s1.s1msgqu#hic

> ### Configuring the JMS Service

> You can edit or check the JMS Service configuration in the following ways:

> - Using the Administration Interface
> - Using the Command Line Interface

> Note | Configuration of the JMS Service should be done only when the Sun Java System Application Server instance is stopped.

> The “Using The Administration Interface” section describes each connection pool setting. The “Using The Command Line Interface” section merely lists syntax and default values.

> #### Using the Administration Interface

> To edit the JMS Service configuration using the Administration interface, perform the following tasks:

> 1. Open the JMS component under your server instance.
> 2. Click Service.
> 3. You can edit the following information. Defaults are displayed.
> - Log Level - Controls the type of messages logged by the JMS Service to the server log. You can select a specific level, or you can select the default level set in the Log Service. For details, see the description of the Log Service in the Sun Java System Application Server Administrator’s Guide.
> - Port - Specifies the port number used by the JMS provider. The default is 7676.
> - Admin Username - Specifies the administrator user name for the JMS provider. The default is admin.
> - Admin Password - Specifies the administrator password for the JMS provider. The default is admin.
> - Start Timeout (secs) - Specifies the amount of time the server instance waits at startup for the corresponding JMS instance to respond. If there is no response, startup is aborted. If set to 0, the server instance waits indefinitely. The default is 30 seconds.
> - Start Arguments - Specifies the string of arguments supplied for startup of the corresponding JMS instance. By default, there are no arguments.
> - Start Enabled - If checked (the default), the Sun Java System Application Server instance is responsible for starting up and shutting down the JMS provider. If unchecked, the Sun Java System Application Server instance does not start up nor shut down the JMS provider (either because the JMS provider is not used or because it is managed independently of the Sun Java System Application Server).
> 4. Click the Properties button to activate and specify values for any properties your application requires.
> 1. To add a property, type its name and value in the Name and Value fields.
> 2. To activate a property, check its box.
> 3. If you need to add more Name and Value fields, click the Add button.

> The following table lists the standard JMS Service properties.

> Table 5-2 JMS Service Properties

> Property | Default | Description
> --- | --- | ---
> instance-name | domain_instance | Specifies the full Sun Java System Message Queue broker instance name, which by default is a concatenation of the domain and server instance names. For example: domain1_server1.
> instance-name-suffix | none | Specifies a suffix to add to the full Sun Java System Message Queue broker instance name. The suffix is separated from the instance name by an underscore character (_). For example, if the instance name is domain1_server1, appending the suffix xyz changes the instance name to domain1_server1_xyz.
> append-version | false | If true, appends the major and minor version numbers, preceded by underscore characters (_), to the full Sun Java System Message Queue broker instance name. For example, if the instance name is domain1_server1, appending the version numbers changes the instance name to domain1_server1_7_0.

> 5. Click the OK button to return to the main JMS Service page.
> 6. Click the Save button.

> #### Using the Command Line Interface

> To configure the JMS service using the command line interface, use the asadmin set command. The syntax is as follows, with defaults shown for optional parameters that have them:

> asadmin set --user admin_user [--password admin_password] [--passwordfile password_file] [--host localhost] [--port 4848] [--secure | -s] attribute_name=value [attribute_name=value] *

> For more information about the general asadmin parameters (--user, --password, --passwordfile, --host, --port, and --secure), see the Sun Java System Application Server Administrator’s Guide.

> The attribute_name is a hierarchical name that looks like this:

> instance.jms-service.jms_attribute_name

> The instance is the application server instance name. The jms_attribute_name is the JMS service attribute that needs to be configured. For example:

> server1.jms-service.port

> To view the list of JMS service attribute names that can be configured using the asadmin set command, use the asadmin get command with a wildcard. The asadmin get command has the same syntax as the asadmin set command. For example:

> asadmin get --user joeuser --password secret "server1.jms-service.*"

> A list of attribute names for configuring the JMS service of the server1 application server instance is displayed as follows:

> server1.jms-service.logLevel
> server1.jms-service.startArgs
> server1.jms-service.adminPassword
> server1.jms-service.port
> server1.jms-service.enabled
> server1.jms-service.adminUserName
> server1.jms-service.initTimeoutInSeconds

> Here is an example of running the asadmin set command:

> asadmin set --user joeuser --password secret server1.jms-service.enabled=false

> The attribute_name for a JMS property is a hierarchical name that looks like this:

> instance.jms-service.property.jms_property_name

> The instance is the application server instance name. The jms_property_name is the JMS service property that needs to be configured. Here is an example of running the asadmin set command to set a JMS property:

> asadmin set --user joeuser --password secret server1.jms-service.property.instance-name-suffix=xyz

> ### Checking Whether the JMS Provider Is Running

> You can use the asadmin jms-ping command to check whether a Sun Java System Message Queue instance is running. The syntax is as follows, with defaults shown for optional parameters that have them:

> asadmin jms-ping --user admin_user [--password admin_password] [--passwordfile password_file] [--host localhost] [--port 4848] [--secure | -s] instance_name

> For example:

> asadmin jms-ping --user joeuser --password secret server1

> ### Creating Physical Destinations

> Produced messages are delivered for routing and subsequent delivery to consumers using physical destinations in the JMS provider. A physical destination is identified and encapsulated by an administered object (a Topic or Queue destination resource) that an application component uses to specify the destination of messages it is producing and the source of messages it is consuming.

> This section describes how to create a physical destination. To create a destination resource, see Creating JMS Resources: Destinations and Connection Factories.

> You can create a JMS physical destination in the following ways:

> - Using the Administration Interface
> - Using the Command Line Interface

> The “Using The Administration Interface” section describes each connection pool setting. The “Using The Command Line Interface” section merely lists syntax and default values.

> #### Using the Administration Interface

> To create a JMS physical destination using the Administration interface, perform the following tasks:

> 1. Open the JMS component under your server instance.
> 2. Click Service, then click Physical Destinations.
> 3. Click the New button.
> 4. Enter the following information:
> - Destination Name (required) - Specify the name of the physical destination.
> - Type (required) - Select queue or topic from the list.
> 5. Click the OK button.

> #### Using the Command Line Interface

> To create a JMS physical destination using the command line, use the asadmin create-jmsdest command. The syntax is as follows, with defaults shown for optional parameters that have them:

> asadmin create-jmsdest --user admin_user [--password admin_password] [--passwordfile password_file] [--host localhost] [--port 4848] [--secure | -s] [--instance instance_name] --desttype dest_type [--property (name=value)[:name=value]*] dest_name

> For more information about the parameters specific to asadmin create-jmsdest, see Using the Administration Interface. For more information about the general asadmin parameters (--user, --password, --passwordfile, --host, --port, and --secure), see the Sun Java System Application Server Administrator’s Guide.

> For example:

> asadmin create-jmsdest --user joeuser --password secret --desttype topic MyDest

> To delete a JMS physical destination, use the following command:

> asadmin delete-jmsdest --user admin_user [--password admin_password] [--passwordfile password_file] [--host localhost] [--port 4848] [--secure | -s] [--instance instance_name] --desttype dest_type dest_name

> For example:

> asadmin delete-jmsdest --user joeuser --password secret --desttype topic MyDest

> To list JMS physical destinations, use the following command:

> asadmin list-jmsdest --user admin_user [--password admin_password] [--passwordfile password_file] [--host localhost] [--port 4848] [--secure | -s] [--desttype dest_type] instance_name

> For example:

> asadmin list-jmsdest --user joeuser --password secret --desttype topic server1

> ### Creating JMS Resources: Destinations and Connection Factories

> You can create two kinds of JMS resources in Sun Java System Application Server:

> - Connection Factories: administered objects that implement the QueueConnectionFactory or TopicConnectionFactory interfaces.
> - Destination Resources: administered objects that implement the Queue or Topic interfaces.

> In either case, the steps for creating a JMS resource are the same. You can create a JMS resource in the following ways:

> - Using the Administration Interface
> - Using the Command Line Interface

> The “Using The Administration Interface” section describes each connection pool setting. The “Using The Command Line Interface” section merely lists syntax and default values.

> #### Using the Administration Interface

> To create a JMS resource using the Administration interface, perform the following tasks:

> 1. Open the JMS component under your server instance.
> 2. Click Connection Factories to create a connection factory, or click Destination Resources to create a queue or topic.
> 3. Click the New button.
> 4. Enter the following information:
> - JNDI Name (required) - Enter the JNDI name that application components must use to access the JMS resource. For more information, see Looking Up Connection Factories and Looking Up Destinations.
> - Type (required) - Select the type of the JMS resource.
> - If you are on the Connection Factories page, the types are:

> javax.jms.TopicConnectionFactory
> javax.jms.QueueConnectionFactory

> - If you are on the Destination Resources page, the types are:

> javax.jms.Topic
> javax.jms.Queue

> - Description (optional) - You can enter a text description of the JMS resource.
> 5. Check the Resource Enabled box to enable the JMS resource.

> If a JMS resource is disabled, no application component can connect to it, but its configuration remains in the server instance.

> 6. Click the OK button.
> 7. To add properties to a JMS resource, perform the following tasks:
> 1. Go back to the Connection Factories or Destination Resources page.
> 2. Click the JMS resource you just created.
> 3. Click the Properties button.
> 4. Specify names and values for any properties you want to use. If you need another name-value row, use the Add button to add it. The following table lists the standard JMS resource properties.

> Table 5-3 JMS Resource Properties

> Property | Default | Description
> --- | --- | ---
> imqDestinationName | none | Specifies the JMS physical destination name associated with this JMS resource. You must specify this property for JMS resources of the Type javax.jms.Topic or javax.jms.Queue. The Sun Java System Message Queue Administrator's Guide shows a default value for this property, but this does not apply in the Sun Java System Application Server environment.
> imqBrokerHostName | the same host name as the Sun Java System Application Server instance (localhost) | Specifies the host name where the JMS service (Sun Java System Message Queue broker) is running. For JMS resources of the Typejavax.jms.TopicConnectionFactory or javax.jms.QueueConnectionFactory.
> imqBrokerHostPort | the JMS Service’s Port setting | Specifies the port where the JMS service (Sun Java System Message Queue broker) is running. For JMS resources of the Typejavax.jms.TopicConnectionFactory or javax.jms.QueueConnectionFactory.
> imqConfiguredClientID | none | Specifies the JMS Client Identifier to be associated with a Connection created using the createQueueConnection and createTopicConnection methods of the QueueConnectionFactory and TopicConnectionFactory classes, respectively. For JMS resources of the Typejavax.jms.TopicConnectionFactory or javax.jms.QueueConnectionFactory. Durable subscription names are unique and only valid within the scope of a client identifier. To create or reactivate a durable subscriber, the connection must have a valid client identifier. The JMS specification ensures that client identifiers are unique and that a given client identifier is allowed to be used by only one active connection at a time.

> 5. Click the OK button.
> 6. Click the Save button.
> 8. Go to the server instance page.
> 9. Click the General tab.
> 10. Click the Apply Changes button.

> #### Using the Command Line Interface

> To create a JMS resource using the command line, use the asadmin create-jms-resource command. The syntax is as follows, with defaults shown for optional parameters that have them:

> asadmin create-jms-resource --user admin_user [--password admin_password] [--passwordfile password_file] [--host localhost] [--port 4848] [--secure | -s] [--instance instance_name] --resourcetype resource_type [--enabled=true] [--description text] [--property (name=value)[:name=value]*] jndi_name

> For more information about the parameters specific to asadmin create-jms-resource, see Using the Administration Interface. For more information about the general asadmin parameters (--user, --password, --passwordfile, --host, --port, and --secure), see the Sun Java System Application Server Administrator’s Guide.

> For example:

> asadmin create-jms-resource --user joeuser --password secret --resourcetype javax.jms.Topic --property imqDestinationName=testTopic MyTopic

> To delete a JMS resource, use the following command:

> asadmin delete-jms-resource --user admin_user [--password admin_password] [--passwordfile password_file] [--host localhost] [--port 4848] [--secure | -s] [--instance instance_name] jndi_name

> For example:

> asadmin delete-jms-resource --user joeuser --password secret MyTopic

> To list JMS resources, use the following command:

> asadmin list-jms-resources --user admin_user [--password admin_password] [--passwordfile password_file] [--host localhost] [--port 4848] [--secure | -s] [--resourcetype resource_type] [--instance instance_name]

> For example:

> asadmin list-jms-resources --user joeuser --password secret --resourcetype Topic --instance server1

> After you create the JMS resource, you must reconfigure the server instance using the following command:

> asadmin reconfig --user user [--password password] [--passwordfile password_file] [--host localhost] [--port 4848] [--secure | -s][--discardmanualchanges=false | --keepmanualchanges=false] instance_name

> For example:

> asadmin reconfig --user joeuser --password secret server1

> ##

> Creating Applications That Use the JMS API

> This section discusses how to use the JMS API in applications:

> - Basic Steps for Developing a JMS Client
> - Processing JMS Messages
> - JMS Cleanup

> ### Basic Steps for Developing a JMS Client

> Developing a JMS client involves these tasks:

> - Importing the JMS Package
> - Looking Up Connection Factories
> - Creating Connections
> - Creating Sessions
> - Looking Up Destinations
> - Creating Message Producers
> - Creating Message Consumers
> - Starting the Connection

> #### Importing the JMS Package

> The javax.jms and javax.naming packages define all the JMS interfaces necessary to develop a JMS client. Import these packages as follows:

> import javax.jms.*;
> import javax.naming.*;

> #### Looking Up Connection Factories

> The standard JNDI subcontext for JMS connection factories is java:comp/env/jms. The resource lookup in the application code looks like this for point-to-point messaging:

> InitialContext ic = new InitialContext();
> QueueConnectionFactory QCFactory = (QueueConnectionFactory) ic.lookup("java:comp/env/jms/MyQCF");

> For publish-subscribe messaging, the only difference is that TopicConnectionFactory is used instead.

> For more information about the JNDI API, see Chapter 4, “Using the Java Naming and Directory Interface.”

> #### Creating Connections

> After you have looked up a connection factory, use it to create connections to the JMS provider. The following code creates a connection for point-to-point messaging:

> QueueConnection connection = QCFactory.createQueueConnection();

> The following code creates a connection for publish-subscribe messaging:

> TopicConnection tConnection = TCFactory.createTopicConnection();

> Note | A servlet should not create Java threads.

> #### Creating Sessions

> Sessions are lightweight JMS objects which provide a context for producing and consuming messages. Sessions are used to create message producers and message consumers, as well as to build messages themselves. The following code creates a session for point-to-point messaging:

> QueueSession session = connection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);

> The following code creates a session for publish-subscribe messaging:

> TopicSession tSession = tConnection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);

> For more information about acknowledgement modes, of which AUTO_ACKNOWLEDGE is one, see Using Acknowledgements.

> #### Looking Up Destinations

> You look up queues and topics by their JNDI names directly. Unlike connection factories, queues and topics do not use resource references in the deployment descriptor files.

> The following code looks up a queue:

> Queue queue = (Queue) ic.lookup("java:comp/env/jms/sampleQ");

> The following code looks up a topic:

> Topic topic = (Topic) ic.lookup("java:comp/env/jms/sampleT");

> To create a queue or topic, see Creating JMS Resources: Destinations and Connection Factories.

> #### Creating Message Producers

> Use the session and destination to create a message producer. The following code creates a message producer for point-to-point messaging:

> QueueSender qSender = session.createSender(queue);

> The following code creates a message producer for publish-subscribe messaging:

> TopicPublisher tPublisher = tSession.createPublisher(topic);

> #### Creating Message Consumers

> You use the session and destination to create a message consumer as well. The following code creates a message consumer for point-to-point messaging:

> QueueReceiver qReceiver = session.createReceiver(queue);

> The following code creates a message consumer for publish-subscribe messaging:

> TopicSubscriber tSubscriber = tSession.createSubscriber(topic);

> For both point-to-point and publish-subscribe message consumers, you can optionally register a message listener with your message consumer to enable asynchronous messaging. First, write a class that implements the MessageListener interface (which contains the onMessage() method), then call the setMessageListener() method of the message consumer:

> tSubscriber.setMessageListener(this);

> It is assumed that the class containing the example code above implements the MessageListener interface, which is why this is used in the setMessageListener() method.

> #### Starting the Connection

> Use the following code to start a connection for point-to-point messaging:

> connection.start();

> Use the following code to start a connection for publish-subscribe messaging:

> tConnection.start();

> ### Processing JMS Messages

> When you have created message producers and consumers, you are ready to perform these tasks:

> - Sending Messages
> - Receiving Messages
> - Acknowledging Received Messages

> #### Sending Messages

> Point-to-point messaging sends one or more messages to a target queue as shown in the following code:

> TextMessage msgSent = session.createTextMessage();
> String msg = "Cold weather today";
> msgSent.setText( to + ":" + from + " ["+new Date()+"]: " + msg);
> qSender.send(msgSent);

> Publish-subscribe messaging publishes messages to a given topic as shown in the following code:

> TextMessage msgPub = tSession.createTextMessage();
> msgPub.setText("temperature: 35 degrees");
> tPublisher.publish(msgPub);

> #### Receiving Messages

> JMS messages can be received (or consumed) synchronously or asynchronously, whether they are used with point-to-point or publish-subscribe message consumers.

> JMS messages can be received synchronously in any of these ways:

> - Call the receive method with no arguments or an argument of 0, so that the method blocks indefinitely until a message arrives:

> TextMessage msgReceived = (TextMessage) qReceiver.receive();

> - Call the receive method with a timeout argument (in milliseconds) greater than 0:

> TextMessage msgReceived = (TextMessage) qReceiver.receive(2000);

> - Call the receiveNoWait method to receive a message only if one is available:

> TextMessage msgReceived = (TextMessage) qReceiver.receiveNoWait();

> To receive JMS messages asynchronously, you register a MessageListener with the consumer as described in Creating Message Consumers. The client consumes a message when a session thread invokes the onMessage() method of the MessageListener object.

> After you have received a message, you can get its contents:

> out("\nMessage received: " + msgReceived.getText());

> #### Acknowledging Received Messages

> You can guarantee successful message delivery using either of these mechanisms supported by a JMS session:

> - Using Acknowledgements
> - Using Transactions for Message Acknowledgement

> ##### Using Acknowledgements

> You can use one of these acknowledgement modes when you instantiate a session as described in Creating Sessions:

> - AUTO_ACKNOWLEDGE - The session automatically acknowledges a client’s receipt of a message either when the session has successfully returned from a call to receive or when the message listener the session has called to process the message successfully returns.
> - DUPS_OK_ACKNOWLEDGE - The session lazily acknowledges the delivery of messages. This is likely to result in the delivery of some duplicate messages if the JMS provider fails, so it should only be used by consumers that can tolerate duplicate messages. Use of this mode can reduce session overhead by minimizing the work the session does to prevent duplicates.
> - CLIENT_ACKNOWLEDGE - The JMS client acknowledges a consumed message by calling the message’s acknowledge method. Acknowledging a consumed message acknowledges all messages that the session has consumed. When client acknowledgment mode is used, a client may build up a large number of unacknowledged messages while attempting to process them.

> ##### Using Transactions for Message Acknowledgement

> You can send and receive messages within local or distributed transactions to ensure message delivery. The JMS API provides methods for initiating, committing, or rolling back a local transaction.

> Distributed transactions use the Sun Java System Application Server’s transaction service. The following table lists the XA classes supported by the JMS provider.

> Table 5-4 XA Classes

> JMS Parent | Point-to-Point | Publish-Subscribe
> --- | --- | ---
> XAConnectionFactory | XAQueueConnectionFactory | XATopicConnectionFactory
> XAConnection | XAQueueConnection | XATopicConnection
> XASession | XAQueueSession | XATopicSession

> You can use the XASession.getTransacted() method to find out whether the current JMS distributed session is within a transaction.

> For details about the transaction service, see Chapter 3, “Using the Transaction Service.”

> ### JMS Cleanup

> To free system resources, make sure your application closes message producers, message consumers, sessions, and connections in that order. For example:

> qSender.close()
> qReceiver.close()
> session.close()
> connection.close()

> Calling close() statements inside a finally block is good programming practice.

> ##

> Delivering SOAP Messages Using the JMS API

> Web service clients use the Simple Object Access Protocol (SOAP) to communicate with web services. SOAP uses a combination of XML-based data structuring and Hyper Text Transfer Protocol (HTTP) to define a standardized way of invoking methods in objects distributed in diverse operating environments across the Internet.

> For more information about SOAP, see the Sun Java System Application Server Developer’s Guide to Web Services and the Apache SOAP web site:

> http://xml.apache.org/soap/index.html

> You can take advantage of the JMS provider’s reliable messaging when delivering SOAP messages. You can convert a SOAP message into a JMS message, send the JMS message, then convert the JMS message back into a SOAP message. The following sections explain how to do these conversions:

> - Sending SOAP Messages Using the JMS API
> - Receiving SOAP Messages Using the JMS API

> ### Sending SOAP Messages Using the JMS API

> You use the MessageTransformer utility to convert a SOAP message into a JMS message. You then send the JMS message containing the SOAP payload as you would a normal JMS message.

> 1. Import the library com.sun.messaging.xml.MessageTransformer. This is the utility whose methods you use to convert SOAP messages to JMS messages and the reverse.

> import com.sun.messaging.xml.MessageTransformer;

> 2. Initialize the TopicConnectionFactory, TopicConnection, TopicSession, and publisher.

> tcf = new TopicConnectionFactory();
> tc = tcf.createTopicConnection();
> session = tc.createTopicSession(false,Session.AUTO_ACKNOWLEDGE);
> topic = session.createTopic(topicName);
> publisher = session.createPublisher(topic);

> 3. Construct a SOAP message using the SOAP with Attachments API for Java (SAAJ). For more information on constructing a SOAP message, see the Sun Java System Application Server Developer’s Guide to Web Services and the Sun Java System Message Queue Developer’s Guide.

> *construct a default soap MessageFactory */
> MessageFactory mf = MessageFactory.newInstance();

> * Create a SOAP message object.*/
> SOAPMessage soapMessage = mf.createMessage();

> /** Get SOAP part.*/
> SOAPPart soapPart = soapMessage.getSOAPPart();

> /* Get SOAP envelope. */
> SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

> /* Get SOAP body.*/
> SOAPBody soapBody = soapEnvelope.getBody();

> /* Create a name object. with name space */
> /* http://www.sun.com/imq. */
> Name name = soapEnvelope.createName("HelloWorld", "hw",
> "http://www.sun.com/imq");

> * Add child element with the above name. */
> SOAPElement element = soapBody.addChildElement(name)

> /* Add another child element.*/
> element.addTextNode( "Welcome to SunOne Web Services." );

> /* Create an atachment with activation API.*/
> URL url = new URL ("http://java.sun.com/webservices/");
> DataHandler dh = new DataHandler (url);
> AttachmentPart ap = soapMessage.createAttachmentPart(dh);

> /*set content type/ID. */
> ap.setContentType("text/html");
> ap.setContentId("cid-001");

> /** add the attachment to the SOAP message.*/
> soapMessage.addAttachmentPart(ap);
> soapMessage.saveChanges();

> 4. Convert the SOAP message to a JMS message by calling the MessageTransformer.SOAPMessageintoJMSMessage() method.

> Message m = MessageTransformer.SOAPMessageIntoJMSMessage (soapMessage, session );

> 5. Publish the JMS message.

> publisher.publish(m);

> 6. Close the JMS connection.

> tc.close();

> ### Receiving SOAP Messages Using the JMS API

> You receive the JMS message containing the SOAP payload as you would a normal JMS message. You then use the MessageTransformer utility to convert the JMS message back into a SOAP message.

> 1. Import the library com.sun.messaging.xml.MessageTransformer. This is the utility whose methods you use to convert SOAP messages to JMS messages and the reverse.

> import com.sun.messaging.xml.MessageTransformer;

> 2. Initialize the TopicConnectionFactory, TopicConnection, TopicSession, TopicSubscriber, and Topic.

> messageFactory = MessageFactory.newInstance();
> tcf = new com.sun.messaging.TopicConnectionFactory();
> tc = tcf.createTopicConnection();

> session = tc.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

> topic = session.createTopic(topicName);
> subscriber = session.createSubscriber(topic);
> subscriber.setMessageListener(this);
> tc.start();

> 3. Use the OnMessage method to receive the message. Use the SOAPMessageFromJMSMessage method to convert the JMS message to a SOAP message.

> public void onMessage (Message message) {
> SOAPMessage soapMessage =
> MessageTransformer.SOAPMessageFromJMSMessage( message,
> messageFactory ); }

> 4. Retrieve the content of the SOAP message. For more information about SOAP messages, see the Sun Java System Application Server Developer’s Guide to Web Services.

> ##

> Sample Applications

> JMS sample applications are in the following directory:

> install_dir/samples/jms

> Message-driven bean sample applications are in the following directory:

> install_dir/samples/ejb/mdb

> Previous Contents Index Next

> Copyright 2004 Sun Microsystems, Inc. All rights reserved.