va mosa
va mosa

Reputation: 13

Create custom Header using Spring Integration

Need to hit a SOAP service whose request structure look as below

In spring integartion we can able to form the body part and hit the service and get the response .

<?xml version="1.0"?>

<soap:Envelope
xmlns:soap="http://www.w3.org/2003/05/soap-envelope/"
soap:encodingStyle="http://www.w3.org/2003/05/soap-encoding">

<soap:Header>
 <m:Trans xmlns:m="https://www.w3schools.com/transaction/"soap:mustUnderstand="1">234
 </m:Trans>
 <authheader>
   <username> uname</username>
   <password>password</password>
 </authheader>
</soap:Header>

<soap:Body xmlns:m="http://www.example.org/stock">
  <m:GetStockPriceResponse>
  <m:Price>34.5</m:Price>
</m:GetStockPriceResponse>
</soap:Body>

But how to form the header part along with body and send it in outbound gateway ?

Could someone help?

Upvotes: 0

Views: 300

Answers (1)

Artem Bilan
Artem Bilan

Reputation: 121272

Starting with version 5.0, the DefaultSoapHeaderMapper supports user-defined headers of type javax.xml.transform.Source and populates them as child nodes of the <soapenv:Header>:

Map<String, Object> headers = new HashMap<>();

String authXml =
     "<auth xmlns='http://test.auth.org'>"
           + "<username>user</username>"
           + "<password>pass</password>"
           + "</auth>";
headers.put("auth", new StringSource(authXml));
...
DefaultSoapHeaderMapper mapper = new DefaultSoapHeaderMapper();
mapper.setRequestHeaderNames("auth");

And in the end we have SOAP envelope as:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Header>
        <auth xmlns="http://test.auth.org">
            <username>user</username>
            <password>pass</password>
        </auth>
    </soapenv:Header>
    <soapenv:Body>
        ...
    </soapenv:Body>
</soapenv:Envelope>

If you can't use Spring Integration 5.0 yet, you can borrow its logic on the matter from the DefaultSoapHeaderMapper for custom extension of this class:

protected void populateUserDefinedHeader(String headerName, Object headerValue, SoapMessage target) {
    SoapHeader soapHeader = target.getSoapHeader();
    if (headerValue instanceof String) {
        QName qname = QNameUtils.parseQNameString(headerName);
        soapHeader.addAttribute(qname, (String) headerValue);
    }
    else if (headerValue instanceof Source) {
        Result result = soapHeader.getResult();
        try {
            this.transformerHelper.transform((Source) headerValue, result);
        }
        catch (TransformerException e) {
            throw new SoapHeaderException(
                    "Could not transform source [" + headerValue + "] to result [" + result + "]", e);
        }
    }
}

Upvotes: 1

Related Questions