简体   繁体   English

使用模式的JAX-RS响应验证

[英]JAX-RS Response validation using schemas

I am using Jersey to send and receive XML over a HTTP REST service, while representing the data in JAXB annotated classes. 我正在使用Jersey通过HTTP REST服务发送和接收XML,同时以JAXB带注释的类表示数据。 Once I receive a Response all I need to do is call response.readEntity(Foo.class) in order to unmarshal the response into an instance of Foo . 收到Response只需调用response.readEntity(Foo.class)即可将响应解组为Foo实例。

Normally during the JAXB unmarshalling process you can validate the input using Schema s, but I didn't find any options to do the same when reading responses into entities. 通常,在JAXB解组过程中,您可以使用Schema来验证输入,但是在将响应读入实体时,我没有找到任何做相同操作的选项。

This is important to us because we have XSD files defining the format of the input and we would like to validate against these schemas. 这对我们很重要,因为我们拥有定义输入格式的XSD文件,并且我们希望针对这些模式进行验证。 Currently my only idea is to read the Response into a String , create the JAXBContext manually and assign the schema to the Unmarshaller before unmarshalling the String into an instance of Foo . 目前我唯一的想法就是读取ResponseString ,创建JAXBContext手动和分配模式的Unmarshaller解编前String入一个实例Foo While this doesn't sound all that horrible, hopefully there is a more concise way of doing this? 虽然这听起来并不那么可怕,但希望有一种更简洁的方法吗?

You need to implement the ValidationEventHandler interface from the JAXB API. 您需要从JAXB API实现ValidationEventHandler接口。

There is a nice blog by Blaise Doughan describing the workflow here . Blaise Doughan有一个不错的博客,在这里描述了工作流程。

Okay, so the way I solved this is that I read the response into a string and than I manually unmarshalled that into an object. 好的,所以我解决此问题的方法是将响应读取为字符串,然后手动将其解组为对象。 Here is the source code of the function that does this: 这是执行此操作的函数的源代码:

public static <T> T unmarshal(Response response, Class<T> entityClass, Schema schema) {
  String responseStr = response.readEntity(String.class);
  try {
    JAXBContext context = JAXBContext.newInstance(entityClass);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    unmarshaller.setSchema(schema);
    try (StringReader responseReader = new StringReader(responseStr)) {
      return (T) unmarshaller.unmarshal(responseReader);
    }
  } catch (JAXBException e) {
    logger.log(Level.SEVERE, "Error during response unmarshalling", e);
  }
  return null;
}

I consider this to be kind of a hack/workaround, rather than a proper solution, but it works flawlessly. 我认为这是一种破解/解决方法,而不是适当的解决方案,但是它可以完美地工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM