Thursday, February 01, 2007

Apache Axis namspace quirk in a SOAP response

When you use Apache Axis for your web services implementation , its a wise move but you got to remember its few one off situations, like this one that I'm going to explain.
Apache axis generates namespaces in every single element of the response , which can be very painful for the client if client is going parse and moreover its additional overhead in your SOAP response back to client, you are pushing more data over the wire where it can be avoided. sample looks something like this

<SOAP ENV..>
<SOAP Header..>
</SOAP Header..>
<SOAP body>
<ns1:elemenntname xsi:type="xsd:string"
xmlns:ns1="http://a.b.c/...." >
<ns2:elemenntname xsi:type="xsd:string"
xmlns:ns2="http://a.b.c/...." >

<ns3:elemenntname xsi:type="xsd:string"
xmlns:ns3="http://x.y.z/...." >

</SOAP body>
</SOAP Env...>


So above if you see , its unnecessary data getting duplicated in each element, where as ideally axis should be doing this internally by aggregating namespaces. So what you have to do is add following code in the your services code

org.apache.axis.utils.NSStack namespaceList = new org.apache.axis.utils.NSStack();
namespaceList .add("http://a.b.c./...", "ns1");
namespaceList .add("http://x.y.z./...", "ns2");
soapRespEnv.setNSMappings(namespaceList .cloneFrame());

Where as soapRespEnv is SOAP response envelope fetched from MessageContext. So what will above code do is, it will notify Axis engine to aggregate SOAP response namespaces in the SOAP envelope root. your response would look like below after above change



<SOAP ENV. xmlns:ns1="http://a.b.c/...." xmlns:ns2="http://x.y.z/....">
<SOAP Header..>
</SOAP Header..>
<SOAP body>
<ns1:elemenntname xsi:type="xsd:string">
<ns1:elemenntname xsi:type="xsd:string">

<ns2:elemenntname xsi:type="xsd:string">

</SOAP body>
</SOAP Env...>



benefitof above approach is

* Sheer data size reduction, that goes over the wire
* SOAP response looks like very clean.

No comments: