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 org.junit.Assert.assertNotNull;
12 import static org.opendaylight.yangtools.yang.data.impl.schema.Builders.augmentationBuilder;
13 import static org.opendaylight.yangtools.yang.data.impl.schema.Builders.choiceBuilder;
14 import static org.opendaylight.yangtools.yang.data.impl.schema.Builders.containerBuilder;
15 import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.leafNode;
17 import com.google.common.base.Preconditions;
18 import com.google.common.collect.Lists;
19 import com.google.common.collect.Maps;
20 import com.google.common.collect.Sets;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.StringWriter;
25 import java.text.ParseException;
26 import java.text.SimpleDateFormat;
27 import java.util.Arrays;
28 import java.util.Collection;
29 import java.util.Date;
30 import java.util.List;
33 import javax.xml.parsers.DocumentBuilder;
34 import javax.xml.parsers.DocumentBuilderFactory;
35 import javax.xml.parsers.ParserConfigurationException;
36 import javax.xml.stream.XMLInputFactory;
37 import javax.xml.stream.XMLOutputFactory;
38 import javax.xml.stream.XMLStreamReader;
39 import javax.xml.stream.XMLStreamWriter;
40 import javax.xml.transform.OutputKeys;
41 import javax.xml.transform.Transformer;
42 import javax.xml.transform.TransformerException;
43 import javax.xml.transform.TransformerFactory;
44 import javax.xml.transform.TransformerFactoryConfigurationError;
45 import javax.xml.transform.dom.DOMResult;
46 import javax.xml.transform.dom.DOMSource;
47 import javax.xml.transform.stream.StreamResult;
48 import org.custommonkey.xmlunit.Diff;
49 import org.custommonkey.xmlunit.ElementNameAndTextQualifier;
50 import org.custommonkey.xmlunit.IgnoreTextAndAttributeValuesDifferenceListener;
51 import org.custommonkey.xmlunit.XMLUnit;
52 import org.junit.Test;
53 import org.junit.runner.RunWith;
54 import org.junit.runners.Parameterized;
55 import org.opendaylight.yangtools.yang.common.QName;
56 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
57 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
58 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
62 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
63 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
64 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
65 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
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.parser.spi.meta.ReactorException;
80 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
81 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
82 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangStatementSourceImpl;
83 import org.w3c.dom.Document;
84 import org.w3c.dom.Node;
85 import org.xml.sax.SAXException;
87 @RunWith(Parameterized.class)
88 public class NormalizedNodeXmlTranslationTest {
89 private final SchemaContext schema;
91 @Parameterized.Parameters()
92 public static Collection<Object[]> data() {
93 return Arrays.asList(new Object[][] {
94 { "/schema/augment_choice_hell.yang", "/schema/augment_choice_hell_ok.xml", augmentChoiceHell() },
95 { "/schema/augment_choice_hell.yang", "/schema/augment_choice_hell_ok2.xml", null },
96 { "/schema/augment_choice_hell.yang", "/schema/augment_choice_hell_ok3.xml", augmentChoiceHell2() },
97 { "/schema/test.yang", "/schema/simple.xml", null },
98 { "/schema/test.yang", "/schema/simple2.xml", null },
99 // TODO check attributes
100 { "/schema/test.yang", "/schema/simple_xml_with_attributes.xml", withAttributes() }
104 private static final String NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:test";
105 private static final Date revision;
108 revision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-03-13");
109 } catch (final ParseException e) {
110 throw new RuntimeException(e);
114 private static ContainerNode augmentChoiceHell2() {
115 final YangInstanceIdentifier.NodeIdentifier container = getNodeIdentifier("container");
116 final QName augmentChoice1QName = QName.create(container.getNodeType(), "augment-choice1");
117 final QName augmentChoice2QName = QName.create(augmentChoice1QName, "augment-choice2");
118 final QName containerQName = QName.create(augmentChoice1QName, "case11-choice-case-container");
119 final QName leafQName = QName.create(augmentChoice1QName, "case11-choice-case-leaf");
121 final YangInstanceIdentifier.AugmentationIdentifier aug1Id = new YangInstanceIdentifier.AugmentationIdentifier(
122 Sets.newHashSet(augmentChoice1QName));
123 final YangInstanceIdentifier.AugmentationIdentifier aug2Id = new YangInstanceIdentifier.AugmentationIdentifier(
124 Sets.newHashSet(augmentChoice2QName));
125 final YangInstanceIdentifier.NodeIdentifier augmentChoice1Id = new YangInstanceIdentifier.NodeIdentifier(
126 augmentChoice1QName);
127 final YangInstanceIdentifier.NodeIdentifier augmentChoice2Id = new YangInstanceIdentifier.NodeIdentifier(
128 augmentChoice2QName);
129 final YangInstanceIdentifier.NodeIdentifier containerId = new YangInstanceIdentifier.NodeIdentifier(
132 return containerBuilder().withNodeIdentifier(container)
133 .withChild(augmentationBuilder().withNodeIdentifier(aug1Id)
134 .withChild(choiceBuilder().withNodeIdentifier(augmentChoice1Id)
135 .withChild(augmentationBuilder().withNodeIdentifier(aug2Id)
136 .withChild(choiceBuilder().withNodeIdentifier(augmentChoice2Id)
137 .withChild(containerBuilder().withNodeIdentifier(containerId)
138 .withChild(leafNode(leafQName, "leaf-value"))
146 private static ContainerNode withAttributes() {
147 final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> b = containerBuilder();
148 b.withNodeIdentifier(getNodeIdentifier("container"));
150 final CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = Builders.mapBuilder().withNodeIdentifier(
151 getNodeIdentifier("list"));
153 final Map<QName, Object> predicates = Maps.newHashMap();
154 predicates.put(getNodeIdentifier("uint32InList").getNodeType(), 3L);
156 final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> list1Builder = Builders
157 .mapEntryBuilder().withNodeIdentifier(
158 new YangInstanceIdentifier.NodeIdentifierWithPredicates(
159 getNodeIdentifier("list").getNodeType(), predicates));
160 final NormalizedNodeBuilder<YangInstanceIdentifier.NodeIdentifier, Object, LeafNode<Object>> uint32InListBuilder = Builders
161 .leafBuilder().withNodeIdentifier(getNodeIdentifier("uint32InList"));
163 list1Builder.withChild(uint32InListBuilder.withValue(3L).build());
165 listBuilder.withChild(list1Builder.build());
166 b.withChild(listBuilder.build());
168 final NormalizedNodeBuilder<YangInstanceIdentifier.NodeIdentifier, Object, LeafNode<Object>> booleanBuilder = Builders
169 .leafBuilder().withNodeIdentifier(getNodeIdentifier("boolean"));
170 booleanBuilder.withValue(false);
171 b.withChild(booleanBuilder.build());
173 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> leafListBuilder = Builders.leafSetBuilder()
174 .withNodeIdentifier(getNodeIdentifier("leafList"));
176 final NormalizedNodeBuilder<YangInstanceIdentifier.NodeWithValue, Object, LeafSetEntryNode<Object>> leafList1Builder = Builders
177 .leafSetEntryBuilder().withNodeIdentifier(
178 new YangInstanceIdentifier.NodeWithValue(getNodeIdentifier("leafList").getNodeType(), "a"));
180 leafList1Builder.withValue("a");
182 leafListBuilder.withChild(leafList1Builder.build());
183 b.withChild(leafListBuilder.build());
188 private static ContainerNode augmentChoiceHell() {
190 final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> b = containerBuilder();
191 b.withNodeIdentifier(getNodeIdentifier("container"));
193 b.withChild(choiceBuilder()
194 .withNodeIdentifier(getNodeIdentifier("ch2"))
196 Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("c2Leaf")).withValue("2").build())
199 .withNodeIdentifier(getNodeIdentifier("c2DeepChoice"))
201 Builders.leafBuilder()
202 .withNodeIdentifier(getNodeIdentifier("c2DeepChoiceCase1Leaf2"))
203 .withValue("2").build()).build()).build());
205 b.withChild(choiceBuilder()
206 .withNodeIdentifier(getNodeIdentifier("ch3"))
208 Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("c3Leaf")).withValue("3").build())
211 b.withChild(augmentationBuilder()
212 .withNodeIdentifier(getAugmentIdentifier("augLeaf"))
214 Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("augLeaf")).withValue("augment")
217 b.withChild(augmentationBuilder()
218 .withNodeIdentifier(getAugmentIdentifier("ch"))
221 .withNodeIdentifier(getNodeIdentifier("ch"))
223 Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("c1Leaf"))
224 .withValue("1").build())
226 augmentationBuilder()
228 getAugmentIdentifier("c1Leaf_AnotherAugment", "deepChoice"))
230 Builders.leafBuilder()
232 getNodeIdentifier("c1Leaf_AnotherAugment"))
233 .withValue("1").build())
236 .withNodeIdentifier(getNodeIdentifier("deepChoice"))
238 Builders.leafBuilder()
240 getNodeIdentifier("deepLeafc1"))
241 .withValue("1").build()).build())
242 .build()).build()).build());
247 private static YangInstanceIdentifier.NodeIdentifier getNodeIdentifier(final String localName) {
248 return new YangInstanceIdentifier.NodeIdentifier(QName.create(URI.create(NAMESPACE), revision, localName));
251 private static YangInstanceIdentifier.AugmentationIdentifier getAugmentIdentifier(final String... childNames) {
252 final Set<QName> qn = Sets.newHashSet();
254 for (final String childName : childNames) {
255 qn.add(getNodeIdentifier(childName).getNodeType());
258 return new YangInstanceIdentifier.AugmentationIdentifier(qn);
261 public NormalizedNodeXmlTranslationTest(final String yangPath, final String xmlPath,
262 final ContainerNode expectedNode) throws ReactorException {
263 this.schema = parseTestSchema(yangPath);
264 this.xmlPath = xmlPath;
265 this.containerNode = (ContainerSchemaNode) getSchemaNode(schema, "test", "container");
266 this.expectedNode = expectedNode;
269 private final ContainerNode expectedNode;
270 private final ContainerSchemaNode containerNode;
271 private final String xmlPath;
273 private SchemaContext parseTestSchema(final String yangPath) throws ReactorException {
274 final CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
275 reactor.addSource(new YangStatementSourceImpl(yangPath, false));
276 return reactor.buildEffective();
280 public void testTranslation() throws Exception {
281 final InputStream resourceAsStream = XmlToNormalizedNodesTest.class.getResourceAsStream(xmlPath);
283 final XMLInputFactory factory = XMLInputFactory.newInstance();
284 final XMLStreamReader reader = factory.createXMLStreamReader(resourceAsStream);
286 final NormalizedNodeResult result = new NormalizedNodeResult();
287 final NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result);
289 final XmlParserStream xmlParser = XmlParserStream.create(streamWriter, schema);
290 xmlParser.parse(reader);
292 final NormalizedNode<?, ?> built = result.getResult();
293 assertNotNull(built);
295 if (expectedNode != null) {
296 org.junit.Assert.assertEquals(expectedNode, built);
299 final Document document = XmlDocumentUtils.getDocument();
300 final DOMResult domResult = new DOMResult(document);
302 final XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
303 outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
305 final XMLStreamWriter xmlStreamWriter = outputFactory.createXMLStreamWriter(domResult);
307 final NormalizedNodeStreamWriter xmlNormalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter
308 .create(xmlStreamWriter, schema);
310 final NormalizedNodeWriter normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter
311 (xmlNormalizedNodeStreamWriter);
313 normalizedNodeWriter.write(built);
315 final Document doc = loadDocument(xmlPath);
317 XMLUnit.setIgnoreWhitespace(true);
318 XMLUnit.setIgnoreComments(true);
319 XMLUnit.setIgnoreAttributeOrder(true);
320 XMLUnit.setNormalize(true);
322 final String expectedXml = toString(doc.getDocumentElement().getElementsByTagName("container").item(0));
323 final String serializedXml = toString(domResult.getNode());
325 final Diff diff = new Diff(expectedXml, serializedXml);
326 diff.overrideDifferenceListener(new IgnoreTextAndAttributeValuesDifferenceListener());
327 diff.overrideElementQualifier(new ElementNameAndTextQualifier());
329 // FIXME the comparison cannot be performed, since the qualifiers supplied by XMlUnit do not work correctly in
331 // We need to implement custom qualifier so that the element ordering does not mess the DIFF
332 // dd.overrideElementQualifier(new MultiLevelElementNameAndTextQualifier(100, true));
333 // assertTrue(dd.toString(), dd.similar());
335 //new XMLTestCase() {}.assertXMLEqual(diff, true);
338 static final XMLOutputFactory XML_FACTORY;
340 XML_FACTORY = XMLOutputFactory.newFactory();
341 XML_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, false);
344 private static Document loadDocument(final String xmlPath) throws IOException, SAXException {
345 final InputStream resourceAsStream = NormalizedNodeXmlTranslationTest.class.getResourceAsStream(xmlPath);
347 final Document currentConfigElement = readXmlToDocument(resourceAsStream);
348 Preconditions.checkNotNull(currentConfigElement);
349 return currentConfigElement;
352 private static final DocumentBuilderFactory BUILDERFACTORY;
355 final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
356 factory.setNamespaceAware(true);
357 factory.setCoalescing(true);
358 factory.setIgnoringElementContentWhitespace(true);
359 factory.setIgnoringComments(true);
360 BUILDERFACTORY = factory;
363 private static Document readXmlToDocument(final InputStream xmlContent) throws IOException, SAXException {
364 final DocumentBuilder dBuilder;
366 dBuilder = BUILDERFACTORY.newDocumentBuilder();
367 } catch (final ParserConfigurationException e) {
368 throw new RuntimeException("Failed to parse XML document", e);
370 final Document doc = dBuilder.parse(xmlContent);
372 doc.getDocumentElement().normalize();
376 private static String toString(final Node xml) {
378 final Transformer transformer = TransformerFactory.newInstance().newTransformer();
379 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
380 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
382 final StreamResult result = new StreamResult(new StringWriter());
383 final DOMSource source = new DOMSource(xml);
384 transformer.transform(source, result);
386 return result.getWriter().toString();
387 } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
388 throw new RuntimeException("Unable to serialize xml element " + xml, e);
392 private static DataSchemaNode getSchemaNode(final SchemaContext context, final String moduleName,
393 final String childNodeName) {
394 for (Module module : context.getModules()) {
395 if (module.getName().equals(moduleName)) {
396 DataSchemaNode found = findChildNode(module.getChildNodes(), childNodeName);
397 Preconditions.checkState(found != null, "Unable to find %s", childNodeName);
401 throw new IllegalStateException("Unable to find child node " + childNodeName);
404 private static DataSchemaNode findChildNode(final Iterable<DataSchemaNode> children, final String name) {
405 List<DataNodeContainer> containers = Lists.newArrayList();
407 for (DataSchemaNode dataSchemaNode : children) {
408 if (dataSchemaNode.getQName().getLocalName().equals(name)) {
409 return dataSchemaNode;
411 if (dataSchemaNode instanceof DataNodeContainer) {
412 containers.add((DataNodeContainer) dataSchemaNode);
413 } else if (dataSchemaNode instanceof ChoiceSchemaNode) {
414 containers.addAll(((ChoiceSchemaNode) dataSchemaNode).getCases());
418 for (DataNodeContainer container : containers) {
419 DataSchemaNode retVal = findChildNode(container.getChildNodes(), name);
420 if (retVal != null) {