Sun logo      Previous      Contents      Index      Next     

Sun ONE Message Queue 3.5 Java Client Developer's Guide

Chapter 6
Working With SOAP Messages

Using Sun™ ONE Message Queue (MQ), you can send JMS messages that contain a SOAP payload. This allows you to transport SOAP messages reliably and to publish SOAP messages to JMS subscribers. This chapter explains how you do the following:

This chapter begins with an overview of SOAP processing and describes the Java API for SOAP with attachments (JAXM). You need to know this information to process SOAP messages. The chapter concludes by explaining how you can create a JMS message that contains a SOAP message payload.

If you are familiar with the SOAP specification, you can skip the introductory section and start by reading "SOAP Messaging in JAVA".

The remaining sections in this chapter cover the following topics:

What is SOAP


The fact that SOAP messages are encoded in XML makes SOAP messages portable, because XML is a portable, system-independent way of representing data. By representing data using XML, you can access data from legacy systems as well as share your data with other enterprises. The data integration offered by XML also makes this technology a natural for web-based computing such as web services. Firewalls can recognize SOAP packets based on their content type (text/xml-SOAP) and can filter messages based on information exposed in the SOAP message header.


The SOAP protocol is fully described at This section restricts itself to discussing the reasons why you would use SOAP and to describing some basic concepts that will make it easier to work with the JAXM API.

SOAP and the JAVA for XML Messaging API

The JAVA API for XML messaging (JAXM) is a JAVA-based API that enforces compliance to the SOAP standard. When you use this API to assemble and disassemble SOAP messages, it ensures the construction of syntactically correct SOAP messages. JAXM also makes it possible to automate message processing when several applications need to handle different parts of a message before forwarding it to the next recipient.


Figure 6-1  SOAP Messaging Layers

Diagram showing the functional layers needed for SOAP messaging. Figure contents are explained in text.


The Transport Layer


The SOAP Layer






          <m:GetLastTradePrice xmlns:m="Some-URI">






The Provider Layer

In Figure 6-1 the provider is shown as two pieces of functionality: a language implementation and delivery semantics.

A provider language implementation allows you to create XML messages that conform to SOAP, using API calls. For example, any implementation of JAXM, allows a Java client to define the SOAP message and all its parts as Java objects. The client would also use JAXM to create a connection and use it to send the message. Likewise, a web service written in Java could use the same (or another) implementation of the JAXM API to receive the message, to disassemble it, and to acknowledge its receipt.

Messaging Semantics

In addition to a language implementation, a SOAP provider can offer services that relate to message delivery. These could include reliability, persistence, security, and administrative control. These services will be provided for SOAP messaging by MQ in future releases.


Because SOAP providers must all construct and deconstruct messages as defined by the SOAP specification, clients and services using SOAP are interoperable. That is, as shown in Figure 6-2, the client and the service doing SOAP messaging do not need to be written in the same language nor do they need to use the same SOAP provider. It is only the packaging of the message that must be standard.

Figure 6-2  SOAP Interoperability

Diagram showing how a client using one SOAP provider sends a message to a client using another SOAP provider.

In order for a JAXM client or service to interoperate with a service or client using a different provider, the parties must agree on two things:

Profiles provide additional processing information, as described next.

The Profiles Layer

The final, profile, layer of SOAP messaging governs messaging semantics between business partners who use SOAP messaging with SOAP providers. A profile is an industry standard, such as “ebxml”, which defines additional rules for message processing. A provider can add profile information to the header of a message when its message factory creates the message. (The SOAP message header is the primary means of SOAP messaging extensibility.) Support for the ebxml profile will be added in future releases of MQ.

The SOAP Message

Having surveyed the SOAP messaging layers, let’s examine the SOAP message itself. Although the work of rendering a SOAP message in XML is taken care of by the JAXM libraries, you must still understand its structure in order to make the JAXM calls in the right order.


A SOAP message may also contain an attachment, which does not have to be in XML. For more information, see "SOAP Packaging Models" next.


SOAP Packaging Models



Figure 6-3  SOAP Message Without Attachments

