How can I work with the SOAP message inside Apache Axis2?
- By Eran Chinthaka
- 30 Jul, 2007
- Reads: 14488
Every message within the Axis2 engine is wrapped inside a MessageContext object. When a SOAP message arrives into the system or is prepared to be sent out, we create an AXIOM object model of the SOAP message.
(Please read the AXIOM article series for more information on AXIOM). This AXIOM model is then included inside the message context object. Let's see how to access this SOAP message inside Axis2.
MessageContext messageContext; // if you are within a handler, reference to the message context
object will be passed to you through Handler.invoke(MessageContext) method.
SOAPEnvelope soapEnvelope = messageContext.getEnvelope();
Now we have access to the AXIOM model of the SOAP message. The AXIOM SOAP API provides convenient methods to navigate inside the SOAP message. The SOAPEnvelope.getBody() and SOAPEnvelope.getHeader() methods give you access to the SOAP body and the SOAP header of the message respectively. (For more information on SOAP API of AXIOM, refer to the Axiom article.) Sometimes you might also need to add a new header or new XML element to the message, especially if you are writing a handler. How do we do this? You use the AXIOM API to create these XML elements.
1. OMFactory omFactory = soapEnvelope.getOMFactory();
2. OMElement newElement = factory.createOMElement("FooElement", null);
All the OMElements should be created using a factory (as shown in the first line). The reason is that AXIOM has a couple of different implementations. The basic implementation is based on a linked list object model. The other model that is used when WS-Security is enabled is called DOOM. DOOM implements DOM API on top of AXIOM API, providing DOM capabilities on AXIOM. Since these implementations can be switched within the Axis2 engine, transparent to the user, we store the factory in which the OMElements are created, within them.
Since we have the choice of two factories to use, we need to know which one to use when we are trying to add a new element to the existing SOAP message. The easiest way is to ask for the factory from the SOAP envelope, by which it was created. All the OMElements have a pointer to the factory they are created, within them. If you do not do this, you may encounter exceptions when your modified message is traversing through the Axis2 engine.
Then you need to create an OMElement as usual using OM API (line 2). Then add that as a child to the SOAP body (line 3). If you want to add an element to the SOAP header, the easiest method is to use the following method inside the SOAP header element. This helper method will take care of getting the proper factory, creating the OMElement and adding that to the SOAP envelope.
SOAPHeader.addHeaderBlock(String localName, OMNamespace ns)
Applies ToAxis2/Java 1.0 or later 2