Google





You are here: CodeIdol.com > Java > J2EE Web Services > SAAJ > Creating A SOAP Message

SAVE
Digg
Shown on del.icio.us del.icio.us
See Whos Talking About This on Technorati Technorati
I've Reddit reddit

13.2 Creating a SOAP Message

To create a simple SOAP document, you obtain a new SOAPMessage object from a MessageFactory object, as shown in this snippet from SaajExample_1 (Listing 13-2):

MessageFactory msgFactory = MessageFactory.newInstance();
SOAPMessage message = msgFactory.createMessage();

Although you will usually work with basic SOAP messages, without attachments, the SAAJ API models SwA, not just SOAP. Appendix F: SAAJ Attachments shows how to create an SwA message in which the SOAP document is treated as a MIME part, and accessed via the SOAPMessage.getSOAPPart() method.

13.2.1 The MessageFactory Class

The MessageFactory is the root factory of SAAJ. It's the class you will start with each time you create a SOAP message. MessageFactory is an abstract class that contains three methods, as shown in Listing 13-3 (the implementations are omitted).

Listing 13-3 The javax.xml.soap.MessageFactory Class
package javax.xml.soap;

public abstract class MessageFactory {

  private static final String DEFAULT_MESSAGE_FACTORY =
          "com.sun.xml.messaging.saaj.soap.MessageFactoryImpl";

  private static final String MESSAGE_FACTORY_PROPERTY =
          "javax.xml.soap.MessageFactory";

  public static MessageFactory newInstance() throws SOAPException;

  public SOAPMessage createMessage() throws SOAPException;

  public SOAPMessage createMessage(MimeHeaders headers,java.io.InputStream in)
  throws SOAPException;
}
13.2.1.1 The newInstance() Method

The MessageFactory class itself is abstract and cannot be instantiated. Its new Instance() method creates an object that is actually a subtype of MessageFactory. By default, the instance is of a proprietary type provided by Sun Microsystems, when SAAJ is employed as a standalone API.

13.2.1.2 The createMessage() Method

In addition to the newInstance() method, the MessageFactory has two create Message() methods. The first takes no arguments, and is the one used in SaajExample_1. It simply creates a new SOAPMessage. The following code line from Listing 13-2 shows how the createMessage() method is used in an application.

SOAPMessage message = msgFactory.createMessage();

In this case the SOAPMessage object is generated from scratch, and contains only the framework of a SOAP message. If you were to dump the contents of the SOAPMessage instance to the screen, it would look something like the following.

<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header/>
  <soap:Body/>
</soap:Envelope>

Notice that the main message elements, Envelope, Header, and Body, are present, the last two empty. These are supplied as a convenience for the developer. Once the SOAPMessage is created, all you need to do is fill in the blanks using the SAAJ API.

13.2.1.3 The createMessage Method with Parameters

The MessageFactory's second create method can construct a SAAJ representation of an existing SOAP message, instead of building a new one from scratch. The following snippet from Listing 13-3 shows the createMessage() method declaration.

public abstract class MessageFactory {
  ...
  public SOAPMessage createMessage(MimeHeaders headers,java.io.InputStream in)
  throws SOAPException;
}

The MimeHeaders parameter holds one or more MIME headers. A MIME header is a name-value pair that describes the contents of a MIME block. For example, a SOAP document might have a MIME header with a name-value pair of "Content-Type = text/xml".

The InputStream parameter can be any kind of stream. For example it could be a network stream from a socket connection, an IO stream from a JDBC connection, or a simple file stream. The data obtained from the InputStream parameter must be a valid SOAP or SwA message. For example, suppose a file called soap.xml contains a SOAP document like the one shown in Listing 13-4.

Listing 13-4 The soap.xml File
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope
 xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
 xmlns:mh="http://www.Monson-Haefel.com/jwsbook/BookQuote">
   <soap:Body>
      <mh:getBookPrice>
          <isbn>0321146182</isbn>
      </mh:getBookPrice>
   </soap:Body>
