|
Sendingattachmentswithsoap.gif (9.9 K) |
|
Clip_image001.gif (9.2 K) |
|
Clip_image003.gif (16.2 K) |
|
Clip_image005.gifs (76.4 k) |
|
Clip_image007.gifs (49.1 K) |
|
Switch to slide Mode
Sending attachments with soap
Soap applications often have to deal with more than just simple messages. the payload for a SOAP message can often include a word processing or PDF document, image, or other binary file. this article explains how to use the message transmission optimization Mechanic (MTOM) to send and receive these messages.
Prerequisites
This article uses the wso2 Web Services Application Server (wsas .) it is recommended that you download and install wso2 wsas 2.0. the article uses the servlet edition installed on Apache Tomcat. any application server can be used with the servlet version, just follow the installation instructions ctions encoded with wso2 wsas. you don't have to use an application server at all, as wso2 wsas works great in a standalone format. wso2 wsas requires Java 1.4 or 1.5 but there are no other prerequisites for it. of course web services and soap especially is used, so familiarity with that will help.
When XML is not enough: binary data
There are endless ways to send data over the network. there are numerous protocols and data formats. standardization around soap has taken away a lot of the guesswork in sending data between systems. soap standardizes the Protocol (HTTP) and the data format (XML .)
One of the main criticisms of soap is its use of XML. XML is text based. this not only makes for large messages, but makes it incompatible with binary data. for example, let's say your message needs to include an image. this poses a problem when your message format is text.
Combining binary data with soap
OK, so you need to send binary data between applications. You 'd like to use soap, but it's limited to text. So shocould you just give up on soap all together? Of course not, There are too when advantages to soap. you just need a way to combine it with binary data. you see web pages do this all the time; it can't be that hard, right? Let's explain e some solutions to this problem.
Naive approaches
One way you might try is to simply dump the binary into a text node. It might look something like Listing 1.
Listing 1. XML with binary data: First try
<? XML version = "1.0" encoding = "UTF-8"?>
<Message>
<DATA> <! -- Binary data goes here --> </data>
</Message>
Remember that characters are also bytes, just like binary data. an XML parser, whether it's a Dom, sax, or Stax parser, must use the character set encoding of the document to interpret all the bytes in the document as characters. so our binary data cocould easily have characters that correspond to reserved xml characters, like <or> or &. any such byte sequence in text node will cause the parser on the other side to break. so this approach will not work.
But wait, maybe there's a way to fix this approach. What about using a CDATA block? That will tell the parser to ignore the characters inside the block. This modified approach might look like Listing 2.
Listing 2. XML with binary: Using CDATA
<? XML version = "1.0" encoding = "UTF-8"?>
<Message>
<DATA> <! [CDATA [binary data goes here]> </data>
</Message>
Now if we have bytes that wocould be interpreted as a> (for example,) They will be ignored. however, the parser has to figure out where the CDATA section ends. it does this by looking for the byte sequence corresponding to the characters]>. it might seem unlikely, but our binary data cocould have just such a byte sequence in the middle of it. that wowould cause any parser to think that the CDATA section had ended and the subsequent characters wocould be interpreted just like in our first attempt. so that's not going to work either. we need a way to make sure those bytes aren't interpreted at all.
Base 64 encoding: works but bloated
There is a solution to this variant of our problem. one common way to do this is to use base 64 encoding. this technique has been around (as a standard) since the 80's. it involves using a 64 character "alphabet" consisting of the lower case characters, a-Z, the upper case characters, A-Z, the numbers 0-9, and the + and/symbols. every byte gets mapped to these characters, so there's no way for any byte to get misinterpreted as anything that wocould choke an XML parser.
So there, problem solved, right? Yes,... It's a rather inefficient solution. base 64 encoded binary winds up being, on average, 37% larger (number of bytes) than the raw, non-encoded binary data. in addition, the parser on the other side needs to know about the encoding so that it can decode the payload. one cocould imagine that if Base 64 encoding was part of the soap standard, then there wocould be some standard way to indicate this SOAP message processors. this is not the case, though. it may be a solution, but it is both inefficient and non-standard. we need something that is both more efficient and standardized.
Soap with attachments: works but flawed design
One solution to the problem is to use what is known as soap with attachments. the idea here is to just put the binary data outside the SOAP message completely. figure 1 provides a nice visualization of this.
Figure 1. Soap with attachments
This is very similar to how binary files can be attached to emails. the SOAP message contains a reference to the binary file that is attached to the message. this is both more efficient and standardized, but it has some flaws in its design. the binary attachment is not part of the SOAP message at all. it's similar in a lot of ways to just passing a URI for the binary data and leaving it up to the message processor to retrieve the actual binary data. it presents some real problems for things like WS-Security. still, this is what was used for a while, until a better solution was proposed: MTOM.
MTOM: Best of both worlds
MTOM stands for SOAP message transmission optimization mechanic. It combines the efficiency of soap with attachments, but it does so without having to break the binary data outside of the SOAP message. How can this be? The key is a technology called XML-binary Optimized Packaging or xop.
Xop explained
Xop allows binary data to be encoded as part of the XML infoset. in fact the XML infoset becomes a superset of the traditional infoset known as the xop infoset. it allows for the binary data to be stored outside of the XML document, just like in soap with attachments. it uses a special xop: Include element to tell the processor to replace the contents with the referenced binary data, thus encapsulating the logic of discrete storage and retrieval of the binary data. this logic becomes inherent to the XML parser, and allows the soap parser to treat the binary data as part of the XML document, with no special retrieval logic. similarly it allows for a SOAP server to create a SOAP message in a uniform way, no special logic for breaking out that binary data from the SOAP message.
MTOM in wso2 wsas
We 've talked a lot about the need for MTOM and how it shoshould work in theory. it doesn' t do us a lot of good without a real implementation. luckily there's an easy way to get a great MTOM implementation, just use wso2 wsas. wso2 wsas is built on top of tried and true technologies, including Apache axis2. axis2 gives wso2 wsas its MTOM implementation. let's take a look at how to tap into the power of wsas/axis2's MTOM implementation.
Sending an MTOM message from a Web service with the Axiom API
MTOM support on axis2 builds on the same classes used throughout axis2. it uses axis2's Object Model (OM ). axis2 supports both Base 64 encoding and MTOM, and makes it relatively simple to switch between them. why? Well for very small files, it can be more efficient to use base 64 encoding.
To achieve this seamless switching between optimized and non-optimized transport, axis2 treats binary data as an XML text node. the only difference is that you need to pass in a javax. activation. datahandler for accessing the data, as shown in listing 3.
Listing 3. Adding binary data with the Axiom API
Omfactory messagefactory = omdomainactfactory. getomfactory ();
Omnamespace NS = messagefactory. createomnamespace ("urn: foo", "foo ");
Omelement binaryelement = messagefactory. createomelement ("payload", NS );
Filedatasource src = new filedatasource ("Temp. dat ");
Datahandler handler = new datahandler (SRC );
Omtext textnode = messagefactory. createomtext (handler, true );
Binaryelement. addchild (textnode );
In the example in listing 3, a javax. activation. filedatasource is used to provide the datahandler with access to the binary data. you can use any class that implements the javax. activation. datasource interface. for example, when working with images, the org. apache. axis2.attachments. imagedatasource can be used. it implements the datasource interface and can be more convenient when working with images.
So how does axis2, and thus wso2 wsas, know to use MTOM to optimize the binary data? That is actually what axis2 will do by default. You can manually override this by adding just one line of code, as shown in Listing 4.
Listing 4. Turning off MTOM
Textnode. setoptimize (false );
That single line of code will tell axis2 to not optimize, I. e. don't use MTOM. thus axis2 will use Base 64 encoding of the binary data, and it really will be a text node. otherwise, MTOM will kick in, and an xop include will be used to optimize the transport of the binary data within the SOAP message.
Enabling MTOM on the server
Of course to get all this wonderful, automatically optimized behavior, you do need to enable MTOM. You can do this through your axis2.xml file very easily, as shown in listing 5.
Listing 5. Enabling MTOM in axis. xml
<Parameter name = "enablemtom"> true </parameter>
It can't get anymore painless than that, right? This is a global setting, and is the default setting on wso2 wsas. you can actually enable MTOM at four different levels: global, Service Group, service, and operation. you use the same semantics for each level. you can use the management console to manage MTOM at each of these levels. for example of this Take A Look At Figure 2.
Figure 2. Managing MTOM at the service group level
Here we see MTOM being managed at the service group level. each service in the Group can also be individually managed, as shown in figure 3.
Figure 3. Managing MTOM at the service level
Of course each service can have one or more operations. wsas lets you manage MTOM at that level too, as shown in figure 4.
Figure 4.
Notice that at each level, MTOM has three possible values: True, false, and optional. if the property is set to true, then the service will send an optimized message when necessary, I. e. when binary data is supported ded. if the value is set to false, then optimization will never be used, and base 64 encoding will be used for any binary data. if it is set to optional, then wsas will optimize if and only if the request came in was optimized. the type of request will indicate to wsas if it shocould use MTOM or not.
Why do we need this kind of flexibility? As mentioned earlier, it is often advantageous to use base 64 encoding on small files. thus you cocould decide that certain operations shocould use MTOM and others shocould not. or you cocould make it optional on an operation, programmatically do a check for the size of the data being sent, and then choose to override the default MTOM if the file is small. then you're sending MTOM. let's take a look at how easy wsas makes it to send an MTOM message from a Web service client.
Creating a soap client that sends MTOM messages
Sending a MTOM message from a client is just as easy as sending an MTOM message from a Web Service. axis2 provides several convenient APIs. An example is shown in Listing 6.
Listing 6. client code for sending MTOM message
Serviceclient wsclient = new serviceclient ();
Options clientoptions = new options ();
Clientoptions. setto (New endpointreference ("http: // some/service "));
Clientoptions. setaction ("foo ");
Clientoptions. setproperty (constants. configuration. enable_mtom, constants. value_true );
Wsclient. setoptions (clientoptions );
As you can see in Listing 6, the key thing to do is to enable MTOM in options for the Web service client. once you do that, then axis2 will optimize any binary data you send to the Web service using MTOM automatically. we 've seen how to send MTOM messages from a Web Service and to a web service, now let's look at how to work with data that has been sent using MTOM.
Handling an MTOM message in a Web Service
Now let's assume you have a web service that accepts binary data as part of a SOAP message from a client. if your web service is running on wsas, you don't need to do anything special to be able to handle optimized binary data from your clients. your clients can send soap messages that use MTOM or base 64 encoding. it's all seamless with wsas. listing 7 shows an example of optimized ing optimized data.
Listing 7. Web Service Processing ing optimized soap
Omelement dataelement; // optimized Element
Omtext datanode = (omtext) dataelement. getfirstomchild ();
Datahandler handler = (datahandler) datanode. getdatahandler ();
Inputstream stream = handler. getdatasource (). getinputstream ();
// Read from the stream, proces data, save to file or database, etc.
As we saw earlier, the Axiom API treats the binary data as a text node. this allows a single API for dealing with optimized and non-optimized (Base 64 encoded) data. you simply access the datahandler associated to the text node (that contains the binary data) and use that to obtain an inputstream. once you have the inputstream, you can read all the bytes and process them however you need. wsas makes it easy to handle soap messages with optimized binary data payloads. let's take a look at how easy it is to work with MTOM on clients.
Handling an MTOM message in a client
There's no magic to handling an MTOM web service response. we 've ve already seen how to setup the request. in Figure 8 you see how to deal with a response that contains binary data optimized with MTOM.
Serviceclient wsclient = new serviceclient ();
Options clientoptions = new options ();
Clientoptions. setto (New endpointreference ("http: // some/service "));
Clientoptions. setaction ("foo ");
Clientoptions. setproperty (constants. configuration. enable_mtom, constants. value_true );
Wsclient. setoptions (clientoptions );
Omelement payload;
Omelement response = wsclient. sendreceive (payload );
Omelement dataelement = response. getfirstelement ();
Omtext binnode = (omtext) dataelement. getfirstomchild ();
Datahandler datahandler2 = (datahandler) binnode. getdatahandler ();
Inputstream stream = datahandler. getinputstream ();
Again the key here is using the Axiom API. it lets us treat the binary data as a text node, and then use the datahandler to get an inputstream to the data. again, once you have the inputstream, You can process the data however you need.
Summary
We 've seen how MTOM provides the perfect combination of soap standardization and efficiency for transporting binary data within a Web Service Message. we 've seen how wso2 wsas implements the MTOM specification using axis2. we 've taken a look at how to setup both web service servers and clients to both send and receive MTOM optimized messages. now we have everything we need for adding binary data to our web services using wso2 wsas.
Resources
- You're going to want to download wso2 wsas.
- Read about the latest features in wso2 wsas 2.0.
- Learn from and interact with the wso2 community on the wsas wiki.
- Learn about exposing your services as Web services easily with axis2.
- Learn how axis2 can enable your SOA designs in the developerworks Article SOA with axis2.
- Learn all about axis interoperability with other Web Service implementations in this entry in the TSS interoperability blog.
- Dive into the Axiom API in the developerworks article get the most out of XML processing with axiom.
- Read all about xop and MTOM in this blog entry by Mark nottheim.
- Interoperability is the name of the game when it comes to Web service, so learn about using MTOM with. net in the article sending files in chunks with MTOM Web Services and. NET 2.0.
About the author
Michael Galpin is an existing ECT at eBay in San Jose, CA. he's been developing software since 1998, and holds a degree in mathematics from the California Institute of Technology.