Issue
I am trying to write a SOAP client and one of its tasks is to unmarshall a SOAP response. But the problem is that whenever I try to unmarshal the response, I am getting null values only.
Here's a sample soap response
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<ns2:CreateOrderResponse xmlns:ns2="https://myns.com">
<ns2:OrderID>100100</ns2:OrderID>
</ns2:CreateOrderResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
and this is the POJO that the body of the soap message is supposed to be unmarshalled to
package per.me.soapclient.response
import jakarta.xml.bind.annotation.*;
import lombok.Getter;
@XmlRootElement(name = "CreateOrderResponse", namespace = "https://myns.com")
@XmlType(propOrder = {"orderID"})
@XmlAccessorType(XmlAccessType.FIELD)
@Getter
public class GetOrderResponse {
@XmlElement(name = "OrderID", namespace = "https://myns.com")
public Long orderID;
}
This is the unmarshalling logic
String soapXML = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
" <SOAP-ENV:Header/>\n" +
" <SOAP-ENV:Body>\n" +
" <ns2:CreateOrderResponse xmlns:ns2=\"https://myns.com\">\n" +
" <ns2:OrderID>100100</ns2:OrderID>\n" +
" </ns2:CreateOrderResponse>\n" +
" </SOAP-ENV:Body>\n" +
"</SOAP-ENV:Envelope>"
try {
final MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
final JAXBContext jaxbContext = JAXBContext.newInstance(CreateOrderResponse.class);
final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
try(ByteArrayInputStream bais = new ByteArrayInputStream(soapXML.getBytes(StandardCharsets.UTF_8))) {
final SOAPMessage soapMessage = messageFactory.createMessage(new MimeHeaders(), bais);
CreateOrderResponse response = unmarshaller.unmarshall(soapMessage.getSOAPBody(), CreateOrderResponse.class).getValue();
Assertions.assertEquals(100100L, response.getOrderID());
}
} catch (SOAPException | JAXBException | IOException e) {
throw new IllegalStateException(e);
}
The assertion fails with the following message
expected: <100100> but was: <null>
Expected :100100
Actual :null
Just in case, here's my package-info.java
@XmlSchema(namespace = "https://myns.com", elementFormDefault = XmlNsForm.QUALIFIED)
package per.me.soapclient.response;
import jakarta.xml.bind.annotation.XmlNsForm;
import jakarta.xml.bind.annotation.XmlSchema;
Can someone please tell me what I am doing wrong? I'm stuck and I can't really think of anything.
Solution
Very silly of me. The element to be passed to the unmarshaller is not the soap body but the first child element under the <SOAP-ENV:Body>
tag.
so I just needed to do something like
CreateOrderResponse response = unmarshaller.unmarshal(soapMessage.getSOAPBody().getChildElements().next(), CreateOrderResponse.class).getValue();
Answered By - thisisshantzz
Answer Checked By - Katrina (JavaFixing Volunteer)