</soap:Envelope>

Using a FileInputStream, the MessageFactory class can read the soap.xml file and generate a SAAJ object graph of the SOAP message it contains. In Listing 13-5 SaajExample_2 uses the MessageFactory class to read the file and generate a SOAPMessage.

Listing 13-5 Building a SAAJ Object Graph from a File
package com.jwsbook.saaj;
import java.io.FileInputStream;
import javax.xml.soap.*;

public class SaajExample_2 {
   public static void main(String [] args)
   throws SOAPException, java.io.IOException{

        MessageFactory msgFactory = MessageFactory.newInstance();

        MimeHeaders mimeHeaders = new MimeHeaders();
        mimeHeaders.addHeader("Content-Type","text/xml; charset=UTF-8");

        FileInputStream file = new FileInputStream("soap.xml");

        SOAPMessage message = msgFactory.createMessage(mimeHeaders, file);

        file.close();
        SaajOutputter.writeToScreen(message);
    }
}

In SaajExample_2 the MIME header "Content-Type=text/xml;charset =UTF-8" is added to an instance of MimeHeaders, which is the first parameter of the createMessage() method. The second parameter is an instance of FileInput Stream that points to the soap.xml file.

To summarize: You can use MessageFactory to create new SOAP messages from scratch or from an existing SOAP message obtained from some type of input stream. In many cases, however, you will use SAAJ in combination with JAX-RPC, as explained in Chapter 14, and receive a complete SAAJ message automatically. In such cases you will not need to use either of the createMessage() methods.

13.2.2 SaajOutputter Classes

To become skilled with SOAP, you must be able to read the SOAP messages generated by SAAJ, so this book uses a custom-built class called SaajOutputter to write SOAPMessage objects out in a nice, readable format. The following snippet shows how SaajOutputter is used.

MessageFactory msgFactory = MessageFactory.newInstance();
SOAPMessage message = msgFactory.createMessage();
SaajOutputter.writeToScreen(message);

SaajOutputter is not a part of the SAAJ API. It was developed specifically for this book and belongs to the com.jwsbook.saaj package, the example code for this chapter. As an alternative you can simply use the SOAPMessage.writeTo() method (using System.out as the parameter), but the output will have no line breaks and won't be as easy to read.

SaajOutputter is a simple hack that works only when the SOAPMessage does not contain attachments. If the SOAPMessage contains attachments, use SOAPMessage.writeTo() instead of SaajOutputter.

13.2.3 The SOAPMessage Class

In many cases, the SOAP message you're working with will not have attachments and will not need the MIME message format. The SAAJ implementations are smart enough to recognize when no attachments are added, and omit the MIME packaging when writing the message. If you look closely at SaajExample_1 (Listing 13-2), you'll notice that no MIME attachments are added, and that the output of the program is strictly XML and doesn't include any MIME headers or boundaries. When SaajExample_1 executed, the SAAJ toolkit realized that no attachments had been added, so it didn't enforce the use of the MIME message format.

Most of the methods defined by the SOAPMessage class are related to SwA MIME parts; these are covered in Appendix F: SAAJ Attachments. The only methods that are relevant to this chapter are writeTo(), getSOAPBody(), getSOAPHeader(), getProperty(), and setProperty().

13.2.3.1 The writeTo() Method

The SOAPMessage.writeTo() method simply writes the message represented by the SOAPMessage object to an output stream. If the SOAPMessage has no attachments, writeTo() will write only the XML SOAP part of the message to the stream. For example, in the following code snippet a SOAPMessage writes its contents to System.out (the screen) using writeTo().

MessageFactory msgFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = msgFactory.createMessage();
soapMessage.writeTo(System.out);

The output from the SOAPMessage.writeTo() method is the default content of the SOAP message without line breaks. The lack of line breaks and white space (except between the XML declaration and the SOAP message) creates a tight stream of text. Because SOAP message are, in practice, processed by software and not read by people, readability is not important; eliminating line breaks and unnecessary white space is considered more efficient.

