|
Home
TOC Index |
|
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 fromhttp://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
SOAPConnectionobject via the methodSOAPConnection.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:
- One-way (asynchronous) messaging
- Routing of a message to more than one party
- Reliable messaging with features such as guaranteed delivery
A
SOAPMessageobject represents an XML document that is a SOAP message. ASOAPMessageobject always has a required SOAP part, and it may also have one or more attachment parts. The SOAP part must always have aSOAPEnvelopeobject, which must in turn always contain aSOAPBodyobject. TheSOAPEnvelopeobject may also contain aSOAPHeaderobject, to which one or more headers can be added.The
SOAPBodyobject 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
SOAPConnectionobject or aProviderConnectionobject.Getting a Point-to-Point Connection
A standalone client is limited to using a
SOAPConnectionobject, 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 aSOAPConnectionobject, the factory is aSOAPConnectionFactoryobject. A client obtains the default implementation forSOAPConnectionFactoryby calling the following line of code.SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();The client can use
factoryto create aSOAPConnectionobject.SOAPConnection con = factory.createConnection();Getting a Connection to the Messaging Provider
In order to use a messaging provider, an application must obtain a
ProviderConnectionobject, which is a connection to the messaging provider rather than to a specified recipient. There are two ways to get aProviderConnectionobject, the first being similar to the way a standalone client gets aSOAPConnectionobject. This way involves obtaining an instance of the default implementation forProviderConnectionFactory, which is then used to create the connection.ProviderConnectionFactory pcFactory = ProviderConnectionFactory.newInstance(); ProviderConnection pcCon = pcFactory.createConnection();The variable
pcConrepresents a connection to the default implementation of a JAXM messaging provider.The second way to create a
ProviderConnectionobject is to retrieve aProviderConnectionFactoryobject that is implemented to create connections to a specific messaging provider. The following code demonstrates getting such aProviderConnectionFactoryobject and using it to create a connection. The first two lines use the Java Naming and Directory Interface(JNDI) API to retrieve the appropriate
ProviderConnectionFactoryobject from the naming service where it has been registered with the name "CoffeeBreakProvider". When this logical name is passed as an argument, the methodlookupreturns theProviderConnectionFactoryobject to which the logical name was bound. The value returned is a JavaObject, which must be narrowed to aProviderConnectionFactoryobject 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
ProviderConnectioninstanceconrepresents 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,
MessageFactoryobjects can be obtained in two ways. The first way is to get an instance of the default implementation for theMessageFactoryclass. This instance can then be used to create a basicSOAPMessageobject.MessageFactory messageFactory = MessageFactory.newInstance(); SOAPMessage m = messageFactory.createMessage();All of the
SOAPMessageobjects thatmessageFactorycreates, includingmin 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
MessageFactoryobject, you use theProviderConnectionmethodcreateMessageFactoryand give it a profile. TheSOAPMessageobjects produced by the resultingMessageFactoryobject will support the specified profile. For example, in the following code fragment, in whichschemaURIis the URI of the schema for the desired profile,m2will support the messaging profile that is supplied tocreateMessageFactory.MessageFactory messageFactory2 = con.createMessageFactory(<schemaURI>); SOAPMessage m2 = messageFactory2.createMessage();Each of the new
SOAPMessageobjectsmandm2automatically contains the required elementsSOAPPart,SOAPEnvelope, andSOAPBody, plus the optional elementSOAPHeader(which is included for convenience). TheSOAPHeaderandSOAPBodyobjects 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
SOAPPartobject, to one or moreAttachmentPartobjects, or to both parts of a message.Populating the SOAP Part of a Message
As stated earlier, all messages have a
SOAPPartobject, which has aSOAPEnvelopeobject containing aSOAPHeaderobject and aSOAPBodyobject. One way to add content to the SOAP part of a message is to create aSOAPHeaderElementobject or aSOAPBodyElementobject and add an XML fragment that you build with the methodSOAPElement.addTextNode. The first three lines of the following code fragment access theSOAPBodyobjectbody, which is used to create a newSOAPBodyElementobject and add it tobody. The argument passed to thecreateNamemethod is aNameobject identifying theSOAPBodyElementbeing added. The last line adds the XML string passed to the methodaddTextNode.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
SOAPPartobject by passing it ajavax.xml.transform.Sourceobject, which may be aSAXSource,DOMSource, orStreamSourceobject. TheSourceobject contains content for the SOAP part of the message and also the information needed for it to act as source input. AStreamSourceobject will contain the content as an XML document; theSAXSourceorDOMSourceobject will contain content and instructions for transforming it into an XML document.The following code fragments illustrates adding content as a
DOMSourceobject. The first step is to get theSOAPPartobject from theSOAPMessageobject. Next the code uses methods from the JAXP API to build the XML document to be added. It uses aDocumentBuilderFactoryobject to get aDocumentBuilderobject. Then it parses the given file to produce the document that will be used to initialize a newDOMSourceobject. Finally, the code passes theDOMSourceobjectdomSourceto the methodSOAPPart.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
Messageobject 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 thejavax.activation.DataHandlerobjectdh. TheMessageobjectmcreates theAttachmentPartobjectattachPart, which is initialized with the data handler containing the URL for the image. Finally, the message addsattachPartto itself.URL url = new URL("http://foo.bar/img.jpg"); DataHandler dh = new DataHandler(url); AttachmentPart attachPart = m.createAttachmentPart(dh); m.addAttachmentPart(attachPart);A
SOAPMessageobject can also give content to anAttachmentPartobject by passing anObjectand its content type to the methodcreateAttachmentPart.AttachmentPart attachPart = m.createAttachmentPart("content-string", "text/plain"); m.addAttachmentPart(attachPart);A third alternative is to create an empty
AttachmentPartobject and then to pass theAttachmentPart.setContentmethod anObjectand its content type. In this code fragment, theObjectis aByteArrayInputStreaminitialized 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
SOAPMessageobject, you are ready to send it. A standalone client uses theSOAPConnectionmethodcallto send a message. This method sends the message and then blocks until it gets back a response. The arguments to the methodcallare the message being sent and aURLobject 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
ProviderConnectionmethodsendto 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);
|
Home
TOC Index |
|
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.