Title: SOLVED: Modify Message Body in Handler

There have been several posts asking how to change the body of a message (not the header) from within a handler. Here is a way to pull it off. It's a little strange, but it works.

    public void invoke(MessageContext msgContext) throws AxisFault {
        try {
            javax.xml.soap.SOAPMessage soapMessage = msgContext.getRequestMessage();
            String oldRequest = soapMessage.getSOAPPart().getEnvelope().toString();
           
            int index = oldRequest.indexOf("<processAttributesParam");
            index = oldRequest.indexOf(">",index);
            String newRequest = oldRequest.substring(0,index+1) +
                "<test_element>5</test_element>" +
                oldRequest.substring(index+1,oldRequest.length());
           
            ByteArrayInputStream istream = new ByteArrayInputStream(newRequest.getBytes());           
            Message msg = new Message(istream, false);
            msgContext.setRequestMessage(msg);

        }
        catch(Exception e) {
            e.printStackTrace();
            throw new AxisFault(e.getMessage());
        }
    }

What this code does is the following:

1) It retrieves the request message out of the MessageContext object.
2) It reads the String value of the SOAP message and stores it in a String (oldRequest)
3) It then searches for a place where I want to insert a new element into the SOAP body (test_element) setting the value of it to '5'. (I'll probably use style sheet transformations to change the message instead of String manipulation)

4) Finally, it creates a new Message with the String that holds the modified SOAP message, and then sets the MessageContext's requestMessage to this new object.

The new message will now be passed to any other handlers and the final web service at the end of the request flow. One thing to watch out for though: if you have any attachments on the incoming message, you need to save them and the re-attach them to the new message after you create it. Otherwise they will be lost (something my web service barked at).

I guess if you beat your head against the monitor long enough, a solution does finally come out.


Tripper McCarthy
[EMAIL PROTECTED]
625 The City Drive
Suite 190
Orange, CA 92868


Reply via email to