13.2.3.2 The getSOAPBody() and getSOAPHeader() Methods

The root MIME part of any SwA message is always the XML SOAP document; this is covered in more detail in Appendix F. The getSOAPPart() method allows you to access the SOAP MIME part directly, as shown in this snippet.

MessageFactory msgFactory = MessageFactory.newInstance();
SOAPMessage message = msgFactory.createMessage();
SOAPPart soap = message.getSOAPPart();

Accessing the SOAPBody and SOAPHeader via the SOAPPart is not necessary, however, if the SOAP message does not use attachments, as will be the case with BP-conformant Web services. When there are no attachments, you can simply use the getSOAPBody() and getSOAPHeader() methods to access those elements in the SOAP message directly. The following snippet from SaajExample_1 shows how these methods are used.

MessageFactory msgFactory = MessageFactory.newInstance();
SOAPMessage message = msgFactory.createMessage();
message.getSOAPHeader().detachNode();
SOAPBody body = message.getSOAPBody();

The examples in this chapter use the getSOAPBody() and getSOAPHeader() methods. In Appendix F: SAAJ Attachments, the getSOAPPart() and getSOAPEnvelope() methods are used. The detachNode() method simply removes the Header element from the SOAP message—SAAJ always includes the Header by default. Header blocks are not used in this example, so the Header element is not needed.

13.2.3.3 The getProperty() and setProperty() Methods

The SOAPMessage type also defines the setProperty() and getProperty() methods, which are used to set and obtain standard and vendor-specific properties of a SOAPMessage object. There are two standard properties:

  • javax.xml.soap.CHARACTER_SET_ENCODING can be either "UTF-8" or "UTF-16" in applications that conform with the BP. The default is "UTF-8".BP

  • javax.xml.soap.WRITE_XML_DECLARATION can have a value of "true" or "false". If it's "true", then the XML declaration is included in the SOAP message; if "false", it is not. The default is "false". Web service endpoints must accept SOAP 1.1 messages with or without an XML declaration.BP

As an example, the following snippet modifies SaajExample_2 (Listing 13-5) so that it sets the values of CHARACTER_SET_ENCODING and WRITE_XML_DECLARATION to "UTF-16" and "true" respectively.

FileInputStream file = new FileInputStream("soap.xml");
SOAPMessage message = msgFactory.createMessage(mimeHeaders, file);

message.setProperty("javax.xml.soap.CHARACTER_SET_ENCODING", "UTF-16");
message.setProperty("javax.xml.soap.WRITE_XML_DECLARATION", "true");

With these properties set, the output for SaajExample_2 would be an XML document in UTF-16 with an XML document declaration, as follows:

<?xml version="1.0" encoding="UTF-16"?>
<soap:Envelope
 xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
 xmlns:mh="http://www.Monson-Haefel.com/jwsbook/BookQuote">
   <soap:Body>
      <mh:getBookPrice>
          <isbn>0321146182</isbn>
      </mh:getBookPrice>
   </soap:Body>
</soap:Envelope>

This SOAP message is exactly the same as the one in Listing 13-4, except that it includes the XML declaration shown in bold. XML declarations are explained in more detail in Section 2.1.2.1 and Section 4.1. The fact that the SOAP message is encoded using UTF-16 rather than UTF-8 is not visible to the eye.

    SAVE
    Digg
    Shown on del.icio.us del.icio.us
    See Whos Talking About This on Technorati Technorati
    I've Reddit reddit

    You are here: CodeIdol.com > Java > J2EE Web Services > SAAJ > Creating A SOAP Message


    ADBRITE ads links
       
    Related tags







    Popular Categories
    Unix books and guides
    AJAX popular information
    C# language guides
    Windows books and cookbooks

    .......








    Business Key Top Sites

    be number one
    rate your site





    © CodeIdol Labs, 2007 - 2009