简体   繁体   中英

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. 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 .

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.

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. 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 . 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.

There is a nice blog by Blaise Doughan describing the workflow here .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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