验证客户响应CXF

时间:2017-11-16 13:59:13

标签: java cxf dropwizard

我们正在使用Apache CXF和Dropwizard-JAXWS与SOAP服务进行交互。我们希望在客户端级别验证响应。

我们试过这个:

((BindingProvider)port).getRequestContext().put("schema-validation-enabled", "true"); 

来自http://cxf.apache.org/faq.html构建客户端时没有运气。

我们最接近的是为客户端编写拦截器并在消息中添加以下内容

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);
}

}

似乎验证强制属性是否存在但不是内容(即匹配xsd中的正则表达式)

1 个答案:

答案 0 :(得分:0)

在记录完成此方法的方法失败后,我创建了一个验证消息的自定义拦截器。

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");
        }
    }
}

}