View Javadoc

1   /*
2    * Copyright 2005-2010 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 javax.xml.transform.Source;
20  import javax.xml.transform.TransformerException;
21  import javax.xml.transform.dom.DOMResult;
22  
23  import org.springframework.util.Assert;
24  import org.springframework.ws.WebServiceMessage;
25  import org.springframework.xml.transform.TransformerHelper;
26  
27  import org.custommonkey.xmlunit.Diff;
28  import org.w3c.dom.Document;
29  
30  import static org.springframework.ws.test.support.AssertionErrors.fail;
31  
32  /**
33   * Matches {@link Source} payloads.
34   *
35   * @author Arjen Poutsma
36   * @author Lukas Krecan
37   * @since 2.0
38   */
39  public class PayloadDiffMatcher extends DiffMatcher {
40  
41      private final Source expected;
42  
43      private final TransformerHelper transformerHelper = new TransformerHelper();
44  
45      public PayloadDiffMatcher(Source expected) {
46          Assert.notNull(expected, "'expected' must not be null");
47          this.expected = expected;
48      }
49  
50      @Override
51      protected final Diff createDiff(WebServiceMessage message) {
52          Source payload = message.getPayloadSource();
53          if (payload == null) {
54              fail("Request message does not contain payload");
55          }
56          return createDiff(payload);
57      }
58  
59      protected Diff createDiff(Source payload) {
60          Document expectedDocument = createDocumentFromSource(expected);
61          Document actualDocument = createDocumentFromSource(payload);
62          return new Diff(expectedDocument, actualDocument);
63      }
64  
65      private Document createDocumentFromSource(Source source) {
66          try {
67              DOMResult result = new DOMResult();
68              transformerHelper.transform(source, result);
69              return (Document) result.getNode();
70          }
71          catch (TransformerException ex) {
72              fail("Could not transform source to DOMResult" + ex.getMessage());
73              return null;
74          }
75      }
76  }