Tip: Use jaxm to send and receive soap messages-Java APIs automate many steps required to manually generate and send messages

Source: Internet
Author: User
Tags xslt

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:

  1. Create a soap connection
  2. Create a SOAP message
  3. Fill messages
  4. Send message
  5. 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 usedSOAPConnectionSend directly or indirectly by using the message delivery provider. In this example, the application is created by using the factorySOAPConnectionObject.

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, useMessageFactoryTo create the message itself. This message already containsenvelopeAndheader.SOAPPartIncludeenvelope, AndenvelopeContains 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 (suchscheduleElement ). Generally, you can useaddChildElement(elementnameButenvelope.createName()The method simplifies the creation of Elements Using namespace declarations for data or loads. Indeed, the schedule element is createdbodyElement SOAPElementObject. Then,bodyElementObjects can be assigned their own child elements.cal:newitemAdd 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.msgAnd 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 secondSOAPMessageAs a response. The destination must beEndpointObject, 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 returnedSOAPMessageSo far.

 

Back to Top

Response

ReturnedSOAPMessagereply-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 ApplicationTransformerObject. 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.outBut 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 messagesProviderConnectionObject insteadSOAPConnectionJaxm 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/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.