Bug 1441: Bug fixes, clean-up and test migration
[yangtools.git] / yang / yang-data-codec-xml / src / test / java / org / opendaylight / yangtools / yang / data / codec / xml / NormalizedNodesToXmlTest.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.yangtools.yang.data.codec.xml;
10
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.Sets;
13 import java.io.IOException;
14 import java.io.InputStream;
15 import java.io.StringWriter;
16 import java.net.URI;
17 import java.net.URISyntaxException;
18 import java.text.ParseException;
19 import java.util.HashMap;
20 import java.util.Map;
21 import javax.xml.parsers.DocumentBuilder;
22 import javax.xml.parsers.DocumentBuilderFactory;
23 import javax.xml.parsers.ParserConfigurationException;
24 import javax.xml.stream.XMLOutputFactory;
25 import javax.xml.stream.XMLStreamException;
26 import javax.xml.stream.XMLStreamWriter;
27 import javax.xml.transform.OutputKeys;
28 import javax.xml.transform.Transformer;
29 import javax.xml.transform.TransformerException;
30 import javax.xml.transform.TransformerFactory;
31 import javax.xml.transform.TransformerFactoryConfigurationError;
32 import javax.xml.transform.dom.DOMResult;
33 import javax.xml.transform.dom.DOMSource;
34 import javax.xml.transform.stream.StreamResult;
35 import org.custommonkey.xmlunit.Diff;
36 import org.custommonkey.xmlunit.DifferenceListener;
37 import org.custommonkey.xmlunit.IgnoreTextAndAttributeValuesDifferenceListener;
38 import org.custommonkey.xmlunit.XMLTestCase;
39 import org.custommonkey.xmlunit.XMLUnit;
40 import org.junit.Before;
41 import org.junit.Test;
42 import org.opendaylight.yangtools.yang.common.QName;
43 import org.opendaylight.yangtools.yang.common.QNameModule;
44 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
49 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
57 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
58 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
59 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
60 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
61 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
62 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
63 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangStatementSourceImpl;
64 import org.w3c.dom.Document;
65 import org.w3c.dom.Node;
66 import org.xml.sax.SAXException;
67
68 public class NormalizedNodesToXmlTest {
69
70     private QNameModule bazModule;
71
72     private QName outerContainer;
73
74     private QName myContainer1;
75     private QName myKeyedList;
76     private QName myKeyLeaf;
77     private QName myLeafInList1;
78     private QName myLeafInList2;
79     private QName myLeaf1;
80     private QName myLeafList;
81
82     private QName myContainer2;
83     private QName innerContainer;
84     private QName myLeaf2;
85     private QName myLeaf3;
86     private QName myChoice;
87     private QName myLeafInCase2;
88
89     private QName myContainer3;
90     private QName myDoublyKeyedList;
91     private QName myFirstKeyLeaf;
92     private QName mySecondKeyLeaf;
93     private QName myLeafInList3;
94
95     @Before
96     public void setup() throws URISyntaxException, ParseException {
97         bazModule = QNameModule.create(new URI("baz-namespace"), SimpleDateFormatUtil.getRevisionFormat()
98                 .parse("1970-01-01"));
99
100         outerContainer = QName.create(bazModule, "outer-container");
101
102         myContainer1 = QName.create(bazModule, "my-container-1");
103         myKeyedList = QName.create(bazModule, "my-keyed-list");
104         myKeyLeaf = QName.create(bazModule, "my-key-leaf");
105         myLeafInList1 = QName.create(bazModule, "my-leaf-in-list-1");
106         myLeafInList2 = QName.create(bazModule, "my-leaf-in-list-2");
107         myLeaf1 = QName.create(bazModule, "my-leaf-1");
108         myLeafList = QName.create(bazModule, "my-leaf-list");
109
110         myContainer2 = QName.create(bazModule, "my-container-2");
111         innerContainer = QName.create(bazModule, "inner-container");
112         myLeaf2 = QName.create(bazModule, "my-leaf-2");
113         myLeaf3 = QName.create(bazModule, "my-leaf-3");
114         myChoice = QName.create(bazModule, "my-choice");
115         myLeafInCase2 = QName.create(bazModule, "my-leaf-in-case-2");
116
117         myContainer3 = QName.create(bazModule, "my-container-3");
118         myDoublyKeyedList = QName.create(bazModule, "my-doubly-keyed-list");
119         myFirstKeyLeaf = QName.create(bazModule, "my-first-key-leaf");
120         mySecondKeyLeaf = QName.create(bazModule, "my-second-key-leaf");
121         myLeafInList3 = QName.create(bazModule, "my-leaf-in-list-3");
122     }
123
124     @Test
125     public void testNormalizedNodeToXmlSerialization() throws ReactorException, XMLStreamException, IOException,
126             SAXException {
127         final CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
128         reactor.addSource(new YangStatementSourceImpl("/baz.yang", false));
129
130         final SchemaContext schemaContext = reactor.buildEffective();
131
132         final Document doc = loadDocument("/baz.xml");
133
134         final Document document = getDocument();
135         final DOMResult domResult = new DOMResult(document);
136
137         final XMLOutputFactory factory = XMLOutputFactory.newInstance();
138         factory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
139
140         final XMLStreamWriter xmlStreamWriter = factory.createXMLStreamWriter(domResult);
141
142         final NormalizedNodeStreamWriter xmlNormalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter.create
143                 (xmlStreamWriter, schemaContext);
144
145         final NormalizedNodeWriter normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter
146                 (xmlNormalizedNodeStreamWriter);
147
148         normalizedNodeWriter.write(buildOuterContainerNode());
149
150         XMLUnit.setIgnoreWhitespace(true);
151         XMLUnit.setNormalize(true);
152
153         final String expectedXml = toString(doc.getDocumentElement().getElementsByTagName("outer-container").item(0));
154         final String serializedXml = toString(domResult.getNode());
155         final Diff diff = new Diff(expectedXml, serializedXml);
156
157         final DifferenceListener differenceListener = new IgnoreTextAndAttributeValuesDifferenceListener();
158         diff.overrideDifferenceListener(differenceListener);
159
160         new XMLTestCase() {}.assertXMLEqual(diff, true);
161     }
162
163     private NormalizedNode<?, ?> buildOuterContainerNode() {
164         // my-container-1
165         MapNode myKeyedListNode = Builders.mapBuilder().withNodeIdentifier(new NodeIdentifier(myKeyedList))
166                 .withChild(Builders.mapEntryBuilder().withNodeIdentifier(
167                         new NodeIdentifierWithPredicates(myKeyedList, myKeyLeaf, "listkeyvalue1"))
168                         .withChild(Builders.leafBuilder().withNodeIdentifier(new NodeIdentifier(myLeafInList1))
169                                 .withValue("listleafvalue1").build())
170                         .withChild(Builders.leafBuilder().withNodeIdentifier(new NodeIdentifier(myLeafInList2))
171                                 .withValue("listleafvalue2").build()).build())
172                 .withChild(Builders.mapEntryBuilder().withNodeIdentifier(
173                         new NodeIdentifierWithPredicates(myKeyedList, myKeyLeaf, "listkeyvalue2"))
174                         .withChild(Builders.leafBuilder().withNodeIdentifier(new NodeIdentifier(myLeafInList1))
175                                 .withValue("listleafvalue12").build())
176                         .withChild(Builders.leafBuilder().withNodeIdentifier(new NodeIdentifier(myLeafInList2))
177                                 .withValue("listleafvalue22").build()).build()).build();
178
179         LeafNode<?> myLeaf1Node = Builders.leafBuilder().withNodeIdentifier(new NodeIdentifier(myLeaf1))
180                 .withValue("value1").build();
181
182         LeafSetNode<?> myLeafListNode = Builders.leafSetBuilder().withNodeIdentifier(new NodeIdentifier(myLeafList))
183                 .withChild(Builders.leafSetEntryBuilder().withNodeIdentifier(
184                         new NodeWithValue<>(myLeafList, "lflvalue1")).withValue("lflvalue1").build())
185                 .withChild(Builders.leafSetEntryBuilder().withNodeIdentifier(
186                         new NodeWithValue<>(myLeafList, "lflvalue2")).withValue("lflvalue2").build()).build();
187
188         ContainerNode myContainer1Node = Builders.containerBuilder().withNodeIdentifier(
189                 new NodeIdentifier(myContainer1))
190                 .withChild(myKeyedListNode)
191                 .withChild(myLeaf1Node)
192                 .withChild(myLeafListNode).build();
193
194         // my-container-2
195         ContainerNode innerContainerNode = Builders.containerBuilder().withNodeIdentifier(
196                 new NodeIdentifier(innerContainer))
197                 .withChild(Builders.leafBuilder().withNodeIdentifier(new NodeIdentifier(myLeaf2))
198                         .withValue("value2").build()).build();
199
200         LeafNode<?> myLeaf3Node = Builders.leafBuilder().withNodeIdentifier(new NodeIdentifier(myLeaf3))
201                 .withValue("value3").build();
202
203         ChoiceNode myChoiceNode = Builders.choiceBuilder().withNodeIdentifier(new NodeIdentifier(myChoice))
204                 .withChild(Builders.leafBuilder().withNodeIdentifier(new NodeIdentifier(myLeafInCase2))
205                         .withValue("case2value").build()).build();
206
207         ContainerNode myContainer2Node = Builders.containerBuilder().withNodeIdentifier(
208                 new NodeIdentifier(myContainer2))
209                 .withChild(innerContainerNode)
210                 .withChild(myLeaf3Node)
211                 .withChild(myChoiceNode).build();
212
213         // my-container-3
214         Map<QName, Object> keys = new HashMap<>();
215         keys.put(myFirstKeyLeaf, "listkeyvalue1");
216         keys.put(mySecondKeyLeaf, "listkeyvalue2");
217
218         MapNode myDoublyKeyedListNode = Builders.mapBuilder().withNodeIdentifier(new NodeIdentifier(myDoublyKeyedList))
219                 .withChild(Builders.mapEntryBuilder().withNodeIdentifier(
220                         new NodeIdentifierWithPredicates(myDoublyKeyedList, keys))
221                         .withChild(Builders.leafBuilder().withNodeIdentifier(
222                                 new NodeIdentifier(myLeafInList3)).withValue("listleafvalue1").build()).build())
223                 .build();
224
225         AugmentationNode myDoublyKeyedListAugNode = Builders.augmentationBuilder().withNodeIdentifier(
226                 new AugmentationIdentifier(Sets.newHashSet(myDoublyKeyedList)))
227                 .withChild(myDoublyKeyedListNode).build();
228
229         ContainerNode myContainer3Node = Builders.containerBuilder().withNodeIdentifier(
230                 new NodeIdentifier(myContainer3))
231                 .withChild(myDoublyKeyedListAugNode).build();
232
233         AugmentationNode myContainer3AugNode = Builders.augmentationBuilder().withNodeIdentifier(
234                 new AugmentationIdentifier(Sets.newHashSet(myContainer3)))
235                 .withChild(myContainer3Node).build();
236
237         ContainerNode outerContainerNode = Builders.containerBuilder().withNodeIdentifier(
238                 new NodeIdentifier(outerContainer))
239                 .withChild(myContainer1Node)
240                 .withChild(myContainer2Node)
241                 .withChild(myContainer3AugNode).build();
242
243         return outerContainerNode;
244     }
245
246     private static Document loadDocument(final String xmlPath) throws IOException, SAXException {
247         final InputStream resourceAsStream = NormalizedNodesToXmlTest.class.getResourceAsStream(xmlPath);
248         final Document currentConfigElement = readXmlToDocument(resourceAsStream);
249         Preconditions.checkNotNull(currentConfigElement);
250         return currentConfigElement;
251     }
252
253     private static Document readXmlToDocument(final InputStream xmlContent) throws IOException, SAXException {
254         final DocumentBuilder dBuilder;
255         try {
256             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
257             factory.setNamespaceAware(true);
258             factory.setCoalescing(true);
259             factory.setIgnoringElementContentWhitespace(true);
260             factory.setIgnoringComments(true);
261             dBuilder = factory.newDocumentBuilder();
262         } catch (final ParserConfigurationException e) {
263             throw new RuntimeException("Failed to parse XML document", e);
264         }
265         final Document doc = dBuilder.parse(xmlContent);
266
267         doc.getDocumentElement().normalize();
268         return doc;
269     }
270
271     private static String toString(final Node xml) {
272         try {
273             final Transformer transformer = TransformerFactory.newInstance().newTransformer();
274             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
275             transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
276
277             final StreamResult result = new StreamResult(new StringWriter());
278             final DOMSource source = new DOMSource(xml);
279             transformer.transform(source, result);
280
281             return result.getWriter().toString();
282         } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
283             throw new RuntimeException("Unable to serialize xml element " + xml, e);
284         }
285     }
286
287     private static Document getDocument() {
288         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
289         Document doc = null;
290         try {
291             DocumentBuilder bob = dbf.newDocumentBuilder();
292             doc = bob.newDocument();
293         } catch (ParserConfigurationException e) {
294             throw new RuntimeException(e);
295         }
296         return doc;
297     }
298 }