0

My task is to implement a webservice that:

  • consumes an XML file on a POST endpoint
  • in happy flow, it returns a DTO as JSON + HTTP 2xx
  • the incoming XML file is validated against a XSD; if the validation fails, a JSON with a list of all validation errors is returned (including the line, column, error) with HTTP Bad request
  • the application exposes two endpoints, only one of them should be validated

I have started the implementation with Spring Boot + web, using regular @PostMapping which has "consumes" and "produces" set to application/xml and application/json, respectively. The usual flow works perfectly fine. Now, I stumbled upon the issue of validating the incoming payload. What I figured out:

1) I have to validate the payload before it is converted (marshalled) to an object.

2) Once validated, I have to either:

  • allow further processing
  • stop any further processing, write the error object to the response and set the status code to 400 Bad request

My approaches were:

1) using a RequestBodyAdvice, more specifically the beforeBodyRead method implementation. I had the following issue here: I don't know how to write anything to the output in case the validation fails.

2) using a Filter (I've extended OncePerRequestFilter) - fortunately, I can read the request (request.getInputStream()) and write to the response (response.getOutputStream()).

However, how can I do the selective filtering (as mentioned, I only want to validate one single endpoint)?

Are there any other alternatives for placing the incoming request XSD validation? Is spring-web the appropriate choice here? Would you recommend some other library / framework?

Maciej Papież
  • 431
  • 1
  • 6
  • 20

1 Answers1

1

To validate xml against xsd schema, my preference is XML Beans. It is very easy to use. Other options are JABX, Castor. Take a look at Java to XML conversions?.

You will need to jar using xsd schmema and will need to put it in the classpath of your application so that it's classes are available for you for validation. Please take a look at this blog.

You can use validation API as mentioned here.

I would prefer to write validation code in the aspect so that it can be reused with other APIs.

  • If validation fails, throw valid exception from the aspect itself.
  • If validation is passed, process your input string that you receive.

Please let us know if you need any more information.

Community
  • 1
  • 1
asg
  • 2,248
  • 3
  • 18
  • 26