The JavaTM Web Services Tutorial
Home
TOC
Index
PREV TOP NEXT
Divider

JAXM

The Java API for XML Messaging (JAXM) provides a standard way to send XML documents over the Internet from the Java platform. It is based on the SOAP 1.1 and SOAP with Attachments specifications, which define a basic framework for exchanging XML messages. JAXM can be extended to work with higher level messaging protocols, such as the one defined in the ebXML (electronic business XML) Message Service Specification, by adding the protocol's functionality on top of SOAP.


Note: The ebXML Message Service Specification is available from http://www.oasis-open.org/committees/ebxml-msg/. Among other things, it provides a more secure means of sending business messages over the Internet than the SOAP specifications do.

Typically, a business uses a messaging provider service, which does the behind-the-scenes work required to transport and route messages. When a messaging provider is used, all JAXM messages go through it, so when a business sends a message, the message first goes to the sender's messaging provider, then to the recipient's messaging provider, and finally to the intended recipient. It is also possible to route a message to go to intermediate recipients before it goes to the ultimate destination.

Because messages go through it, a messaging provider can take care of housekeeping details like assigning message identifiers, storing messages, and keeping track of whether a message has been delivered before. A messaging provider can also try resending a message that did not reach its destination on the first attempt at delivery. The beauty of a messaging provider is that the client using JAXM technology ("JAXM client") is totally unaware of what the provider is doing in the background. The JAXM client simply makes Java method calls, and the messaging provider in conjunction with the messaging infrastructure makes everything happen behind the scenes.

Though in the typical scenario a business uses a messaging provider, it is also possible to do JAXM messaging without using a messaging provider. In this case, the JAXM client (called a standalone client) is limited to sending point-to-point messages directly to a Web service that is implemented for request-response messaging. Request-response messaging is synchronous, meaning that a request is sent and its response is received in the same operation. A request-response message is sent over a SOAPConnection object via the method SOAPConnection.call, which sends the message and blocks until it receives a response. A standalone client can operate only in a client role, that is, it can only send requests and receive their responses. In contrast, a JAXM client that uses a messaging provider may act in either the client or server (service) role. In the client role, it can send requests; in the server role, it can receive requests, process them, and send responses.

Though it is not required, JAXM messaging usually takes place within a container, generally a servlet or a J2EE container. A Web service that uses a messaging provider and is deployed in a container has the capability of doing one-way messaging, meaning that it can receive a request as a one-way message and can return a response some time later as another one-way message.

Because of the features that a messaging provider can supply, JAXM can sometimes be a better choice for SOAP messaging than JAX-RPC. The following list includes features that JAXM can provide and that RPC, including JAX-RPC, does not generally provide:

A SOAPMessage object represents an XML document that is a SOAP message. A SOAPMessage object always has a required SOAP part, and it may also have one or more attachment parts. The SOAP part must always have a SOAPEnvelope object, which must in turn always contain a SOAPBody object. The SOAPEnvelope object may also contain a SOAPHeader object, to which one or more headers can be added.

The SOAPBody object can hold XML fragments as the content of the message being sent. If you want to send content that is not in XML format or that is an entire XML document, your message will need to contain an attachment part in addition to the SOAP part. There is no limitation on the content in the attachment part, so it can include images or any other kind of content, including XML fragments and documents.

Getting a Connection

The first thing a JAXM client needs to do is get a connection, either a SOAPConnection object or a ProviderConnection object.

Getting a Point-to-Point Connection

A standalone client is limited to using a SOAPConnection object, which is a point-to-point connection that goes directly from the sender to the recipient. All JAXM connections are created by a connection factory. In the case of a SOAPConnection object, the factory is a SOAPConnectionFactory object. A client obtains the default implementation for SOAPConnectionFactory by calling the following line of code.

SOAPConnectionFactory factory =
        SOAPConnectionFactory.newInstance();
 

The client can use factory to create a SOAPConnection object.

SOAPConnection con = factory.createConnection();
 

Getting a Connection to the Messaging Provider

In order to use a messaging provider, an application must obtain a ProviderConnection object, which is a connection to the messaging provider rather than to a specified recipient. There are two ways to get a ProviderConnection object, the first being similar to the way a standalone client gets a SOAPConnection object. This way involves obtaining an instance of the default implementation for ProviderConnectionFactory, which is then used to create the connection.

ProviderConnectionFactory pcFactory =
      ProviderConnectionFactory.newInstance();
ProviderConnection pcCon = pcFactory.createConnection();
 

The variable pcCon represents a connection to the default implementation of a JAXM messaging provider.

The second way to create a ProviderConnection object is to retrieve a ProviderConnectionFactory object that is implemented to create connections to a specific messaging provider. The following code demonstrates getting such a ProviderConnectionFactory object and using it to create a connection. The first two lines use the Java Naming and Directory Interface (JNDI) API to retrieve the appropriate ProviderConnectionFactory object from the naming service where it has been registered with the name "CoffeeBreakProvider". When this logical name is passed as an argument, the method lookup returns the ProviderConnectionFactory object to which the logical name was bound. The value returned is a Java Object, which must be narrowed to a ProviderConnectionFactory object so that it can be used to create a connection. The third line uses a JAXM method to actually get the connection.

Context ctx = getInitialContext();
ProviderConnectionFactory pcFactory =  
(ProviderConnectionFactory)ctx.lookup("CoffeeBreakProvider");
 
ProviderConnection con = pcFactory.createConnection();
 

The ProviderConnection instance con represents a connection to The Coffee Break's messaging provider.

Creating a Message

As is true with connections, messages are created by a factory. And similar to the case with connection factories, MessageFactory objects can be obtained in two ways. The first way is to get an instance of the default implementation for the MessageFactory class. This instance can then be used to create a basic SOAPMessage object.

MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage m = messageFactory.createMessage();
 

All of the SOAPMessage objects that messageFactory creates, including m in the previous line of code, will be basic SOAP messages. This means that they will have no pre-defined headers.

Part of the flexibility of the JAXM API is that it allows a specific usage of a SOAP header. For example, protocols such as ebXML can be built on top of SOAP messaging to provide the implementation of additional headers, thus enabling additional functionality. This usage of SOAP by a given standards group or industry is called a profile. (See the JAXM tutorial section Profiles for more information on profiles.)

In the second way to create a MessageFactory object, you use the ProviderConnection method createMessageFactory and give it a profile. The SOAPMessage objects produced by the resulting MessageFactory object will support the specified profile. For example, in the following code fragment, in which schemaURI is the URI of the schema for the desired profile, m2 will support the messaging profile that is supplied to createMessageFactory.

MessageFactory messageFactory2 =
          con.createMessageFactory(<schemaURI>);
SOAPMessage m2 = messageFactory2.createMessage();
 

Each of the new SOAPMessage objects m and m2 automatically contains the required elements SOAPPart, SOAPEnvelope, and SOAPBody, plus the optional element SOAPHeader (which is included for convenience). The SOAPHeader and SOAPBody objects are initially empty, and the following sections will illustrate some of the typical ways to add content.

Populating a Message

Content can be added to the SOAPPart object, to one or more AttachmentPart objects, or to both parts of a message.

Populating the SOAP Part of a Message

As stated earlier, all messages have a SOAPPart object, which has a SOAPEnvelope object containing a SOAPHeader object and a SOAPBody object. One way to add content to the SOAP part of a message is to create a SOAPHeaderElement object or a SOAPBodyElement object and add an XML fragment that you build with the method SOAPElement.addTextNode. The first three lines of the following code fragment access the SOAPBody object body, which is used to create a new SOAPBodyElement object and add it to body. The argument passed to the createName method is a Name object identifying the SOAPBodyElement being added. The last line adds the XML string passed to the method addTextNode.

SOAPPart sp = m.getSOAPPart();
SOAPEnvelope envelope = sp.getSOAPEnvelope();
SOAPBody body = envelope.getSOAPBody();
SOAPBodyElement bodyElement = body.addBodyElement(
        envelope.createName("text", "hotitems",
        "http://hotitems.com/products/gizmo");
bodyElement.addTextNode("some-xml-text");
 

Another way is to add content to the SOAPPart object by passing it a javax.xml.transform.Source object, which may be a SAXSource, DOMSource, or StreamSource object. The Source object contains content for the SOAP part of the message and also the information needed for it to act as source input. A StreamSource object will contain the content as an XML document; the SAXSource or DOMSource object will contain content and instructions for transforming it into an XML document.

The following code fragments illustrates adding content as a DOMSource object. The first step is to get the SOAPPart object from the SOAPMessage object. Next the code uses methods from the JAXP API to build the XML document to be added. It uses a DocumentBuilderFactory object to get a DocumentBuilder object. Then it parses the given file to produce the document that will be used to initialize a new DOMSource object. Finally, the code passes the DOMSource object domSource to the method SOAPPart.setContent.

SOAPPart soapPart = message.getSOAPPart();
 
DocumentBuilderFactory dbf=
      DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("file:///foo.bar/soap.xml");
DOMSource domSource = new DOMSource(doc);
 
soapPart.setContent(domSource);
 

Populating the Attachment Part of a Message

A Message object may have no attachment parts, but if it is to contain anything that is not in XML format, that content must be contained in an attachment part. There may be any number of attachment parts, and they may contain anything from plain text to image files. In the following code fragment, the content is an image in a JPEG file, whose URL is used to initialize the javax.activation.DataHandler object dh. The Message object m creates the AttachmentPart object attachPart, which is initialized with the data handler containing the URL for the image. Finally, the message adds attachPart to itself.

URL url = new URL("http://foo.bar/img.jpg");
DataHandler dh = new DataHandler(url);
AttachmentPart attachPart = m.createAttachmentPart(dh);
m.addAttachmentPart(attachPart);
 

A SOAPMessage object can also give content to an AttachmentPart object by passing an Object and its content type to the method createAttachmentPart.

AttachmentPart attachPart = 
  m.createAttachmentPart("content-string", "text/plain");
m.addAttachmentPart(attachPart);
 

A third alternative is to create an empty AttachmentPart object and then to pass the AttachmentPart.setContent method an Object and its content type. In this code fragment, the Object is a ByteArrayInputStream initialized with a jpeg image.

AttachmentPart ap = m.createAttachmentPart();
byte[] jpegData =  ...;
ap.setContent(new ByteArrayInputStream(jpegData),
                "image/jpeg");
m.addAttachmentPart(ap);
 

Sending a Message

Once you have populated a SOAPMessage object, you are ready to send it. A standalone client uses the SOAPConnection method call to send a message. This method sends the message and then blocks until it gets back a response. The arguments to the method call are the message being sent and a URL object that contains the URL specifying the endpoint of the receiver. .

SOAPMessage response = 
        soapConnection.call(message, endpoint);
 

An application that is using a messaging provider uses the ProviderConnection method send to send a message. This method sends the message asynchronously, meaning that it sends the message and returns immediately. The response, if any, will be sent as a separate operation at a later time. Note that this method takes only one parameter, the message being sent. The messaging provider will use header information to determine the destination.

providerConnection.send(message);
 
Divider
Home
TOC
Index
PREV TOP NEXT
Divider

This tutorial contains information on the 1.0 version of the Java Web Services Developer Pack.

All of the material in The Java Web Services Tutorial is copyright-protected and may not be published in other works without express written permission from Sun Microsystems.