We're using Apache CXF with Dropwizard-JAXWS to interact with a SOAP service. We want to validate responses on the client level.
We've tried this:
((BindingProvider)port).getRequestContext().put("schema-validation-enabled", "true");
from http://cxf.apache.org/faq.html when constructing the client, with no luck.
The closest we've gotten is writing an interceptor for the client and adding the following to the message
public class ClientResponseSchemaValidatingInterceptor extends AbstractSoapInterceptor {
public ClientResponseSchemaValidatingInterceptor() {
super(Phase.RECEIVE);
}
@Override
public void handleMessage(SoapMessage message) {
message.put(Message.SCHEMA_VALIDATION_ENABLED, validationEnabled);
message.getExchange().getInMessage().put(Message.SCHEMA_VALIDATION_ENABLED, validationEnabled);
message.getExchange().put(Message.SCHEMA_VALIDATION_ENABLED, validationEnabled);
}
}
which seems to validate mandatory attributes being present or not but not the contents (i.e. matching a regex in the xsd)
After failing on the documented methods of achieving this I creating a custom interceptor which validates the messages.
public class ClientResponseSchemaValidatingInterceptor extends AbstractSoapInterceptor {
private Marshaller marshaller= null;
public ClientResponseSchemaValidatingInterceptor() {
super(Phase.PRE_INVOKE);
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try {
Schema schema =
schemaFactory.newSchema(this.getClass().getClassLoader().getResource("schema/your-xsd.xsd"));
marshaller = JAXBContext.newInstance(YourModelClass.class).createMarshaller();
marshaller.setSchema(schema);
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
} catch (SAXException | JAXBException ex) {
log.error("Error creating marshaller",ex);
}
}
@Override
public void handleMessage(SoapMessage message) {
List contents = message.getContent(List.class);
if (contents!=null){
String responseType = contents.get(0).getClass().getSimpleName();
try {
marshaller.marshal(contents.get(0), new DefaultHandler())
}
} catch (JAXBException ex){
log.info("Failed validation",ex);
throw new RuntimeException("Validation Error");
}
}
}
}