Introduction:In this article, the author and developer Nicholas Chase will show you how to use the Java API (Java API for XML messaging (jaxm) for XML message transmission )) simplify the process of creating and sending soap messages.
The foundation of Web Services is to send and receive messages in standard format so that all systems can understand them. Generally, the format is Simple Object Access Protocol (SOAP )). Soap messages can be manually generated and sent, but the Java API (jaxm) for XML message transmission automates many required steps (such as creating a connection or creating and sending actual messages. This article describes how to create and send a synchronous SOAP message.
This process includes five steps:
- Create a soap connection
- Create a SOAP message
- Fill messages
- Send message
- Retrieve response
Jaxm can be obtained as part of the Java XML pack (spring 2002) and Java Web Services developer pack ea2 (see references. The latter also contains a copy of the Tomcat web server and sample application. One of the sample Web Services serves as the destination of the SOAP message in this article. In this example, the actual service content and functions are not very important.
SOAP message structure
A basic SOAP message consists of two main parts (header and body. The application determines how to use these parts, but the entire message must follow a specific XML structure, for example:
Sample SOAP message
<soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/"> <soap-env:Header/> <soap-env:Body> <cal:schedule xmlns:cal="http://www.example.com/calendar"> <cal:newitem> <cal:eventDate>4/10/2002</cal:eventDate> <cal:title>Fun With Frogs</cal:title> </cal:newitem> </cal:schedule> </soap-env:Body></soap-env:Envelope> |
In this example, the header is empty, and the subject contains information for a calendar application as the destination.
Pay attention to the message structure. Envelope contains header and body elements, all of which arehttp://schemas.xmlsoap.org/soap/envelope/
A part of the namespace. The entire message is sent to a web service through a soap connection.
Back to Top
Create connection and message
The first step is to create the entire class and connection:
Create a connection
import javax.xml.soap.SOAPConnectionFactory;import javax.xml.soap.SOAPConnection;public class SOAPTip { public static void main(String args[]) { try { //First create the connection SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance(); SOAPConnection connection = soapConnFactory.createConnection(); //Close the connection connection.close(); } catch(Exception e) { System.out.println(e.getMessage()); } }} |
Soap messages can be usedSOAPConnection
Send directly or indirectly by using the message delivery provider. In this example, the application is created by using the factorySOAPConnection
Object.
The factory also creates the message itself:
Create a message object
import javax.xml.soap.SOAPConnectionFactory;import javax.xml.soap.SOAPConnection;import javax.xml.soap.MessageFactory;import javax.xml.soap.SOAPMessage;import javax.xml.soap.SOAPPart;import javax.xml.soap.SOAPEnvelope;import javax.xml.soap.SOAPBody;public class SOAPTip { public static void main(String args[]) { try { //First create the connection SOAPConnectionFactory soapConnFactory = SOAPConnectionFactory.newInstance(); SOAPConnection connection = soapConnFactory.createConnection(); //Next, create the actual message MessageFactory messageFactory = MessageFactory.newInstance(); SOAPMessage message = messageFactory.createMessage(); //Create objects for the message parts SOAPPart soapPart = message.getSOAPPart(); SOAPEnvelope envelope = soapPart.getEnvelope(); SOAPBody body = envelope.getBody(); //Close the connection connection.close(); } catch(Exception e) { System.out.println(e.getMessage()); } }} |
First, useMessageFactory
To create the message itself. This message already containsenvelope
Andheader
.SOAPPart
Includeenvelope
, Andenvelope
Contains the subject. Create the required object (for exampleSOAPBody
.
Then fillSOAPBody
:
Fill Body
...import javax.xml.soap.SOAPBody;import javax.xml.soap.SOAPElement;public class SOAPTip { public static void main(String args[]) { try {... //Create objects for the message parts SOAPPart soapPart = message.getSOAPPart(); SOAPEnvelope envelope = soapPart.getEnvelope(); SOAPBody body = envelope.getBody(); //Populate the body //Create the main element and namespace SOAPElement bodyElement = body.addChildElement(envelope.createName("schedule" , "cal", "http://www.example.com/calendar")); //Add content bodyElement.addChildElement("cal:newitem").addTextNode("contentHere"); //Save the message message.saveChanges(); //Check the input System.out.println("\nREQUEST:\n"); message.writeTo(System.out); System.out.println(); //Close the connection connection.close(); } catch(Exception e) { System.out.println(e.getMessage()); } }} |
The body of a SOAP message is like any other XML element. You can add sub-elements (suchschedule
Element ). Generally, you can useaddChildElement(elementname)
Butenvelope.createName()
The method simplifies the creation of Elements Using namespace declarations for data or loads. Indeed, the schedule element is createdbodyElement SOAPElement
Object. Then,bodyElement
Objects can be assigned their own child elements.cal:newitem
Add your own text nodes. In this way, you can build an XML structure like any other XML document.
However, with jaxm, you also have the opportunity to directly create messages by using external filesSOAPPart
. For example, the XML structure in the first configuration is saved in the fileprepped.msg
And can be called to replace manual document building.
Create a message from an external file
...import javax.xml.soap.SOAPElement;import java.io.FileInputStream;import javax.xml.transform.stream.StreamSource;public class SOAPTip { public static void main(String args[]) {... //Create objects for the message parts SOAPPart soapPart = message.getSOAPPart(); SOAPEnvelope envelope = soapPart.getEnvelope(); SOAPBody body = envelope.getBody(); //Populate the Message StreamSource preppedMsgSrc = new StreamSource( new FileInputStream("prepped.msg")); soapPart.setContent(preppedMsgSrc); //Save the message message.saveChanges();... }} |
The result is the SOAP message to be sent.
Back to Top
Send message
For synchronous messages, sending soap messages and receiving responses occur in a single step:
Send message
...import javax.xml.messaging.URLEndpoint;public class SOAPTip { public static void main(String args[]) { ... //Check the input System.out.println("\nREQUEST:\n"); message.writeTo(System.out); System.out.println(); //Send the message and get a reply //Set the destination URLEndpoint destination = new URLEndpoint("http://localhost:8080/jaxm-simple/receiver"); //Send the message SOAPMessage reply = connection.call(message, destination); //Close the connection connection.close(); ... }} |
The actual message is usedcall()
Sent by the method. This method takes the message itself and the destination as the parameter, and then returns the secondSOAPMessage
As a response. The destination must beEndpoint
Object, or in this exampleURLEndpoint
. In this example, a sample servlet from jwsdp is used only to obtain the response.
call()
Method is blocked until it receives the returnedSOAPMessage
So far.
Back to Top
Response
ReturnedSOAPMessage
―reply
-It is a SOAP message. It is in the same format as the sent message. Therefore, it can be operated like any other XML message. SOAP allows you to directly convert the response using XSLT:
Read response
...import javax.xml.transform.TransformerFactory;import javax.xml.transform.Transformer;import javax.xml.transform.Source;import javax.xml.transform.stream.StreamResult;public class SOAPTip { public static void main(String args[]) { try { ... //Send the message SOAPMessage reply = connection.call(message, destination); //Check the output System.out.println("\nRESPONSE:\n"); //Create the transformer TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); //Extract the content of the reply Source sourceContent = reply.getSOAPPart().getContent(); //Set the output for the transformation StreamResult result = new StreamResult(System.out); transformer.transform(sourceContent, result); System.out.println(); //Close the connection connection.close();... }} |
Create as in any XSLT ApplicationTransformer
Object. In this example, we only want to output the content, so the style sheet is not used. The content itself is the entire soap part of the message (different from the SOAP message that may contain attachments ). You can also extract the envelope and subject before processing. The result in this example is onlySystem.out
But it can be any choice that is usually used for conversion. Convert as usual.
Figure 1. SOAP request and response
Back to Top
Next step
Although the endpoint in this example is a servlet that provides static responses, the actual response depends on the service features and the nature of the request. At the same time, although this article demonstrates the synchronous sending and receiving of messagesProviderConnection
Object insteadSOAPConnection
Jaxm allows asynchronous sending using the message passing provider. The provider keeps saving the message until the message is successfully sent.
Jaxm is also allowedProfileThis makes it easy to create specialized soap messages, such as SOAP-RP or ebXML messages, and also enables non-XML attachments to be attached to soap messages.
References
- For more information, see the original article on the developerworks global site.
- View the various web service-related proposals in W3C.
- Jaxm can be obtained as part of Java XML pack (spring 2002) and Java Web Services developer pack ea2.
- IBM WebSphere Studio Application Developer is an easy-to-use integrated development environment for building, testing, and deploying web services.
- To obtain the complete Web Service toolkit, download IBM Web Services Development Kit.
- Find more references in the XML and web services area of developerworks.
Reprinted: http://www.ibm.com/developerworks/cn/xml/tips/x-jaxmsoap/