View Javadoc

1   /*
2    * Copyright 2005-2011 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.ws.test.support.matcher;
18  
19  import java.io.IOException;
20  import java.util.Arrays;
21  
22  import org.springframework.core.io.Resource;
23  import org.springframework.util.Assert;
24  import org.springframework.util.ObjectUtils;
25  import org.springframework.ws.WebServiceMessage;
26  import org.springframework.xml.validation.XmlValidator;
27  import org.springframework.xml.validation.XmlValidatorFactory;
28  
29  import org.xml.sax.SAXParseException;
30  
31  import static org.springframework.ws.test.support.AssertionErrors.fail;
32  
33  /**
34   * Uses the {@link XmlValidator} to validate request payload.
35   *
36   * @author Lukas Krecan
37   * @author Arjen Poutsma
38   * @since 2.0
39   */
40  public class SchemaValidatingMatcher implements WebServiceMessageMatcher {
41  
42      private final XmlValidator xmlValidator;
43  
44      /**
45       * Creates a {@code SchemaValidatingMatcher} based on the given schema resource(s).
46       *
47       * @param schema         the schema
48       * @param furtherSchemas further schemas, if necessary
49       * @throws IOException in case of I/O errors
50       */
51      public SchemaValidatingMatcher(Resource schema, Resource... furtherSchemas) throws IOException {
52          Assert.notNull(schema, "'schema' must not be null");
53          Resource[] joinedSchemas = new Resource[furtherSchemas.length + 1];
54          joinedSchemas[0] = schema;
55          System.arraycopy(furtherSchemas, 0, joinedSchemas, 1, furtherSchemas.length);
56          xmlValidator = XmlValidatorFactory.createValidator(joinedSchemas, XmlValidatorFactory.SCHEMA_W3C_XML);
57  
58      }
59  
60      public void match(WebServiceMessage message) throws IOException, AssertionError {
61          SAXParseException[] exceptions = xmlValidator.validate(message.getPayloadSource());
62          if (!ObjectUtils.isEmpty(exceptions)) {
63              fail("XML is not valid: " + Arrays.toString(exceptions), "Payload", message.getPayloadSource());
64          }
65      }
66  }