Search code examples
javaspring-bootxsdwsdlspring-ws

How to validate multiple XSD Schemas with Spring's PayloadValidatingInterceptor


I have a Spring Boot project with multiple XSD Schemas (I'm using Spring-WS).

If I use Spring's PayloadValidatingInterceptor to validate requests and responses, it only works with the latest set schema.

For instance:

public void addInterceptors(List<EndpointInterceptor> interceptors) {
    PayloadValidatingInterceptor validatingInterceptor = new PayloadValidatingInterceptor();
    validatingInterceptor.setValidateRequest(true);
    validatingInterceptor.setValidateResponse(true);
    validatingInterceptor.setXsdSchema(getFirstSchema());
    validatingInterceptor.setXsdSchema(getSecondSchema());
    interceptors.add(validatingInterceptor);
    super.addInterceptors(interceptors);
}

This snippet will make Spring to validate only the second schema, not the first. I've tried creating multiple PayloadValidatingInterceptors to add them with super.addInterceptors(interceptors);, but it didn't work either. The only response I was able to find (with Java instead of XML), is from 2009:

https://jira.spring.io/browse/SWS-481

Does anyone know of a Java-based solution to validate requests and responses from multiple XSDs in the same project?


Solution

  • Posting a solution for future reference, since I wasn't able to find a single example in internet.

    To validate multiple schemas, this is what I did:

    Instead of validatingInterceptor.setXsdSchema(), I ended up using validatingInterceptor.setXsdSchemaCollection().

    This receives an XsdSchemaCollection, which you need to instanciate and implement 2 anon methods, like this:

        XsdSchemaCollection schemaCollection = new XsdSchemaCollection() {
    
            @Override
            public XsdSchema[] getXsdSchemas() {
                return null;
            }
    
            @Override
            public XmlValidator createValidator() {
                try {
                    XmlValidator xmlValidator = XmlValidatorFactory.createValidator(getSchemas(), "http://www.w3.org/2001/XMLSchema");
    
                    return xmlValidator;
                } catch (IOException e) {
                    logger.error(e.getLocalizedMessage());
                }
                return null;
            }
        };
    

    The getSchemas() method returns an array of Resources from where you pass the current XSDs to validate:

    public Resource[] getSchemas() {
        List<Resource> schemaResources = new ArrayList<>();
        schemaResources.add(new ClassPathResource("firstService.xsd"));
        schemaResources.add(new ClassPathResource("secondService.xsd"));
        schemaResources.add(new ClassPathResource("thirdService.xsd"));
        return schemaResources.toArray(new Resource[schemaResources.size()]);
    }