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.ArrayList;
25 import java.util.Arrays;
26 import java.util.Collection;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.List;
32 import javax.xml.stream.XMLInputFactory;
33 import javax.xml.stream.XMLOutputFactory;
34 import javax.xml.stream.XMLStreamReader;
35 import javax.xml.stream.XMLStreamWriter;
36 import javax.xml.transform.OutputKeys;
37 import javax.xml.transform.Transformer;
38 import javax.xml.transform.TransformerException;
39 import javax.xml.transform.TransformerFactory;
40 import javax.xml.transform.TransformerFactoryConfigurationError;
41 import javax.xml.transform.dom.DOMResult;
42 import javax.xml.transform.dom.DOMSource;
43 import javax.xml.transform.stream.StreamResult;
44 import org.custommonkey.xmlunit.Diff;
45 import org.custommonkey.xmlunit.ElementNameAndTextQualifier;
46 import org.custommonkey.xmlunit.IgnoreTextAndAttributeValuesDifferenceListener;
47 import org.custommonkey.xmlunit.XMLUnit;
48 import org.junit.Test;
49 import org.junit.runner.RunWith;
50 import org.junit.runners.Parameterized;
51 import org.opendaylight.yangtools.util.xml.UntrustedXML;
52 import org.opendaylight.yangtools.yang.common.QName;
53 import org.opendaylight.yangtools.yang.common.Revision;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
55 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
56 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
58 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
62 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
63 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
64 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
65 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
66 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
67 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
68 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
69 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
70 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
71 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
72 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
73 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
74 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
75 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
76 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
77 import org.opendaylight.yangtools.yang.model.api.Module;
78 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
79 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
80 import org.w3c.dom.Document;
81 import org.w3c.dom.Node;
82 import org.xml.sax.SAXException;
84 @RunWith(Parameterized.class)
85 public class NormalizedNodeXmlTranslationTest {
86 private final SchemaContext schema;
88 @Parameterized.Parameters()
89 public static Collection<Object[]> data() {
90 return Arrays.asList(new Object[][] {
91 { "/schema/augment_choice_hell.yang", "/schema/augment_choice_hell_ok.xml", augmentChoiceHell() },
92 { "/schema/augment_choice_hell.yang", "/schema/augment_choice_hell_ok2.xml", null },
93 { "/schema/augment_choice_hell.yang", "/schema/augment_choice_hell_ok3.xml", augmentChoiceHell2() },
94 { "/schema/test.yang", "/schema/simple.xml", null },
95 { "/schema/test.yang", "/schema/simple2.xml", null },
96 // TODO check attributes
97 { "/schema/test.yang", "/schema/simple_xml_with_attributes.xml", withAttributes() }
101 private static final String NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:test";
102 private static final Revision REVISION = Revision.valueOf("2014-03-13");
104 static final XMLOutputFactory XML_FACTORY;
107 XML_FACTORY = XMLOutputFactory.newFactory();
108 XML_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.FALSE);
111 private static ContainerNode augmentChoiceHell2() {
112 final NodeIdentifier container = getNodeIdentifier("container");
113 final QName augmentChoice1QName = QName.create(container.getNodeType(), "augment-choice1");
114 final QName augmentChoice2QName = QName.create(augmentChoice1QName, "augment-choice2");
115 final QName containerQName = QName.create(augmentChoice1QName, "case11-choice-case-container");
116 final QName leafQName = QName.create(augmentChoice1QName, "case11-choice-case-leaf");
118 final AugmentationIdentifier aug1Id = new AugmentationIdentifier(ImmutableSet.of(augmentChoice1QName));
119 final AugmentationIdentifier aug2Id = new AugmentationIdentifier(ImmutableSet.of(augmentChoice2QName));
120 final NodeIdentifier augmentChoice1Id = new NodeIdentifier(augmentChoice1QName);
121 final NodeIdentifier augmentChoice2Id = new NodeIdentifier(augmentChoice2QName);
122 final NodeIdentifier containerId = new NodeIdentifier(containerQName);
124 return containerBuilder().withNodeIdentifier(container)
125 .withChild(augmentationBuilder().withNodeIdentifier(aug1Id)
126 .withChild(choiceBuilder().withNodeIdentifier(augmentChoice1Id)
127 .withChild(augmentationBuilder().withNodeIdentifier(aug2Id)
128 .withChild(choiceBuilder().withNodeIdentifier(augmentChoice2Id)
129 .withChild(containerBuilder().withNodeIdentifier(containerId)
130 .withChild(leafNode(leafQName, "leaf-value"))
138 private static ContainerNode withAttributes() {
139 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> b = containerBuilder();
140 b.withNodeIdentifier(getNodeIdentifier("container"));
142 final CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = Builders.mapBuilder().withNodeIdentifier(
143 getNodeIdentifier("list"));
145 final Map<QName, Object> predicates = new HashMap<>();
146 predicates.put(getNodeIdentifier("uint32InList").getNodeType(), 3L);
148 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> list1Builder = Builders
149 .mapEntryBuilder().withNodeIdentifier(
150 new NodeIdentifierWithPredicates(
151 getNodeIdentifier("list").getNodeType(), predicates));
152 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> uint32InListBuilder = Builders
153 .leafBuilder().withNodeIdentifier(getNodeIdentifier("uint32InList"));
155 list1Builder.withChild(uint32InListBuilder.withValue(3L).build());
157 listBuilder.withChild(list1Builder.build());
158 b.withChild(listBuilder.build());
160 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> booleanBuilder = Builders
161 .leafBuilder().withNodeIdentifier(getNodeIdentifier("boolean"));
162 booleanBuilder.withValue(Boolean.FALSE);
163 b.withChild(booleanBuilder.build());
165 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> leafListBuilder = Builders.leafSetBuilder()
166 .withNodeIdentifier(getNodeIdentifier("leafList"));
168 final NormalizedNodeBuilder<NodeWithValue, Object, LeafSetEntryNode<Object>> leafList1Builder = Builders
169 .leafSetEntryBuilder().withNodeIdentifier(
170 new NodeWithValue(getNodeIdentifier("leafList").getNodeType(), "a"));
172 leafList1Builder.withValue("a");
174 leafListBuilder.withChild(leafList1Builder.build());
175 b.withChild(leafListBuilder.build());
180 private static ContainerNode augmentChoiceHell() {
182 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> b = containerBuilder();
183 b.withNodeIdentifier(getNodeIdentifier("container"));
185 b.withChild(choiceBuilder()
186 .withNodeIdentifier(getNodeIdentifier("ch2"))
188 Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("c2Leaf")).withValue("2").build())
191 .withNodeIdentifier(getNodeIdentifier("c2DeepChoice"))
193 Builders.leafBuilder()
194 .withNodeIdentifier(getNodeIdentifier("c2DeepChoiceCase1Leaf2"))
195 .withValue("2").build()).build()).build());
197 b.withChild(choiceBuilder()
198 .withNodeIdentifier(getNodeIdentifier("ch3"))
200 Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("c3Leaf")).withValue("3").build())
203 b.withChild(augmentationBuilder()
204 .withNodeIdentifier(getAugmentIdentifier("augLeaf"))
206 Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("augLeaf")).withValue("augment")
209 b.withChild(augmentationBuilder()
210 .withNodeIdentifier(getAugmentIdentifier("ch"))
213 .withNodeIdentifier(getNodeIdentifier("ch"))
215 Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("c1Leaf"))
216 .withValue("1").build())
218 augmentationBuilder()
220 getAugmentIdentifier("c1Leaf_AnotherAugment", "deepChoice"))
222 Builders.leafBuilder()
224 getNodeIdentifier("c1Leaf_AnotherAugment"))
225 .withValue("1").build())
228 .withNodeIdentifier(getNodeIdentifier("deepChoice"))
230 Builders.leafBuilder()
232 getNodeIdentifier("deepLeafc1"))
233 .withValue("1").build()).build())
234 .build()).build()).build());
239 private static NodeIdentifier getNodeIdentifier(final String localName) {
240 return new NodeIdentifier(QName.create(URI.create(NAMESPACE), REVISION, localName));
243 private static AugmentationIdentifier getAugmentIdentifier(final String... childNames) {
244 final Set<QName> qn = new HashSet<>();
246 for (final String childName : childNames) {
247 qn.add(getNodeIdentifier(childName).getNodeType());
250 return new AugmentationIdentifier(qn);
253 public NormalizedNodeXmlTranslationTest(final String yangPath, final String xmlPath,
254 final ContainerNode expectedNode) {
255 this.schema = YangParserTestUtils.parseYangResource(yangPath);
256 this.xmlPath = xmlPath;
257 this.containerNode = (ContainerSchemaNode) getSchemaNode(schema, "test", "container");
258 this.expectedNode = expectedNode;
261 private final ContainerNode expectedNode;
262 private final ContainerSchemaNode containerNode;
263 private final String xmlPath;
266 public void testTranslation() throws Exception {
267 final InputStream resourceAsStream = XmlToNormalizedNodesTest.class.getResourceAsStream(xmlPath);
269 final XMLInputFactory factory = XMLInputFactory.newInstance();
270 final XMLStreamReader reader = factory.createXMLStreamReader(resourceAsStream);
272 final NormalizedNodeResult result = new NormalizedNodeResult();
273 final NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result);
275 final XmlParserStream xmlParser = XmlParserStream.create(streamWriter, schema, containerNode);
276 xmlParser.parse(reader);
278 final NormalizedNode<?, ?> built = result.getResult();
279 assertNotNull(built);
281 if (expectedNode != null) {
282 org.junit.Assert.assertEquals(expectedNode, built);
285 final Document document = UntrustedXML.newDocumentBuilder().newDocument();
286 final DOMResult domResult = new DOMResult(document);
288 final XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
289 outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
291 final XMLStreamWriter xmlStreamWriter = outputFactory.createXMLStreamWriter(domResult);
293 final NormalizedNodeStreamWriter xmlNormalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter
294 .create(xmlStreamWriter, schema);
296 final NormalizedNodeWriter normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(
297 xmlNormalizedNodeStreamWriter);
299 normalizedNodeWriter.write(built);
301 final Document doc = loadDocument(xmlPath);
303 XMLUnit.setIgnoreWhitespace(true);
304 XMLUnit.setIgnoreComments(true);
305 XMLUnit.setIgnoreAttributeOrder(true);
306 XMLUnit.setNormalize(true);
308 final String expectedXml = toString(doc.getDocumentElement());
309 final String serializedXml = toString(domResult.getNode());
311 final Diff diff = new Diff(expectedXml, serializedXml);
312 diff.overrideDifferenceListener(new IgnoreTextAndAttributeValuesDifferenceListener());
313 diff.overrideElementQualifier(new ElementNameAndTextQualifier());
315 // FIXME the comparison cannot be performed, since the qualifiers supplied by XMlUnit do not work correctly in
317 // We need to implement custom qualifier so that the element ordering does not mess the DIFF
318 // dd.overrideElementQualifier(new MultiLevelElementNameAndTextQualifier(100, true));
319 // assertTrue(dd.toString(), dd.similar());
321 //new XMLTestCase() {}.assertXMLEqual(diff, true);
324 private static Document loadDocument(final String xmlPath) throws IOException, SAXException {
325 final InputStream resourceAsStream = NormalizedNodeXmlTranslationTest.class.getResourceAsStream(xmlPath);
326 return requireNonNull(readXmlToDocument(resourceAsStream));
329 private static Document readXmlToDocument(final InputStream xmlContent) throws IOException, SAXException {
330 final Document doc = UntrustedXML.newDocumentBuilder().parse(xmlContent);
331 doc.getDocumentElement().normalize();
335 private static String toString(final Node xml) {
337 final Transformer transformer = TransformerFactory.newInstance().newTransformer();
338 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
339 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
341 final StreamResult result = new StreamResult(new StringWriter());
342 final DOMSource source = new DOMSource(xml);
343 transformer.transform(source, result);
345 return result.getWriter().toString();
346 } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
347 throw new RuntimeException("Unable to serialize xml element " + xml, e);
351 private static DataSchemaNode getSchemaNode(final SchemaContext context, final String moduleName,
352 final String childNodeName) {
353 for (Module module : context.getModules()) {
354 if (module.getName().equals(moduleName)) {
355 DataSchemaNode found = findChildNode(module.getChildNodes(), childNodeName);
356 checkState(found != null, "Unable to find %s", childNodeName);
360 throw new IllegalStateException("Unable to find child node " + childNodeName);
363 private static DataSchemaNode findChildNode(final Iterable<DataSchemaNode> children, final String name) {
364 List<DataNodeContainer> containers = new ArrayList<>();
366 for (DataSchemaNode dataSchemaNode : children) {
367 if (dataSchemaNode.getQName().getLocalName().equals(name)) {
368 return dataSchemaNode;
370 if (dataSchemaNode instanceof DataNodeContainer) {
371 containers.add((DataNodeContainer) dataSchemaNode);
372 } else if (dataSchemaNode instanceof ChoiceSchemaNode) {
373 containers.addAll(((ChoiceSchemaNode) dataSchemaNode).getCases());
377 for (DataNodeContainer container : containers) {
378 DataSchemaNode retVal = findChildNode(container.getChildNodes(), name);
379 if (retVal != null) {