2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.yangtools.yang.data.codec.xml;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
13 import static org.junit.Assert.assertNotNull;
14 import static org.opendaylight.yangtools.yang.data.impl.schema.Builders.augmentationBuilder;
15 import static org.opendaylight.yangtools.yang.data.impl.schema.Builders.choiceBuilder;
16 import static org.opendaylight.yangtools.yang.data.impl.schema.Builders.containerBuilder;
17 import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.leafNode;
19 import com.google.common.collect.ImmutableSet;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.StringWriter;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.HashMap;
27 import java.util.HashSet;
30 import javax.xml.stream.XMLInputFactory;
31 import javax.xml.stream.XMLOutputFactory;
32 import javax.xml.stream.XMLStreamReader;
33 import javax.xml.stream.XMLStreamWriter;
34 import javax.xml.transform.OutputKeys;
35 import javax.xml.transform.Transformer;
36 import javax.xml.transform.TransformerException;
37 import javax.xml.transform.TransformerFactory;
38 import javax.xml.transform.TransformerFactoryConfigurationError;
39 import javax.xml.transform.dom.DOMResult;
40 import javax.xml.transform.dom.DOMSource;
41 import javax.xml.transform.stream.StreamResult;
42 import org.custommonkey.xmlunit.Diff;
43 import org.custommonkey.xmlunit.ElementNameAndTextQualifier;
44 import org.custommonkey.xmlunit.IgnoreTextAndAttributeValuesDifferenceListener;
45 import org.custommonkey.xmlunit.XMLUnit;
46 import org.junit.Test;
47 import org.junit.runner.RunWith;
48 import org.junit.runners.Parameterized;
49 import org.opendaylight.yangtools.util.xml.UntrustedXML;
50 import org.opendaylight.yangtools.yang.common.QName;
51 import org.opendaylight.yangtools.yang.common.Revision;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
55 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
56 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
58 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
62 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
63 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
64 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
65 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
66 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
67 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
68 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
69 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
70 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
71 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
72 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
73 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
74 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
75 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
76 import org.opendaylight.yangtools.yang.model.api.Module;
77 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
78 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
79 import org.w3c.dom.Document;
80 import org.w3c.dom.Node;
81 import org.xml.sax.SAXException;
83 @RunWith(Parameterized.class)
84 public class NormalizedNodeXmlTranslationTest {
85 private final SchemaContext schema;
87 @Parameterized.Parameters()
88 public static Collection<Object[]> data() {
89 return Arrays.asList(new Object[][] {
90 { "/schema/augment_choice_hell.yang", "/schema/augment_choice_hell_ok.xml", augmentChoiceHell() },
91 { "/schema/augment_choice_hell.yang", "/schema/augment_choice_hell_ok2.xml", null },
92 { "/schema/augment_choice_hell.yang", "/schema/augment_choice_hell_ok3.xml", augmentChoiceHell2() },
93 { "/schema/test.yang", "/schema/simple.xml", null },
94 { "/schema/test.yang", "/schema/simple2.xml", null },
95 // TODO check attributes
96 { "/schema/test.yang", "/schema/simple_xml_with_attributes.xml", withAttributes() }
100 private static final String NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:test";
101 private static final Revision REVISION = Revision.of("2014-03-13");
103 static final XMLOutputFactory XML_FACTORY;
106 XML_FACTORY = XMLOutputFactory.newFactory();
107 XML_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.FALSE);
110 private static ContainerNode augmentChoiceHell2() {
111 final NodeIdentifier container = getNodeIdentifier("container");
112 final QName augmentChoice1QName = QName.create(container.getNodeType(), "augment-choice1");
113 final QName augmentChoice2QName = QName.create(augmentChoice1QName, "augment-choice2");
114 final QName containerQName = QName.create(augmentChoice1QName, "case11-choice-case-container");
115 final QName leafQName = QName.create(augmentChoice1QName, "case11-choice-case-leaf");
117 final AugmentationIdentifier aug1Id = new AugmentationIdentifier(ImmutableSet.of(augmentChoice1QName));
118 final AugmentationIdentifier aug2Id = new AugmentationIdentifier(ImmutableSet.of(augmentChoice2QName));
119 final NodeIdentifier augmentChoice1Id = new NodeIdentifier(augmentChoice1QName);
120 final NodeIdentifier augmentChoice2Id = new NodeIdentifier(augmentChoice2QName);
121 final NodeIdentifier containerId = new NodeIdentifier(containerQName);
123 return containerBuilder().withNodeIdentifier(container)
124 .withChild(augmentationBuilder().withNodeIdentifier(aug1Id)
125 .withChild(choiceBuilder().withNodeIdentifier(augmentChoice1Id)
126 .withChild(augmentationBuilder().withNodeIdentifier(aug2Id)
127 .withChild(choiceBuilder().withNodeIdentifier(augmentChoice2Id)
128 .withChild(containerBuilder().withNodeIdentifier(containerId)
129 .withChild(leafNode(leafQName, "leaf-value"))
137 private static ContainerNode withAttributes() {
138 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> b = containerBuilder();
139 b.withNodeIdentifier(getNodeIdentifier("container"));
141 final CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = Builders.mapBuilder().withNodeIdentifier(
142 getNodeIdentifier("list"));
144 final Map<QName, Object> predicates = new HashMap<>();
145 predicates.put(getNodeIdentifier("uint32InList").getNodeType(), 3L);
147 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> list1Builder = Builders
148 .mapEntryBuilder().withNodeIdentifier(
149 new NodeIdentifierWithPredicates(
150 getNodeIdentifier("list").getNodeType(), predicates));
151 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> uint32InListBuilder = Builders
152 .leafBuilder().withNodeIdentifier(getNodeIdentifier("uint32InList"));
154 list1Builder.withChild(uint32InListBuilder.withValue(3L).build());
156 listBuilder.withChild(list1Builder.build());
157 b.withChild(listBuilder.build());
159 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> booleanBuilder = Builders
160 .leafBuilder().withNodeIdentifier(getNodeIdentifier("boolean"));
161 booleanBuilder.withValue(Boolean.FALSE);
162 b.withChild(booleanBuilder.build());
164 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> leafListBuilder = Builders.leafSetBuilder()
165 .withNodeIdentifier(getNodeIdentifier("leafList"));
167 final NormalizedNodeBuilder<NodeWithValue, Object, LeafSetEntryNode<Object>> leafList1Builder = Builders
168 .leafSetEntryBuilder().withNodeIdentifier(
169 new NodeWithValue(getNodeIdentifier("leafList").getNodeType(), "a"));
171 leafList1Builder.withValue("a");
173 leafListBuilder.withChild(leafList1Builder.build());
174 b.withChild(leafListBuilder.build());
179 private static ContainerNode augmentChoiceHell() {
181 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> b = containerBuilder();
182 b.withNodeIdentifier(getNodeIdentifier("container"));
184 b.withChild(choiceBuilder()
185 .withNodeIdentifier(getNodeIdentifier("ch2"))
187 Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("c2Leaf")).withValue("2").build())
190 .withNodeIdentifier(getNodeIdentifier("c2DeepChoice"))
192 Builders.leafBuilder()
193 .withNodeIdentifier(getNodeIdentifier("c2DeepChoiceCase1Leaf2"))
194 .withValue("2").build()).build()).build());
196 b.withChild(choiceBuilder()
197 .withNodeIdentifier(getNodeIdentifier("ch3"))
199 Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("c3Leaf")).withValue("3").build())
202 b.withChild(augmentationBuilder()
203 .withNodeIdentifier(getAugmentIdentifier("augLeaf"))
205 Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("augLeaf")).withValue("augment")
208 b.withChild(augmentationBuilder()
209 .withNodeIdentifier(getAugmentIdentifier("ch"))
212 .withNodeIdentifier(getNodeIdentifier("ch"))
214 Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("c1Leaf"))
215 .withValue("1").build())
217 augmentationBuilder()
219 getAugmentIdentifier("c1Leaf_AnotherAugment", "deepChoice"))
221 Builders.leafBuilder()
223 getNodeIdentifier("c1Leaf_AnotherAugment"))
224 .withValue("1").build())
227 .withNodeIdentifier(getNodeIdentifier("deepChoice"))
229 Builders.leafBuilder()
231 getNodeIdentifier("deepLeafc1"))
232 .withValue("1").build()).build())
233 .build()).build()).build());
238 private static NodeIdentifier getNodeIdentifier(final String localName) {
239 return new NodeIdentifier(QName.create(URI.create(NAMESPACE), REVISION, localName));
242 private static AugmentationIdentifier getAugmentIdentifier(final String... childNames) {
243 final Set<QName> qn = new HashSet<>();
245 for (final String childName : childNames) {
246 qn.add(getNodeIdentifier(childName).getNodeType());
249 return new AugmentationIdentifier(qn);
252 public NormalizedNodeXmlTranslationTest(final String yangPath, final String xmlPath,
253 final ContainerNode expectedNode) {
254 this.schema = YangParserTestUtils.parseYangResource(yangPath);
255 this.xmlPath = xmlPath;
256 this.containerNode = (ContainerSchemaNode) getSchemaNode(schema, "test", "container");
257 this.expectedNode = expectedNode;
260 private final ContainerNode expectedNode;
261 private final ContainerSchemaNode containerNode;
262 private final String xmlPath;
265 public void testTranslation() throws Exception {
266 final InputStream resourceAsStream = XmlToNormalizedNodesTest.class.getResourceAsStream(xmlPath);
268 final XMLInputFactory factory = XMLInputFactory.newInstance();
269 final XMLStreamReader reader = factory.createXMLStreamReader(resourceAsStream);
271 final NormalizedNodeResult result = new NormalizedNodeResult();
272 final NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result);
274 final XmlParserStream xmlParser = XmlParserStream.create(streamWriter, schema, containerNode);
275 xmlParser.parse(reader);
277 final NormalizedNode<?, ?> built = result.getResult();
278 assertNotNull(built);
280 if (expectedNode != null) {
281 org.junit.Assert.assertEquals(expectedNode, built);
284 final Document document = UntrustedXML.newDocumentBuilder().newDocument();
285 final DOMResult domResult = new DOMResult(document);
287 final XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
288 outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
290 final XMLStreamWriter xmlStreamWriter = outputFactory.createXMLStreamWriter(domResult);
292 final NormalizedNodeStreamWriter xmlNormalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter
293 .create(xmlStreamWriter, schema);
295 final NormalizedNodeWriter normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(
296 xmlNormalizedNodeStreamWriter);
298 normalizedNodeWriter.write(built);
300 final Document doc = loadDocument(xmlPath);
302 XMLUnit.setIgnoreWhitespace(true);
303 XMLUnit.setIgnoreComments(true);
304 XMLUnit.setIgnoreAttributeOrder(true);
305 XMLUnit.setNormalize(true);
307 final String expectedXml = toString(doc.getDocumentElement());
308 final String serializedXml = toString(domResult.getNode());
310 final Diff diff = new Diff(expectedXml, serializedXml);
311 diff.overrideDifferenceListener(new IgnoreTextAndAttributeValuesDifferenceListener());
312 diff.overrideElementQualifier(new ElementNameAndTextQualifier());
314 // FIXME the comparison cannot be performed, since the qualifiers supplied by XMlUnit do not work correctly in
316 // We need to implement custom qualifier so that the element ordering does not mess the DIFF
317 // dd.overrideElementQualifier(new MultiLevelElementNameAndTextQualifier(100, true));
318 // assertTrue(dd.toString(), dd.similar());
320 //new XMLTestCase() {}.assertXMLEqual(diff, true);
323 private static Document loadDocument(final String xmlPath) throws IOException, SAXException {
324 final InputStream resourceAsStream = NormalizedNodeXmlTranslationTest.class.getResourceAsStream(xmlPath);
325 return requireNonNull(readXmlToDocument(resourceAsStream));
328 private static Document readXmlToDocument(final InputStream xmlContent) throws IOException, SAXException {
329 final Document doc = UntrustedXML.newDocumentBuilder().parse(xmlContent);
330 doc.getDocumentElement().normalize();
334 private static String toString(final Node xml) {
336 final Transformer transformer = TransformerFactory.newInstance().newTransformer();
337 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
338 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
340 final StreamResult result = new StreamResult(new StringWriter());
341 final DOMSource source = new DOMSource(xml);
342 transformer.transform(source, result);
344 return result.getWriter().toString();
345 } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
346 throw new RuntimeException("Unable to serialize xml element " + xml, e);
350 private static DataSchemaNode getSchemaNode(final SchemaContext context, final String moduleName,
351 final String childNodeName) {
352 for (Module module : context.getModules()) {
353 if (module.getName().equals(moduleName)) {
354 DataSchemaNode found = findChildNode(module, childNodeName);
355 checkState(found != null, "Unable to find %s", childNodeName);
359 throw new IllegalStateException("Unable to find child node " + childNodeName);
362 // FIXME: duplicate of NormalizedDataBuilderTest.findChildNode()
363 private static DataSchemaNode findChildNode(final DataNodeContainer container, final String name) {
364 for (DataSchemaNode dataSchemaNode : container.getChildNodes()) {
365 if (dataSchemaNode.getQName().getLocalName().equals(name)) {
366 return dataSchemaNode;
368 if (dataSchemaNode instanceof DataNodeContainer) {
369 DataSchemaNode retVal = findChildNode((DataNodeContainer) dataSchemaNode, name);
370 if (retVal != null) {
373 } else if (dataSchemaNode instanceof ChoiceSchemaNode) {
374 for (ChoiceCaseNode caseNode : ((ChoiceSchemaNode) dataSchemaNode).getCases().values()) {
375 DataSchemaNode retVal = findChildNode(caseNode, name);
376 if (retVal != null) {