How to modify headers in the SOAP response.
Below snippet will do the trick. In a nutshell, you need to:
- Add @SoapHeader annotation in the service method.
- Use Unmarshaller to map header xml elements to java object.
- Make necessary changes to this java object.
- Finally, use Marshaller to map java object back to xml, and set in response.
// Service class code
private static final String NAMESPACE_URI = "http://domain.com/context/../DummyRequest.xsd";
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "RequestPartInXml")
@ResponsePayload
public JAXBElement<ResponsePOJO> returnApiResponse(
@RequestPayload JAXBElement<RequestPojo> request,
@SoapHeader(value = "{http://domain.com/context/../DummyRequest.xsd}MessageHeader") SoapHeaderElement soapHeaders,
MessageContext messageContext) {
// handleSoap Headers
handleSoapHeaders(messageContext, soapHeaders);
...
...
}
// handling of headers
public static void handleSoapHeaders(MessageContext messageContext, SoapHeaderElement soapHeaders) {
try {
context = JAXBContext.newInstance(ObjectFactory.class);
MessageHeaderInfo requestSoapHeaders = getRequestHeaders(soapHeaders);
setCustomHeaders(requestSoapHeaders);
pushResponseHeaders(messageContext, requestSoapHeaders);
} catch (JAXBException e) {
e.printStackTrace();
}
}
// Use un-marshalling to map Xml to Java Object
private static MessageHeaderInfo getRequestHeaders(SoapHeaderElement soapHeaders) throws JAXBException {
Unmarshaller unmarshaller = context.createUnmarshaller();
JAXBElement<MessageHeaderPojo> headers = (JAXBElement<MessageHeaderPojo>) unmarshaller
.unmarshal(soapHeaders.getSource());
return headers.getValue();
}
private static void setCustomHeaders(MessageHeaderPojo requestSoapHeaders) {
MessageHeaderPojo mH = requestSoapHeaders;
mh.setOneObj(requestSoapHeaders.getOneObj()); // to return request Header Element as it is in the response
mh.setSecondObj(requestSoapHeaders.getSecondObj());
mh.setThirdObj(requestSoapHeaders.getThirdObj()); // to modify request Header Object and send in response
mh.getThirdObj().setnewParameter("customValue"); // newParameter is an attribute in ThirdObj Class
}
// Use marshalling to map Java back to Xml
private static void pushResponseHeaders(MessageContext messageContext, MessageHeaderPojo mh)
throws JAXBException {
ObjectFactory obja = new ObjectFactory();
JAXBElement<MessageHeaderPojo> modifiedHeaders = obja.createMessageHeader(info);
Marshaller marshaller = context.createMarshaller();
SaajSoapMessage soapResponses = (SaajSoapMessage) messageContext.getResponse();
SoapHeader resheader = soapResponses.getSoapHeader();
marshaller.marshal(modifiedHeaders, resheader.getResult());
}
If any issues are encountered, do drop the same in comments section.
I will be happy to help.
######### Happy Coding #########
Comments
Post a Comment