Adding SOAP header to response messages

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

Adding SOAP header to response messages

Pietro Romanazzi
Hello guys
 
I need to add a custom header to a response SOAP message.
The simple handler I wrote is:
 
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.SOAPFactory;
import org.apache.axiom.soap.SOAPHeader;
import org.apache.axiom.soap.SOAPHeaderBlock;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.handlers.AbstractHandler;
 
public class AddHeaderHandler extends AbstractHandler {   
    public AddHeaderHandler()  {       
    }   
    public InvocationResponse invoke(MessageContext ctx) {
        SOAPEnvelope env = ctx.getEnvelope();        
        System.out.println("Soap Envelope before header injection: "+env.toString());
        SOAPFactory factory = (SOAPFactory) env.getOMFactory();       
        OMNamespace ns = factory.createOMNamespace("<A href='http://my.org/axis2"'>http://my.org/axis2", "myns");
        SOAPHeader head = factory.createSOAPHeader(env);
        SOAPHeaderBlock header = head.addHeaderBlock("greetings", ns);
        header.setText("byebye");
        System.out.println("Soap Envelope after header injection"+env.toString());
        return InvocationResponse.CONTINUE;
    }   
}
 
 
This is a fragment of axis2.xml
 
<phaseOrder type="OutFlow">
    <!--      user can add his own phases to this area  -->
    <phase name="soapmonitorPhase"/>
    <phase name="OperationOutPhase">
    <handler name="greetings" class="AddHeaderHandler" />
    </phase>
    <!--system predefined phase-->
    <!--these phase will run irrespective of the service-->
    <phase name="RMPhase"/>
    <phase name="PolicyDetermination"/>
    <phase name="MessageOut">       
    </phase>
    <phase name="Security"/>
</phaseOrder>
 
in response I see a soap fault
 
<?xml version='1.0' encoding='utf-8'?><soapenv:Envelope xmlns:soapenv="<A href='http://schemas.xmlsoap.org/soap/envelope/"'>http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><soapenv:Fault><faultcode>soapenv:Server</faultcode><faultstring>SOAPEnvelope must contain a body element which is either first or second child element of the SOAPEnvelope.</faultstring><detail /></soapenv:Fault></soapenv:Body></soapenv:Envelope>
 
Debugging the code I see that the handler is started but, after the statement
SOAPHeader head = factory.createSOAPHeader(env);
If I watch the env variable I see
com.sun.jdi.InvocationException occurred invoking method (the toString I suppose).
 
It seems that the createSOAPHeader corrupts the env.
 
I tried to put the handler in the “MessageOut” phase but the problem is the same.
If I put the same handler in the “InFlow”, even if it doesn’t make any sense but just to try, it completes properly and the header is added prior the dispatching phase but obviously the response doesn’t contain the header.
 
Help, suggestions?
 
Thanks
 
Pietro
Reply | Threaded
Open this post in threaded view
|

Re: Adding SOAP header to response messages

Andreas Veithen-2
When Axis2 initializes the SOAPEnvelope for outgoing messages, it
already creates an empty SOAPHeader object. Therefore you should use
SOAPEnvelope#getHeader() instead of
SOAPFactory#createSOAPHeader(SOAPEnvelope).

Andreas

On Fri, Jan 18, 2013 at 10:03 AM, Pietro Romanazzi
<[hidden email]> wrote:

> Hello guys
>
> I need to add a custom header to a response SOAP message.
> The simple handler I wrote is:
>
> import org.apache.axiom.om.OMNamespace;
> import org.apache.axiom.soap.SOAPEnvelope;
> import org.apache.axiom.soap.SOAPFactory;
> import org.apache.axiom.soap.SOAPHeader;
> import org.apache.axiom.soap.SOAPHeaderBlock;
> import org.apache.axis2.context.MessageContext;
> import org.apache.axis2.handlers.AbstractHandler;
>
> public class AddHeaderHandler extends AbstractHandler {
>     public AddHeaderHandler()  {
>     }
>     public InvocationResponse invoke(MessageContext ctx) {
>         SOAPEnvelope env = ctx.getEnvelope();
>         System.out.println("Soap Envelope before header injection:
> "+env.toString());
>         SOAPFactory factory = (SOAPFactory) env.getOMFactory();
>         OMNamespace ns = factory.createOMNamespace("http://my.org/axis2",
> "myns");
>         SOAPHeader head = factory.createSOAPHeader(env);
>         SOAPHeaderBlock header = head.addHeaderBlock("greetings", ns);
>         header.setText("byebye");
>         System.out.println("Soap Envelope after header
> injection"+env.toString());
>         return InvocationResponse.CONTINUE;
>     }
> }
>
>
> This is a fragment of axis2.xml
>
> <phaseOrder type="OutFlow">
>     <!--      user can add his own phases to this area  -->
>     <phase name="soapmonitorPhase"/>
>     <phase name="OperationOutPhase">
>     <handler name="greetings" class="AddHeaderHandler" />
>     </phase>
>     <!--system predefined phase-->
>     <!--these phase will run irrespective of the service-->
>     <phase name="RMPhase"/>
>     <phase name="PolicyDetermination"/>
>     <phase name="MessageOut">
>     </phase>
>     <phase name="Security"/>
> </phaseOrder>
>
> in response I see a soap fault
>
> <?xml version='1.0' encoding='utf-8'?><soapenv:Envelope
> xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><soapenv:Fault><faultcode>soapenv:Server</faultcode><faultstring>SOAPEnvelope
> must contain a body element which is either first or second child element of
> the SOAPEnvelope.</faultstring><detail
> /></soapenv:Fault></soapenv:Body></soapenv:Envelope>
>
> Debugging the code I see that the handler is started but, after the
> statement
> SOAPHeader head = factory.createSOAPHeader(env);
> If I watch the env variable I see
> com.sun.jdi.InvocationException occurred invoking method (the toString I
> suppose).
>
> It seems that the createSOAPHeader corrupts the env.
>
> I tried to put the handler in the “MessageOut” phase but the problem is the
> same.
> If I put the same handler in the “InFlow”, even if it doesn’t make any sense
> but just to try, it completes properly and the header is added prior the
> dispatching phase but obviously the response doesn’t contain the header.
>
> Help, suggestions?
>
> Thanks
>
> Pietro

---------------------------------------------------------------------
To unsubscribe, e-mail: [hidden email]
For additional commands, e-mail: [hidden email]

Reply | Threaded
Open this post in threaded view
|

Re: Adding SOAP header to response messages

Pietro Romanazzi
Right!

Thank you Andreas

Regards,
Pietro

-----Messaggio originale-----
From: Andreas Veithen
Sent: Sunday, January 20, 2013 10:05 AM
To: java-user
Subject: Re: Adding SOAP header to response messages

When Axis2 initializes the SOAPEnvelope for outgoing messages, it
already creates an empty SOAPHeader object. Therefore you should use
SOAPEnvelope#getHeader() instead of
SOAPFactory#createSOAPHeader(SOAPEnvelope).

Andreas

On Fri, Jan 18, 2013 at 10:03 AM, Pietro Romanazzi
<[hidden email]> wrote:

> Hello guys
>
> I need to add a custom header to a response SOAP message.
> The simple handler I wrote is:
>
> import org.apache.axiom.om.OMNamespace;
> import org.apache.axiom.soap.SOAPEnvelope;
> import org.apache.axiom.soap.SOAPFactory;
> import org.apache.axiom.soap.SOAPHeader;
> import org.apache.axiom.soap.SOAPHeaderBlock;
> import org.apache.axis2.context.MessageContext;
> import org.apache.axis2.handlers.AbstractHandler;
>
> public class AddHeaderHandler extends AbstractHandler {
>     public AddHeaderHandler()  {
>     }
>     public InvocationResponse invoke(MessageContext ctx) {
>         SOAPEnvelope env = ctx.getEnvelope();
>         System.out.println("Soap Envelope before header injection:
> "+env.toString());
>         SOAPFactory factory = (SOAPFactory) env.getOMFactory();
>         OMNamespace ns = factory.createOMNamespace("http://my.org/axis2",
> "myns");
>         SOAPHeader head = factory.createSOAPHeader(env);
>         SOAPHeaderBlock header = head.addHeaderBlock("greetings", ns);
>         header.setText("byebye");
>         System.out.println("Soap Envelope after header
> injection"+env.toString());
>         return InvocationResponse.CONTINUE;
>     }
> }
>
>
> This is a fragment of axis2.xml
>
> <phaseOrder type="OutFlow">
>     <!--      user can add his own phases to this area  -->
>     <phase name="soapmonitorPhase"/>
>     <phase name="OperationOutPhase">
>     <handler name="greetings" class="AddHeaderHandler" />
>     </phase>
>     <!--system predefined phase-->
>     <!--these phase will run irrespective of the service-->
>     <phase name="RMPhase"/>
>     <phase name="PolicyDetermination"/>
>     <phase name="MessageOut">
>     </phase>
>     <phase name="Security"/>
> </phaseOrder>
>
> in response I see a soap fault
>
> <?xml version='1.0' encoding='utf-8'?><soapenv:Envelope
> xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><soapenv:Fault><faultcode>soapenv:Server</faultcode><faultstring>SOAPEnvelope
> must contain a body element which is either first or second child element
> of
> the SOAPEnvelope.</faultstring><detail
> /></soapenv:Fault></soapenv:Body></soapenv:Envelope>
>
> Debugging the code I see that the handler is started but, after the
> statement
> SOAPHeader head = factory.createSOAPHeader(env);
> If I watch the env variable I see
> com.sun.jdi.InvocationException occurred invoking method (the toString I
> suppose).
>
> It seems that the createSOAPHeader corrupts the env.
>
> I tried to put the handler in the “MessageOut” phase but the problem is
> the
> same.
> If I put the same handler in the “InFlow”, even if it doesn’t make any
> sense
> but just to try, it completes properly and the header is added prior the
> dispatching phase but obviously the response doesn’t contain the header.
>
> Help, suggestions?
>
> Thanks
>
> Pietro

---------------------------------------------------------------------
To unsubscribe, e-mail: [hidden email]
For additional commands, e-mail: [hidden email]


---------------------------------------------------------------------
To unsubscribe, e-mail: [hidden email]
For additional commands, e-mail: [hidden email]

Reply | Threaded
Open this post in threaded view
|

Re: Adding SOAP header to response messages

sanjoy de
This post has NOT been accepted by the mailing list yet.
I have a webservice and a standalone client. I want to add header to the soap response. Below the actual service implementation---

package com.tcs.ttg.service;

import java.io.StringReader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.jws.HandlerChain;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;

import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.engine.Handler.InvocationResponse;
import org.apache.xerces.parsers.SAXParser;
import org.json.JSONObject;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import com.tcs.ttg.dbconn.DBUtils;

public class SDAService {
        public String sendResponseOrAck(String str) throws Exception {
                System.out.println("--------------Entering into the service----" + str);

                MessageContext cMessageContext = MessageContext.getCurrentMessageContext();
                org.apache.axiom.soap.SOAPHeader header1 = cMessageContext.getEnvelope().getHeader();
                org.apache.axiom.soap.SOAPBody body = cMessageContext.getEnvelope().getBody();

                String xmlString = header1.toString();
                System.out.println("Header: " + xmlString+"\r\nBody: "+body.toString());
                Connection conn = null;
                Statement stmt = null;
                ResultSet rs = null;
                String sql = null;
                JSONObject asyncObject = null;
                boolean isSync = false;

                SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();
                SOAPConnection connection = factory.createConnection();  
                //Create a SOAPMessage
                MessageFactory messageFactory = MessageFactory.newInstance();
                SOAPMessage message = messageFactory.createMessage();
                SOAPPart  soapPart = message.getSOAPPart();
                SOAPEnvelope envelope = soapPart.getEnvelope();
                //SOAPHeader header = envelope.getHeader();
                SOAPHeader header = message.getSOAPHeader();
                Iterator iterator = null;

                try{
                        conn = DBUtils.getConnections();
                        stmt = conn.createStatement();
                        asyncObject = new JSONObject();
                        XMLReader xr = new SAXParser();
                        XMLParser xmlHandler = new XMLParser();
                        xr.setContentHandler(xmlHandler);
                        xr.parse(new InputSource(new StringReader(xmlString)));
                        List<String> aList = xmlHandler.parseInputXML();
                        Map<String, String> map = xmlHandler.parseInputXML1();


                        Iterator it = map.entrySet().iterator();

                        while (it.hasNext()) {
                                Map.Entry pairs = (Map.Entry)it.next();
                                if(pairs.getKey().equals("Class") || pairs.getKey().equals("Timestamp") || pairs.getKey().equals("Qualifier") || pairs.getKey().equals("Function") || pairs.getKey().equals("ClientId") || pairs.getKey().equals("CorrelationId") || pairs.getKey().equals("SourceIdentifier") || pairs.getKey().equals("DocumentStatus")){
                                        if (header == null)
                                                header = envelope.addHeader();
                                        SOAPHeaderElement he1 = header.addHeaderElement(envelope.createName(pairs.getKey().toString(), "ns1", "http://172.18.2.226:9090/SDAWebService"));
                                        he1.setValue(pairs.getValue().toString());
                                        he1.setMustUnderstand(true);
                                        message.saveChanges();

                                        iterator = message.getSOAPHeader().extractAllHeaderElements();  
                                        while(iterator.hasNext()){
                                                SOAPElement element = (SOAPElement) iterator.next();
                                                System.out.println("-----header value-------->"+element.getValue()+"<---header name--->"+element.getLocalName());
                                        }
                                }
                                if(pairs.getValue().equals("Synchronous")){
                                        isSync = true;
                                        System.out.println("===================Synchronous Response==================="+isSync);
                                        //Insert Req_Recv_TS, CorrelationID and Request_Dump into the Database tables
                                        //and when the response is back from the Handler then update Resp_Recv_TS and Response_Dump column

                                        sql = "";
                                }
                                else if(pairs.getValue().equals("Asynchronous")){
                                        isSync = false;
                                        //System.out.println("===================Asynchronous Response==================="+isSync);
                                }
                        }

                        if(isSync == false){
                                System.out.println("json obj:  "+asyncObject.toString());
                                //Audit DB call
                        }
                }
                catch(Exception e){
                        e.printStackTrace();
                }
                //System.out.println("===================envelope.toString()==================="+message.toString());
                return message.toString();

        }

}



And the Client to invoke the service is----


package com.tcs.ttg.client;

/*import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.ServiceClient;*/

import java.net.URL;
import java.util.Iterator;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.Name;
import javax.xml.soap.Node;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;


public class TestClient {

        public static void main(String[] args) {
                String serviceEndpoint = "http://172.18.2.226:9090/SDAWebService/services/SDAService";
                try{
                        SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();

                        SOAPConnection connection = factory.createConnection();  

                        //Create a SOAPMessage
                        MessageFactory messageFactory = MessageFactory.newInstance();
                        SOAPMessage message = messageFactory.createMessage();
                        SOAPPart  soapPart = message.getSOAPPart();
                        SOAPEnvelope envelope = soapPart.getEnvelope();
                        //SOAPHeader header = envelope.getHeader();
                        SOAPHeader header = message.getSOAPHeader();
                        if (header == null)
                header = envelope.addHeader();

                        SOAPHeaderElement he1 = header.addHeaderElement(envelope.createName("Class", "ns1", "http://172.18.2.226:9090/SDAWebService"));
                        SOAPHeaderElement he2 = header.addHeaderElement(envelope.createName("Timestamp", "ns1", "http://172.18.2.226:9090/SDAWebService"));
                        SOAPHeaderElement he3 = header.addHeaderElement(envelope.createName("Qualifier", "ns1", "http://172.18.2.226:9090/SDAWebService"));
                        SOAPHeaderElement he4 = header.addHeaderElement(envelope.createName("Function", "ns1", "http://172.18.2.226:9090/SDAWebService"));
                        SOAPHeaderElement he5 = header.addHeaderElement(envelope.createName("ClientId", "ns1", "http://172.18.2.226:9090/SDAWebService"));
                        SOAPHeaderElement he6 = header.addHeaderElement(envelope.createName("CorrelationId", "ns1", "http://172.18.2.226:9090/SDAWebService"));
                        SOAPHeaderElement he7 = header.addHeaderElement(envelope.createName("SenderId", "ns1", "http://172.18.2.226:9090/SDAWebService"));
                        SOAPHeaderElement he8 = header.addHeaderElement(envelope.createName("Method", "ns1", "http://172.18.2.226:9090/SDAWebService"));
                        SOAPHeaderElement he9 = header.addHeaderElement(envelope.createName("Value", "ns1", "http://172.18.2.226:9090/SDAWebService"));
                        SOAPHeaderElement he10 = header.addHeaderElement(envelope.createName("ResponseMode", "ns1", "http://172.18.2.226:9090/SDAWebService"));
                        SOAPHeaderElement he11 = header.addHeaderElement(envelope.createName("AutomationServiceName", "ns1", "http://172.18.2.226:9090/SDAWebService"));
                        SOAPHeaderElement he12 = header.addHeaderElement(envelope.createName("Endpoint", "ns1", "http://172.18.2.226:9090/SDAWebService"));
                        SOAPHeaderElement he13 = header.addHeaderElement(envelope.createName("Source", "ns1", "http://172.18.2.226:9090/SDAWebService"));
                        SOAPHeaderElement he14 = header.addHeaderElement(envelope.createName("SourceIdentifier", "ns1", "http://172.18.2.226:9090/SDAWebService"));
                        SOAPHeaderElement he15 = header.addHeaderElement(envelope.createName("DocumentStatus", "ns1", "http://172.18.2.226:9090/SDAWebService"));
                        SOAPHeaderElement he16 = header.addHeaderElement(envelope.createName("BodyFormat", "ns1", "http://172.18.2.226:9090/SDAWebService"));

                        he1.setValue("");
                        he2.setValue("1373363012261");
                        he3.setValue("Request");
                        he4.setValue("Submit");
                        he5.setValue("1001");
                        he6.setValue("137336301226113");
                        he7.setValue("");
                        he8.setValue("");
                        he9.setValue("");
                        he10.setValue("FALSE");
                        he11.setValue("AutomationService1");
                        he12.setValue("http://google.com");
                        he13.setValue("Incident");
                        he14.setValue("1236540");
                        he15.setValue("Open");
                        he16.setValue("json");

                        SOAPBody body = envelope.getBody();

                        SOAPElement bodyElement = body.addChildElement(envelope.createName("sendResponseOrAck", "ns1", "http://service.ttg.tcs.com/xsd"));
                        bodyElement.addChildElement("Product").addTextNode("Apple");
            bodyElement.addChildElement("Price").addTextNode("20");

            message.saveChanges();

                        // Create an endpint point which is either URL or String type
                        URL endpoint = new URL(serviceEndpoint);

                        //Send a SOAPMessage (request) and then wait for SOAPMessage (response)
                        SOAPMessage response = connection.call(message, endpoint);

                        SOAPHeader header2 = response.getSOAPHeader();
                        System.out.println("------"+header2.getValue());
                        TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            // Extract the content of the reply
            Source sourceContent = response.getSOAPPart().getContent();
            // Set the output for the transformation
            StreamResult result = new StreamResult(System.out);
            transformer.transform(sourceContent, result);
            System.out.println();


                        // Close the SOAPConnection
                        connection.close();
                }
                catch(Exception e){
                        e.printStackTrace();
                }

        }

        /*private void invokeService() {
        try {
            ServiceClient serviceClient = new ServiceClient();

            serviceClient.setTargetEPR(new EndpointReference("http://172.18.2.226:9090/SDAWebService/services/SDAService"));

            // invoking in only operation
            serviceClient.getOptions().setAction("urn:SampleInOnlyOperation");
            serviceClient.fireAndForget(getOMElement());

            // invoking in out operation
            serviceClient.getOptions().setAction("urn:SampleInOutOperation");
            OMElement response = serviceClient.sendReceive(getOMElement());

            System.out.println("Response ==> " + response.toString());

        } catch (AxisFault axisFault) {
            axisFault.printStackTrace();
        }
    }

    private OMElement getOMElement() {
        OMFactory omFactory = OMAbstractFactory.getOMFactory();
        OMNamespace omNamespace = omFactory.createOMNamespace("http://172.18.2.226:9090/SDAWebService", "ns1");
        OMElement omElement = omFactory.createOMElement("Request", omNamespace);
        omElement.setText("Hello service");
        return omElement;
    }

    public static void main(String[] args) {
         new TestClient().invokeService();
    }*/


}



Now my problem is the output is showing header is null and the output is---

<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Header/><soapenv:Body><ns:sendResponseOrAckResponse xmlns:ns="http://service.ttg.tcs.com/xsd"><ns:return>org.apache.axis2.saaj.SOAPMessageImpl@18d7ace</ns:return></ns:sendResponseOrAckResponse></soapenv:Body></soapenv:Envelope>


See the bold section, it is showing that the header is null. The entire response is inside the body tag.
How to solve the problem so that the header comes under header and body comes under body section?

Please help.
Thanks in advance.