Diagram showing body and header enclosed in an envelope, which is in a SOAP message package, which is in a communication protocol envelope.

When you construct a SOAP message using JAXM, you do not have to specify which model you’re following. If you add an attachment, a message like that shown in Figure 6-4 is constructed; if you don’t, a message like that shown in Figure 6-3 is constructed.


A message that contains one or more attachments is enclosed in a MIME envelope that contains all the parts of the message. In JAXM, the MIME envelope is automatically produced whenever the client creates an attachment part. If you add an attachment to a message, you are responsible for specifying (in the MIME header) the type of data in the attachment.

Figure 6-4  SOAP Message with Attachments

Diagram showing SOAP part enclosed in a MIME envelope together with the attachment part, which contains the SOAP attachment.

SOAP Messaging in JAVA




It also explains how you can use the JMS API and MQ to send and receive JMS messages that carry SOAP message payloads.

The SOAP Message Object

A SOAP Message Object is a tree of objects as shown in Figure 6-5. The classes or interfaces from which these objects are derived are all defined in the javax.xml.soap package.

Figure 6-5  SOAP Message Object

Diagram showing hierarchy of objects that make up a SOAP message object. Long description follows figure.[D]


The SOAP part of the message contains an envelope that contains a body (which can contain data or fault information) and an optional header. When you use JAXM to create a SOAP message, the SOAP part, envelope, and body are created for you: you need only create the body elements. To do that you need to get to the parent of the body element, the SOAP body.

In order to reach any object in the SOAPMessage tree, you must traverse the tree starting from the root, as shown in the following lines of code. For example, assuming we have created the SOAPMessage MyMsg, here are the calls you would have to make in order to get the SOAP body:

SOAPPart MyPart = MyMsg.getSOAPPart();

SOAPEnvelope MyEnv = MyPart.getEnvelope();

SOAPBody MyBody = envelope.getBody();

At this point, you can create a name for a body element (as described in "Namespaces") and add the body element to the SOAPMessage.


Name bodyName = envelope.createName("Temperature");

The next code line adds the body element to the body:

SOAPBodyElement myTemp = MyBody.addBodyElement(bodyName);



Inherited Methods


Table 6-1  Inherited Methods 

Inherited From

Method Name



addAttribute(Name, String)

Add an attribute with the specified Name object and string value.



addChildElement(String, String)

addChildElement(String, String, String)


(Use the Envelope.createName method to create a Name object.)


addNameSpaceDeclaration (String, String)

Add a namespace declaration with the specified prefix and URI.






Return an iterator over all the attribute names in this object.



Return the value of the specified attribute.



Return an iterator over all the immediate content of this element.



Return an iterator over all the child elements with the specified name.



Return the name of this object.



Return the encoding style for this object.



Return an iterator of namespace prefixes.



Return the URI of the namespace with the given prefix.



Remove the specified attribute.



Remove the namespace declaration that corresponds to the specified prefix.



Set the encoding style for this object to that specified by String.



Remove this Node object from the tree.



Return the parent element of this Node object.









Set the parent of this object to that specified by the SOAPElement parameter.



An explicit XML namespace declaration takes the following form


xmlns:prefix ="URI">


The following is an example of a namespace declaration:

<SOAP-ENV:Envelope xmlns:SOAP-ENV=""

This declaration defines SOAP_ENV as an alias for the namespace

After defining the alias, you can use it as a prefix to any attribute or element in the Envelope element. In Code Example 6-1, the elements <Envelope> and <Body> and the attribute encodingStyle all belong to the SOAP namespace specified by the URI "".

Code Example 6-1  Explicit Namespace Declarations 








     The text of the header










Pre-defined SOAP Namespaces

SOAP defines two namespaces:

When you use JAXM to construct or consume messages, you are responsible for setting or processing namespaces correctly and for discarding messages that have incorrect namespaces.

Using Namespaces when Creating a SOAP Name


When you call this method, you can pass a local name as a parameter or you can specify a local name, prefix, and uri. For example, the following line of code defines a name object bodyName.

Name bodyName = MyEnvelope.createName("TradePrice",

This would be equivalent to the namespace declaration:

<GetLTP:TradePrice xmlns:GetLTP= "">




SOAPBodyElement gltp = body.addBodyElement(bodyName);

Parsing Name Objects


Destination, Message Factory, and Connection Objects

SOAP messaging occurs when a SOAP message, produced by a message factory, is sent to an endpoint via a connection.




Constructing an Endpoint

You can initialize an endpoint either by calling its constructor or by looking it up in a naming service. For information about creating administered objects for endpoints, see "Using JAXM Administered Objects".

The following code uses a constructor to create a URLEndpoint:


Using the Endpoint to Address a Message

If you are using a provider, the Message Factory creating the message includes the endpoint specification in the message header.

If you do not use a provider, you can specify the endpoint as a parameter to the method, which you use to send a SOAP message.

Sending a Message to Multiple Endpoints

If you are using an administered object to define an endpoint, note that it is possible to associate that administered object with multiple URLs--each URL, is capable of processing incoming SOAP messages. The code sample below associates the endpoint whose lookup name is myEndpoint with two URLs: http://www.myServlet1/ and http://www.myServlet2/.

imqobjmgr add

  -t e

  -l "cn=myEndpoint"

  -o "imqSOAPEndpointList=http://www.myServlet1/

This syntax allows you to use a SOAP connection to publish a SOAP message to multiple endpoints. For additional information about the endpoint administered object, see "Using JAXM Administered Objects".

Message Factory

You use a Message Factory to create a SOAP message.


To send a SOAP message using JAXM, you must obtain either a SOAPConnection or a ProviderConnection. You can also transport a SOAP message using MQ; for more information, see "Integrating SOAP and MQ".

SOAP Connection


Provider Connection

A ProviderConnection, which you get from a ProviderConnectionFactory, creates a connection to a particular messaging provider. When you send a SOAP message using a provider, the message is forwarded to the provider, and then the provider is responsible for delivery to its final destination. The provider guarantees reliable, secure messaging. (MQ does not currently offer SOAP provider support.)

Using JAXM Administered Objects

Administered objects are objects that encapsulate provider-specific configuration and naming information. For endpoint objects, you have the choice either to instantiate such an object or to create an administered object and associate it with an endpoint object instance.

The main benefit of creating an endpoint through a JNDI lookup is to isolate endpoint URLs from the code, allowing the application to switch the destination without recompiling the code. A secondary benefit is provider independence.

Creating an administered object for a SOAP element is the same as creating an administered object in MQ: you use the Object Manager (imqobjmgr) utility to specify the lookup name of the object, its attributes, and its type.

Table 6-2 lists and describes the attributes and other information that you need to specify when you create an endpoint administered object. Remember to specify all attributes as strings.

Table 6-2  SOAP Administered Object Information 



-o “attribute=val

Use this option to specify three possible attributes for an endpoint administered object:

  • A URL list
  • -o “imqSOAPEndpointList = “url1 url2 ....urln

    The list may contain one or more space-separated URLs. If it contains more than one, the message is broadcast to all the URLs. Each URL should be associated with a servlet that can receive and process a SOAP message.

  • A name
  • -o “imqEndpointName=SomeName

    If you don’t specify a name, the name Untitled_Endpoint_Object is used by default.

  • A description
  • -o "imqEndpointDescription=my endpoints for broadcast"

    If you don’t specify a description, the default value "A description for the endpoint object" is supplied by default.

-l “cn=lookupName

Use this option to specify the lookup name of the endpoint.

-t type

Use this option to specify the object’s type. This is always e for an endpoint.

-i filename

Use this option to specify the name of an input file containing imqobjmgr commands. Such an input file is typically used to specify object store attributes.

-j “attribute=val

Use this option to specify object store attributes. You can also specify these in an input file. Use the -i option to specify the input file.

Code Example 6-2 shows how you use the imqobjmgr command to create an administered object for an endpoint and add it to an object store. The -i option specifies the name of an input file that defines object store attributes (-j option).

Code Example 6-2  Adding an Endpoint Administered Object 

imqobjmgr add

  -t e

  -l "cn=myEndpoint"

  -o "imqSOAPEndpointList=http://www.myServlet/

  -o "imqEndpointName=MyBroadcastEndpoint"

  -i MyObjStoreAttrs

Having created the administered object and added it to an object store, you can now use it when you want to use an endpoint in your JAXM application. In Code Example 6-3, you first create an initial context for the JNDI lookup and then you look up the desired object.

Code Example 6-3  Looking up an Endpoint Administered Object 

Hashtable env = new Hashtable();

env.put (Context.PROVIDER_URL,

Context ctx = new InitialContext(env);

Endpoint mySOAPEndpoint = (Endpoint)

You can also list, delete, and update administered objects. For additional information, please see MQ Administrator’s Guide.

SOAP Messaging Models and Examples

This section explains how you use JAXM to send and receive a SOAP message. It is also possible to construct a SOAP message using JAXM and to send it as the payload of a JMS message. For information, see "Integrating SOAP and MQ".

JAXM supplies two models that you can use to do SOAP messaging: one uses the SOAPConnection object and the other uses the ProviderConnection object. MQ does not currently support the ProviderConnection object.

SOAP Messaging Programming Models

This section provides a brief summary of the programming models used in SOAP messaging using JAXM.

A SOAP message is sent to an endpoint by way of a connection. There are two types of connections: point-to-point connections (implemented by the SOAPConnection class) and provider connections (implemented by the ProviderConnection class).

Point-to-Point Connections

You use point-to-point connections to establish a request-reply messaging model. The request-reply model is illustrated in Figure 6-6.

Figure 6-6  Request-Reply Messaging

Diagram showing the client sending a message to an endpoint that receives the message, processes it, and then returns to the sender.

Using this model, the client does the following:


The JAXM service listening for a request-reply message uses a ReqRespListener object to receive messages.

For a detailed example of a client that does point-to-point messaging, see "Writing a SOAP Client".

Provider Connections

You use a provider connection to implement one-way messaging. Figure 6-7 illustrates the one-way messaging model.

Figure 6-7  One-way Messaging

Diagram showing SOAP message being sent by way of a messaging provider to a SOAP endpoint.

As opposed to the point-to-point model, the final destination for the message is written into the message header by the provider. (When the administrator configures the messaging provider, she can supply a list of Endpoint objects. When a client uses the provider to send messages, the provider sends the messages only to those parties represented by Endpoint objects in its messaging provider’s list.)

A message sent by means of a provider connection is always routed through an intermediate destination in the provider before it is forwarded to its final destination. The provider is also responsible for the reliability of the transmission and the privacy of the message.

Using this model, the client does the following:

The JAXM service listening for a one way message uses a OnewayListener object to receive messages asynchronously.

Working with Attachments




    To Create and Add an Attachment
  2. URL url = new URL("");

  4. DataHandler dh = new DataHandler(url);

  6. AttachmentPart ap1 = message.createAttachmentPart(dh);

  7. Add the attachment part to the SOAP message.
  8. myMessage.addAttachmentPart(ap1);



Exception and Fault Handling


Writing a SOAP Client


  1. Get an instance of a SOAPConnectionFactory:
  2. SOAPConnectionFactory myFct = SOAPConnectionFactory.newInstance();

  3. Get a SOAP connection from the SOAPConnectionFactory object:
  4. SOAPConnection myCon = myFct.createConnection();


  5. Get a MessageFactory object to create a message:
  6. MessageFactory myMsgFct = MessageFactory.newInstance();

  7. Use the message factory to create a message.
  8. SOAPMessage message = myMsgFct.createMessage();

    The message that is created has all the parts that are shown in the next figure.

    Diagram showing SOAP message with pre-initialized objects: part, envelope, header, and body.



    SOAPPart mySPart = message.getSOAPPart();

    SOAPEnvelope myEnvp = mySPart.getEnvelope();

  9. Now, you can get the body element from the myEnvp object:
  10. SOAPBody body = myEnvp.getBody();


  12. Name bodyName = envelope.createName("GetLastTradePrice", "m",

    SOAPBodyElement gltp = body.addBodyElement(bodyName);

  13. Now, we’ll create another body element to add to the gltp element:
  14. Name myContent = envelope.createName("symbol");

    SOAPElement mySymbol = gltp.addChildElement(myContent);

  15. And now you can define data for the body element mySymbol:
  16. mySymbol.addTextNode("SUNW");

    The resulting SOAP message object is equivalent to this XML scheme:

    <SOAP-ENV: Envelope



          <m:GetLastTradePrice xmlns:m="">




    </SOAP-ENV: Envelope>

  18. message.saveChanges();

  20. URLEndpoint endPt = new

  21. Now, you can send the message:
  22. SOAPMessage reply =, endPt);


  24. myCon.close();

Writing a SOAP Service



Using either of these interfaces, you must implement a method called onMessage(SOAPMsg). JAXMservlet will call onMessage after receiving a message using the HTTP POST method, which saves you the work of implementing your own doPost() method to convert the incoming message into a SOAP message.

Code Example 6-4 shows the basic structure of a SOAP service that uses the JAXM servlet utility class.

Code Example 6-4  Skeleton Message Consumer 

public class MyServlet extends JAXMServlet implements


  public SOAPMessage onMessage(SOAP Message msg)

  { //Process message here



Code Example 6-5 shows a simple ping message service:

Code Example 6-5  A Simple Ping Message Service 

public class SOAPEchoServlet extends JAXMServlet
                    implements ReqRespListener{

  public SOAPMessage onMessage(SOAPMessage mySoapMessage) {

    return mySoapMessage




Table 6-3  JAXMServlet Methods 



void init



void doPost (HTTPRequest, HTTPResponse



It is recommended that you do not override this method.

void setMessageFactory (MessageFactory)


MimeHeaders getHeaders (HTTPRequest)


void putHeaders (mimeHeaders, HTTPresponse)




Disassembling Messages



See for more information about the DOM API.

Code Example 6-6  Processing a SOAP Message 


  SOAPEnvelope env = reply.getSOAPPart().getEnvelope();

  SOAPBody sb = env.getBody();

  // create Name object for XElement that we are searching for

  Name ElName = env.createName("XElement");

  //Get child elements with the name XElement

  Iterator it = sb.getChildElements( ElName );

  //Get the first matched child element.
  //We know there is only one.

  SOAPBodyElement sbe = (SOAPBodyElement);

  //Get the value for XElement

  MyValue =   sbe.getValue();


Handling Attachments

A SOAP message may have attachments. For sample code that shows you how to create and add an attachment, see Code Example 6-7. For sample code that shows you how to receive and process an attachment, see Code Example 6-8.

In handling attachments, you will need to use the Java Activation Framework API. See for more information.

Replying to Messages


Handling SOAP Faults



Within a SOAP message object, the SOAP fault object is a child of the SOAP body, as shown in Figure 6-8. Detail and detail entry objects are only needed if one needs to report that the body of the received message was malformed or contained inappropriate data. In such a case, the detail entry object is used to describe the malformed data.

Figure 6-8  SOAP Fault Element

Diagram showing hierarchy from top to bottom for a message containing fault information: SOAP part, envelope, body, fault, detail, and detail entry.

The SOAP Fault element defines the following four sub-elements:

Predefined Fault Codes


Table 6-4  SOAP Faultcode Values 

Faultcode Name











These standard fault codes represent classes of faults. You can extend these by appending a period to the code and adding an additional name. For example: you could define a Server.OutOfMemory code, a Server.Down code, etc.

Defining a SOAP Fault


SOAPFault fault;

reply = factory.createMessage();

envp = reply.getSOAPPart().getEnvelope(true);

someBody = envp.getBody();

fault = someBody.addFault():


fault.setFaultString("Some Server Error");





SOAPFault fault = someBody.addFault();



fault.setFaultString ("Unkown error");

Detail myDetail = fault.addDetail();

detail.addDetailEntry(envelope.createName("125detail", "m",
    the string //");


Integrating SOAP and MQ


MQ provides a utility to help you send and receive SOAP messages using the JMS API. With the support it provides, you can convert a SOAP message into a JMS message in order to take advantage of MQ’s reliable messaging service, and then convert it back into a SOAP message on the receiving side and process it as such using the JAXM API.

To send, receive, and process a JMS message that contains a SOAP payload you must do the following:


Example 1: Deferring SOAP Processing


For information on how the servlet receives the SOAP message, see "Writing a SOAP Service".

Figure 6-9  Deferring SOAP Processing

Diagram showing deferred SOAP processing. Figure content is described in text.

    To Transform the SOAP Message into a JMS Message and Send the JMS Message
  2. QueueConnectionFactory myQConnFact =
        new com.sun.messaging.QueueConnectionFactory();

  3. Use the ConnectionFactory object to create a Connection object.
  4. QueueConnection myQConn =

  5. Use the Connection object to create a Session object.
  6. QueueSession myQSess = myQConn.createQueueSession(false,

  7. Instantiate an MQ Destination administered object corresponding to a physical destination in the MQ Message Service. In this example, the administered object is mySOAPQueue and the physical destination to which it refers is myPSOAPQ.
  8. Queue mySOAPQueue = new com.sun.messaging.Queue("myPSOAPQ");

  10. Message MyJMS = MessageTransformer.SOAPMessageIntoJMSMessage
                      (MySOAPMsg, MyQSess);

  11. Create a QueueSender message producer.
  12. This message producer, associated with mySOAPQueue, is used to send messages to the queue destination named myPSOAPQ.

    QueueSender myQueueSender = myQSess.createSender(mySOAPQueue);

  13. Send a message to the queue.
  14. myQueueSender.send(myJMS);

    To Receive the JMS Message, Transform it into a SOAP Message, and Process It
  1. Instantiate a ConnectionFactory object and set its attribute values.
  2. QueueConnectioFactory myQConnFact = new

  3. Use the ConnectionFactory object to create a Connection object.
  4. QueueConnection myQConn = myQConnFact.createQueueConnection();

  5. Use the Connection object to create one or more Session objects.
  6. QueueSession myRQSess = myQConn.createQueueSession(false,

  7. Instantiate a Destination object and set its name attribute.
  8. Queue myRQueue = new com.sun.messaging.Queue("mySOAPQ");

  9. Use a Session object and a Destination object to create any needed MessageConsumer objects.
  10. QueueReceiver myQueueReceiver =

  11. If needed, instantiate a MessageListener object and register it with a MessageConsumer object.
  12. Start the QueueConnection you created in Step 2. Messages for consumption by a client can only be delivered over a connection that has been started.
  13. myQConn.start();

  14. Receive a message from the queue
  15. The code, below, is an example of a synchronous consumption of messages.

    Message myJMS = myQueueReceiver.receive();

  16. Use the Message Transformer to convert the JMS message back to a SOAP message.
  17. SOAPMessage MySoap =
          (myJMS, MyMsgFactory);


  18. Disassemble the SOAP message in preparation for further processing. See "The SOAP Message Object" for information.

Example 2: Publishing SOAP Messages


Figure 6-10  Publishing a SOAP Message

Diagram showing how a SOAP message is transformed into a JMS message, published to listeners, and reconverted into SOAP.

The code that accomplishes this is exactly the same as in the previous example, except that instead of sending the JMS message to a queue, you send it to a topic. For an example of publishing a SOAP message using MQ, see Code Example 6-7.

Code Samples


Code Example 6-7 illustrates the use of the JMS API, the JAXM API, and the JAF API to send a SOAP message with attachments as the payload to a JMS message. The code shown for the SendSOAPMessageWithJMS includes the following methods:

Code Example 6-8 illustrates the use of the JMS API, the JAXM API, and the DOM API to receive a SOAP message with attachments as the payload to a JMS message. The code shown for the ReceiveSOAPMessageWithJMS includes the following methods:

Previous      Contents      Index      Next     

Copyright 2003 Sun Microsystems, Inc. All rights reserved.