- SOAP Messaging in JAVA
- The SOAP Message Object
- Inherited Methods
- Namespaces
- Pre-defined SOAP Namespaces
- Using Namespaces when Creating a SOAP Name
- Parsing Name Objects
- Destination, Message Factory, and Connection Objects
- Endpoint
- Constructing an Endpoint
- Using the Endpoint to Address a Message
- Message Factory
- Connection
- SOAP Connection
- Create SOAP message using Java
- Share this post
SOAP Messaging in JAVA
The SOAP specification does not provide a programming model or even an API for the construction of SOAP messages; it simply defines the XML schema to be used in packaging a SOAP message.
SAAJ is an application programming interface that can be implemented to support a programming model for SOAP messaging and to furnish Java objects that application or tool writers can use to construct, send, receive, and examine SOAP messages. SAAJ defines two packages:
- javax.xml.soap: you use the objects in this package to define the parts of a SOAP message and to assemble and disassemble SOAP messages. You can also use this package to send a SOAP message without the support of a provider.
- javax.xml.messaging: you use the objects in this package to send a SOAP message using a provider and to receive SOAP messages.
Beginning with SAAJ 1.3, you must put the file mail.jar explicitly in CLASSPATH.
This chapter focuses on the javax.xml.soap package and how you use the objects and methods it defines
It also explains how you can use the JMS API and Message Queue 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 5–5. The classes or interfaces from which these objects are derived are all defined in the javax.xml.soap package.
Figure 5–5 SOAP Message Object
As shown in the figure, the SOAPMessage object is a collection of objects divided in two parts: a SOAP part and an attachment part. The main thing to remember is that the attachment part can contain non-xml data.
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 SAAJ 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 the SOAPMessage is 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.
For example, the following code line creates a name (a representation of an XML tag) for a body element:
Name bodyName = envelope.createName("Temperature");
The next code line adds the body element to the body:
SOAPBodyElement myTemp = MyBody.addBodyElement(bodyName);
Finally, this code line defines some data for the body element bodyName :
Inherited Methods
The elements of a SOAP message form a tree. Each node in that tree implements the Node interface and, starting at the envelope level, each node implements the SOAPElement interface as well. The resulting shared methods are described in Table 5–1.
Add an attribute with the specified Name object and string value
addChildElement(Name) addChildElement(String, String) addChildElement (String, String, String)
Create a new SOAPElement object, initialized with the given Name object, and add the new element
(Use the Envelope.createName method to create a Name object)
addNameSpaceDeclaration (String, String)
Add a namespace declaration with the specified prefix and URI
Create a new Text object initialized with the given String and add it to this SOAPElement object
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
removeNamespaceDeclaration (String)
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
Return the value of the immediate child of this Node object if a child exists and its value is text
Notify the implementation that his Node object is no longer being used and is free for reuse
setParentElement(SOAPElement)
Set the parent of this object to that specified by the SOAPElement parameter
Namespaces
An XML namespace is a means of qualifying element and attribute names to disambiguate them from other names in the same document. This section provides a brief description of XML namespaces and how they are used in SOAP. For complete information, see http://www.w3.org/TR/REC-xml-names/
An explicit XML namespace declaration takes the following form:
prefix:myElement xmlns:prefix >
The declaration defines prefix as an alias for the specified URI. In the element myElement, you can use prefix with any element or attribute to specify that the element or attribute name belongs to the namespace specified by the URI.
The following is an example of a namespace declaration:
This declaration defines SOAP_ENV as an alias for the namespace:
http://schemas.xmlsoap.org/soap/envelope/
After defining the alias, you can use it as a prefix to any attribute or element in the Envelope element. In Example 5–1, the elements and and the attribute encodingStyle all belong to the SOAP namespace specified by the http://schemas.sxmlsoap.org/soap/envelope/URI .
Example 5–1 Explicit Namespace Declarations
Note that the URI that defines the namespace does not have to point to an actual location; its purpose is to disambiguate attribute and element names.
Pre-defined SOAP Namespaces
SOAP defines two namespaces:
- The SOAP envelope, the root element of a SOAP message, has the following namespace identifier:
"http://schemas.xmlsoap.org/soap/envelope"
"http://schemas.xmlsoap.org/soap/encoding"
When you use SAAJ 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 create the body elements or header elements of a SOAP message, you must use the Name object to specify a well-formed name for the element. You obtain a Name object by calling the method SOAPEnvelope.createName.
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", "GetLTP","http://foo.eztrade.com");
This would be equivalent to the namespace declaration:
The following code shows how you create a name and associate it with a SOAPBody element. Note the use and placement of the createName method.
SoapBody body = envelope.getBody();//get body from envelope Name bodyName = envelope.createName("TradePrice", "GetLTP", "http://foo.eztrade.com"); SOAPBodyElement gltp = body.addBodyElement(bodyName);
Parsing Name Objects
For any given Name object, you can use the following Name methods to parse the name:
- getQualifiedName returns " prefix:LocalName ", for the given name, this would be GetLTP:TradePrice.
- getURI would return "http://foo.eztrade.com" .
- getLocalName would return "TradePrice ".
- getPrefix would return "GetLTP".
Destination, Message Factory, and Connection Objects
SOAP messaging occurs when a SOAP message, produced by a message factory , is sent to an endpoint by way of a connection .
If you are working without a provider, you must do the following:
- Create a SOAPConnectionFactory object.
- Create a SOAPConnection object.
- Create an Endpoint object that represents the message’s destination.
- Create a MessageFactory object and use it to create a message.
- Populate the message.
- Send the message.
If you are working with a provider, you must do the following:
- Create a ProviderConnectionFactory object.
- Get a ProviderConnection object from the provider connection factory.
- Get a MessageFactory object from the provider connection and use it to create a message.
- Populate the message.
- Send the message.
The following three sections describe endpoint, message factory, and connection objects in greater detail.
Endpoint
An endpoint identifies the final destination of a message. An endpoint is defined either by the Endpoint class (if you use a provider) or by the URLEndpoint class (if you don’t use a provider).)
Constructing an Endpoint
You can initialize an endpoint by calling its constructor. The following code uses a constructor to create a URLEndpoint.
myEndpoint = new URLEndpoint("http://somehost/myServlet");
Using the Endpoint to Address a Message
To address a message to an endpoint, specify the endpoint as a parameter to the SOAPConnection.call method, which you use to send a SOAP message.
Message Factory
You use a Message Factory to create a SOAP message.
To instantiate a message factory directly, use a statement like the following:
MessageFactory mf = MessageFactory.newInstance();
Connection
To send a SOAP message using SAAJ, you must obtain a SOAPConnection . You can also transport a SOAP message using Message Queue; for more information, see Integrating SOAP and Message Queue.
SOAP Connection
A SOAPConnection allows you to send messages directly to a remote party. You can obtain a SOAPConnection object simply by calling the static method SOAPConnectionFactory.newInstance(). Neither reliability nor security are guaranteed over this type of connection.
Create SOAP message using Java
In this article, i am going to create the SOAP Message by using core Java Only. SOAP Stands for ” Simple Object Access Protocol”, which is used to exchange the structured information via Webservices.
SOAP Message consist of following three parts:
- SOAP-ENV:Envelope
- SOAP-ENV:Header
- SOAP-ENV:Body
To create the SOAP, first we will need to create the object of “javax.xml.soap.MessageFactory“, then create object of “javax.xml.soap.SOAPMessage“. This object of “SOAPMessage” will have all the messages inside it in “javax.xml.soap.SOAPEnvelope” object. Every “Envelope” will have the “Header” and “Body” as shown in below program:
package com.service.SOAPMain; import java.io.FileOutputStream; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPBody; import javax.xml.soap.SOAPBodyElement; import javax.xml.soap.SOAPEnvelope; import javax.xml.soap.SOAPHeader; import javax.xml.soap.SOAPMessage; import javax.xml.soap.SOAPPart; public class CreateSOAPMessage < /** * @param args */ public static void main(String[] args) < try< MessageFactory factory = MessageFactory.newInstance(); SOAPMessage soapMsg = factory.createMessage(); SOAPPart part = soapMsg.getSOAPPart(); SOAPEnvelope envelope = part.getEnvelope(); SOAPHeader header = envelope.getHeader(); SOAPBody body = envelope.getBody(); header.addTextNode("Training Details"); SOAPBodyElement element = body.addBodyElement(envelope.createName("JAVA", "training", "https://jitendrazaa.com/blog")); element.addChildElement("WS").addTextNode("Training on Web service"); SOAPBodyElement element1 = body.addBodyElement(envelope.createName("JAVA", "training", "https://jitendrazaa.com/blog")); element1.addChildElement("Spring").addTextNode("Training on Spring 3.0"); soapMsg.writeTo(System.out); FileOutputStream fOut = new FileOutputStream("SoapMessage.xml"); soapMsg.writeTo(fOut); System.out.println(); System.out.println("SOAP msg created"); >catch(Exception e) < e.printStackTrace(); >> >
As the output, one xml file of named “SoapMessage.xml” will be created and also printed on the console.