Now using the dom level 3 API for parsing. Also extended the test case
[utils] / support / general / src / test / java / org / wamblee / xml / XmlUtils.java
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 package org.wamblee.xml;
17
18 import java.io.Serializable;
19 import java.util.ArrayList;
20 import java.util.Collections;
21 import java.util.Comparator;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.TreeMap;
25
26 import junit.framework.TestCase;
27
28 import org.w3c.dom.Attr;
29 import org.w3c.dom.Document;
30 import org.w3c.dom.Element;
31 import org.w3c.dom.NamedNodeMap;
32 import org.w3c.dom.Node;
33 import org.w3c.dom.NodeList;
34 import org.w3c.dom.Text;
35
36 /**
37  * XML test support utilities.
38  * 
39  * @author Erik Brakkee
40  */
41 public final class XmlUtils {
42     /**
43      * Disabled constructor.
44      * 
45      */
46     private XmlUtils() {
47         // Empty
48     }
49
50     /**
51      * Checks equality of two XML documents excluding comment and processing
52      * nodes and trimming the text of the elements. In case of problems, it
53      * provides an xpath-like expression describing where the problem is.
54      * 
55      * @param aMsg
56      * @param aExpected
57      * @param aActual
58      */
59     public static void assertEquals(String aMsg, Document aExpected,
60         Document aActual) {
61         assertEquals(
62             aMsg + "/" + aExpected.getDocumentElement().getLocalName(),
63             aExpected.getDocumentElement(), aActual.getDocumentElement());
64     }
65
66     private static <T> List<T> convertMap(NamedNodeMap aMap, Class<T> aType) {
67         List<T> result = new ArrayList<T>();
68         for (int i = 0; i < aMap.getLength(); i++) {
69             result.add((T) aMap.item(i));
70         }
71         return result;
72     }
73
74     private static List<Element> getChildElements(Element aElement) {
75         List<Element> result = new ArrayList<Element>();
76         NodeList children = aElement.getChildNodes();
77         for (int i = 0; i < children.getLength(); i++) {
78             Node node = children.item(i);
79             if (node instanceof Element) {
80                 result.add((Element) node);
81             }
82         }
83         return result;
84     }
85     
86     private static String getDirectText(Element aElement) { 
87         String res = "";
88         NodeList children = aElement.getChildNodes();
89         for (int i = 0; i < children.getLength(); i++) {
90             Node node = children.item(i);
91             if (node instanceof Text) {
92                 res += node.getTextContent() + " ";
93             }
94         }
95         return trim(res); 
96     }
97     
98     private static String trim(String aText) { 
99         return aText.trim().replaceAll("\\n", " ").replaceAll("\\s+", " ");
100     }
101
102     /**
103      * Checks equality of two XML elements excluding comment and processing
104      * nodes and trimming the text of the elements (including whitespace in the middle). 
105      * In case of problems, it
106      * provides an xpath-like expression describing where the problem is.
107      * 
108      * @param aMsg
109      * @param aExpected
110      * @param aActual
111      */
112     private static void assertEquals(String aMsg, Element aExpected,
113         Element aActual) {
114         // Name.
115         TestCase.assertEquals(aMsg + "/name()", aExpected.getLocalName(),
116             aActual.getLocalName());
117         TestCase.assertEquals(aMsg + "/namespace()",
118             aExpected.getNamespaceURI(), aActual.getNamespaceURI());
119
120         // Text
121         TestCase.assertEquals(aMsg + "/text()", getDirectText(aExpected)
122             , getDirectText(aActual));
123
124         // Attributes
125         List<Attr> expectedAttrs = convertMap(aExpected.getAttributes(),
126             Attr.class);
127
128         Collections.sort(expectedAttrs, new AttributeComparator());
129
130         List<Attr> actualAttrs = convertMap(aActual.getAttributes(), Attr.class);
131         Collections.sort(actualAttrs, new AttributeComparator());
132
133         TestCase.assertEquals("count(" + aMsg + "/@*)", expectedAttrs.size(),
134             actualAttrs.size());
135
136         for (int i = 0; i < expectedAttrs.size(); i++) {
137             String msg = aMsg + "/@" + expectedAttrs.get(i).getName();
138             assertEquals(msg, expectedAttrs.get(i), actualAttrs.get(i));
139         }
140
141         // Nested elements.
142         List<Element> expectedElems = getChildElements(aExpected);
143         List<Element> actualElems = getChildElements(aActual);
144         TestCase.assertEquals("count(" + aMsg + "/*)", expectedElems.size(),
145             actualElems.size());
146
147         // determine the how-manyth element of the given name we are at.
148         // Maps element name to the last used index (or null if not yet used)
149         Map<String, Integer> elementIndex = new TreeMap<String, Integer>();
150
151         for (int i = 0; i < expectedElems.size(); i++) {
152             String elemName = expectedElems.get(i).getLocalName();
153             Integer index = elementIndex.get(elemName);
154
155             if (index == null) {
156                 index = 1;
157             } else {
158                 index++;
159             }
160
161             elementIndex.put(elemName, index);
162
163             String msg = aMsg + "/" + expectedElems.get(i).getLocalName() + "[" +
164                 index + "]";
165
166             assertEquals(msg, expectedElems.get(i), actualElems.get(i));
167         }
168     }
169
170     /**
171      * Checks equality of two attributes. In case of problems, it provides an
172      * xpath-like expression describing where the problem is.
173      * 
174      * @param aMsg
175      * @param aExpected
176      * @param aActual
177      */
178     private static void assertEquals(String aMsg, Attr aExpected, Attr aActual) {
179         TestCase.assertEquals(aMsg + ":name", aExpected.getName(),
180             aActual.getName());
181         TestCase.assertEquals(aMsg + ":value", aExpected.getValue(),
182             aActual.getValue());
183     }
184
185     /**
186      * Comparator which compares attributes by name.
187      */
188     private static final class AttributeComparator implements Comparator<Attr>,
189         Serializable {
190
191         private static final long serialVersionUID = 7897287273519886301L;
192
193         /*
194          * (non-Javadoc)
195          * 
196          * @see java.util.Comparator#compare(T, T)
197          */
198         public int compare(Attr aAttribute1, Attr aAttribute2) {
199             return aAttribute1.getName().compareTo(aAttribute2.getName());
200         }
201     }
202 }