Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

A while back I've shown an example MTOM/XOP enabled web service using DataHandler. Although MTOM is great for optimising the output of a web service, sometimes it's just better to compress these results before sending them.

This is a small change to the original service I've shown. It takes the data to be returned and compresses it into a ZIP stream, which is then returned as a ZIP file attachment.
public void getData(
@WebParam(mode = WebParam.Mode.IN, name = "dataId")
String dataId,
@WebParam(mode = WebParam.Mode.OUT, name = "data")
Holder<DataHandler> data
) {
String returnData = "Some data with ID:" + dataId;
ByteArrayOutputStream ops = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(ops);
try {
zos.putNextEntry(new ZipEntry("mydata.txt"));
// write data to zip
OutputStreamWriter osw = new OutputStreamWriter(zos);
osw.write(returnData, 0, returnData.length());
// end write data to zip
DataHandler dh = new DataHandler(ops.toByteArray(), "application/zip");
data.value = dh;
catch (Exception e) {
// ignore for example purposes

On line 14 I set compression level to 2, which is quite low but in my limited testing it still gave me a 14:1 compression ratio (on XML data). Having too high a compression level is not worth it in my opinion as that would introduce too much CPU overhead for compression and decompression later.

Something to note is that on line 17 I create a ZIP file entry called mydata.txt, this is the name of the file inside the ZIP that contains the actual data we have compressed. In order to access the data, whatever is calling the web service will have to decompress it.

On lines 19-23 Is where I actually write data to the ZIP file. In this case I am using a OutputStreamWriter to write data to the ZipOutputStream, however any stream could be used here depending on what kind of data you are returning. For example if you are returning marshalled results of your JAXB tree, you can marshall directly to the ZipOutputStream!

This may seem like an awful lot of work so if you are running WebLogic 12.2, you can Enable GZIP Compression for Web Applications instead. This is a transport layer compression so your web service is not aware that it's data is compressed over the network.


Did you like this post or found it useful? Considering supporting this Blog to keep its web servers running, any amount helps! Thanks!
Have comments or feedback on what I wrote? Please share them below!
comments powered by Disqus
Other posts you may like...