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.XMLOutputFactory;
31 import javax.xml.stream.XMLStreamReader;
32 import javax.xml.stream.XMLStreamWriter;
33 import javax.xml.transform.OutputKeys;
34 import javax.xml.transform.Transformer;
35 import javax.xml.transform.TransformerException;
36 import javax.xml.transform.TransformerFactory;
37 import javax.xml.transform.TransformerFactoryConfigurationError;
38 import javax.xml.transform.dom.DOMResult;
39 import javax.xml.transform.dom.DOMSource;
40 import javax.xml.transform.stream.StreamResult;
41 import org.custommonkey.xmlunit.Diff;
42 import org.custommonkey.xmlunit.ElementNameAndTextQualifier;
43 import org.custommonkey.xmlunit.IgnoreTextAndAttributeValuesDifferenceListener;
44 import org.custommonkey.xmlunit.XMLUnit;
45 import org.junit.Test;
46 import org.junit.runner.RunWith;
47 import org.junit.runners.Parameterized;
48 import org.opendaylight.yangtools.util.xml.UntrustedXML;
49 import org.opendaylight.yangtools.yang.common.QName;
50 import org.opendaylight.yangtools.yang.common.Revision;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
55 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
58 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
62 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
63 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
64 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
65 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
66 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
67 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
68 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
69 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
70 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
71 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
72 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
73 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
74 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
75 import org.opendaylight.yangtools.yang.model.api.Module;
76 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
77 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
78 import org.w3c.dom.Document;
79 import org.w3c.dom.Node;
80 import org.xml.sax.SAXException;
82 @RunWith(Parameterized.class)
83 public class NormalizedNodeXmlTranslationTest {
84 private final SchemaContext schema;
86 @Parameterized.Parameters()
87 public static Collection<Object[]> data() {
88 return Arrays.asList(new Object[][] {
89 { "/schema/augment_choice_hell.yang", "/schema/augment_choice_hell_ok.xml", augmentChoiceHell() },
90 { "/schema/augment_choice_hell.yang", "/schema/augment_choice_hell_ok2.xml", null },
91 { "/schema/augment_choice_hell.yang", "/schema/augment_choice_hell_ok3.xml", augmentChoiceHell2() },
92 { "/schema/test.yang", "/schema/simple.xml", null },
93 { "/schema/test.yang", "/schema/simple2.xml", null },
94 // TODO check attributes
95 { "/schema/test.yang", "/schema/simple_xml_with_attributes.xml", withAttributes() }
99 private static final String NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:test";
100 private static final Revision REVISION = Revision.of("2014-03-13");
102 static final XMLOutputFactory XML_FACTORY;
105 XML_FACTORY = XMLOutputFactory.newFactory();
106 XML_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.FALSE);
109 private static ContainerNode augmentChoiceHell2() {
110 final NodeIdentifier container = getNodeIdentifier("container");
111 final QName augmentChoice1QName = QName.create(container.getNodeType(), "augment-choice1");
112 final QName augmentChoice2QName = QName.create(augmentChoice1QName, "augment-choice2");
113 final QName containerQName = QName.create(augmentChoice1QName, "case11-choice-case-container");
114 final QName leafQName = QName.create(augmentChoice1QName, "case11-choice-case-leaf");
116 final AugmentationIdentifier aug1Id = new AugmentationIdentifier(ImmutableSet.of(augmentChoice1QName));
117 final AugmentationIdentifier aug2Id = new AugmentationIdentifier(ImmutableSet.of(augmentChoice2QName));
118 final NodeIdentifier augmentChoice1Id = new NodeIdentifier(augmentChoice1QName);
119 final NodeIdentifier augmentChoice2Id = new NodeIdentifier(augmentChoice2QName);
120 final NodeIdentifier containerId = new NodeIdentifier(containerQName);
122 return containerBuilder().withNodeIdentifier(container)
123 .withChild(augmentationBuilder().withNodeIdentifier(aug1Id)
124 .withChild(choiceBuilder().withNodeIdentifier(augmentChoice1Id)
125 .withChild(augmentationBuilder().withNodeIdentifier(aug2Id)
126 .withChild(choiceBuilder().withNodeIdentifier(augmentChoice2Id)
127 .withChild(containerBuilder().withNodeIdentifier(containerId)
128 .withChild(leafNode(leafQName, "leaf-value"))
136 private static ContainerNode withAttributes() {
137 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> b = containerBuilder();
138 b.withNodeIdentifier(getNodeIdentifier("container"));
140 final CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = Builders.mapBuilder().withNodeIdentifier(
141 getNodeIdentifier("list"));
143 final Map<QName, Object> predicates = new HashMap<>();
144 predicates.put(getNodeIdentifier("uint32InList").getNodeType(), 3L);
146 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> list1Builder = Builders
147 .mapEntryBuilder().withNodeIdentifier(
148 new NodeIdentifierWithPredicates(
149 getNodeIdentifier("list").getNodeType(), predicates));
150 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> uint32InListBuilder = Builders
151 .leafBuilder().withNodeIdentifier(getNodeIdentifier("uint32InList"));
153 list1Builder.withChild(uint32InListBuilder.withValue(3L).build());
155 listBuilder.withChild(list1Builder.build());
156 b.withChild(listBuilder.build());
158 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> booleanBuilder = Builders
159 .leafBuilder().withNodeIdentifier(getNodeIdentifier("boolean"));
160 booleanBuilder.withValue(Boolean.FALSE);
161 b.withChild(booleanBuilder.build());
163 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> leafListBuilder = Builders.leafSetBuilder()
164 .withNodeIdentifier(getNodeIdentifier("leafList"));
166 final NormalizedNodeBuilder<NodeWithValue, Object, LeafSetEntryNode<Object>> leafList1Builder = Builders
167 .leafSetEntryBuilder().withNodeIdentifier(
168 new NodeWithValue(getNodeIdentifier("leafList").getNodeType(), "a"));
170 leafList1Builder.withValue("a");
172 leafListBuilder.withChild(leafList1Builder.build());
173 b.withChild(leafListBuilder.build());
178 private static ContainerNode augmentChoiceHell() {
180 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> b = containerBuilder();
181 b.withNodeIdentifier(getNodeIdentifier("container"));
183 b.withChild(choiceBuilder()
184 .withNodeIdentifier(getNodeIdentifier("ch2"))
186 Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("c2Leaf")).withValue("2").build())
189 .withNodeIdentifier(getNodeIdentifier("c2DeepChoice"))
191 Builders.leafBuilder()
192 .withNodeIdentifier(getNodeIdentifier("c2DeepChoiceCase1Leaf2"))
193 .withValue("2").build()).build()).build());
195 b.withChild(choiceBuilder()
196 .withNodeIdentifier(getNodeIdentifier("ch3"))
198 Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("c3Leaf")).withValue("3").build())
201 b.withChild(augmentationBuilder()
202 .withNodeIdentifier(getAugmentIdentifier("augLeaf"))
204 Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("augLeaf")).withValue("augment")
207 b.withChild(augmentationBuilder()
208 .withNodeIdentifier(getAugmentIdentifier("ch"))
211 .withNodeIdentifier(getNodeIdentifier("ch"))
213 Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("c1Leaf"))
214 .withValue("1").build())
216 augmentationBuilder()
218 getAugmentIdentifier("c1Leaf_AnotherAugment", "deepChoice"))
220 Builders.leafBuilder()
222 getNodeIdentifier("c1Leaf_AnotherAugment"))
223 .withValue("1").build())
226 .withNodeIdentifier(getNodeIdentifier("deepChoice"))
228 Builders.leafBuilder()
230 getNodeIdentifier("deepLeafc1"))
231 .withValue("1").build()).build())
232 .build()).build()).build());
237 private static NodeIdentifier getNodeIdentifier(final String localName) {
238 return new NodeIdentifier(QName.create(URI.create(NAMESPACE), REVISION, localName));
241 private static AugmentationIdentifier getAugmentIdentifier(final String... childNames) {
242 final Set<QName> qn = new HashSet<>();
244 for (final String childName : childNames) {
245 qn.add(getNodeIdentifier(childName).getNodeType());
248 return new AugmentationIdentifier(qn);
251 public NormalizedNodeXmlTranslationTest(final String yangPath, final String xmlPath,
252 final ContainerNode expectedNode) {
253 this.schema = YangParserTestUtils.parseYangResource(yangPath);
254 this.xmlPath = xmlPath;
255 this.containerNode = (ContainerSchemaNode) getSchemaNode(schema, "test", "container");
256 this.expectedNode = expectedNode;
259 private final ContainerNode expectedNode;
260 private final ContainerSchemaNode containerNode;
261 private final String xmlPath;
264 public void testTranslation() throws Exception {
265 final InputStream resourceAsStream = XmlToNormalizedNodesTest.class.getResourceAsStream(xmlPath);
267 final XMLStreamReader reader = UntrustedXML.createXMLStreamReader(resourceAsStream);
269 final NormalizedNodeResult result = new NormalizedNodeResult();
270 final NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result);
272 final XmlParserStream xmlParser = XmlParserStream.create(streamWriter, schema, containerNode);
273 xmlParser.parse(reader);
275 final NormalizedNode<?, ?> built = result.getResult();
276 assertNotNull(built);
278 if (expectedNode != null) {
279 org.junit.Assert.assertEquals(expectedNode, built);
282 final Document document = UntrustedXML.newDocumentBuilder().newDocument();
283 final DOMResult domResult = new DOMResult(document);
285 final XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
286 outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
288 final XMLStreamWriter xmlStreamWriter = outputFactory.createXMLStreamWriter(domResult);
290 final NormalizedNodeStreamWriter xmlNormalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter
291 .create(xmlStreamWriter, schema);
293 final NormalizedNodeWriter normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(
294 xmlNormalizedNodeStreamWriter);
296 normalizedNodeWriter.write(built);
298 final Document doc = loadDocument(xmlPath);
300 XMLUnit.setIgnoreWhitespace(true);
301 XMLUnit.setIgnoreComments(true);
302 XMLUnit.setIgnoreAttributeOrder(true);
303 XMLUnit.setNormalize(true);
305 final String expectedXml = toString(doc.getDocumentElement());
306 final String serializedXml = toString(domResult.getNode());
308 final Diff diff = new Diff(expectedXml, serializedXml);
309 diff.overrideDifferenceListener(new IgnoreTextAndAttributeValuesDifferenceListener());
310 diff.overrideElementQualifier(new ElementNameAndTextQualifier());
312 // FIXME the comparison cannot be performed, since the qualifiers supplied by XMlUnit do not work correctly in
314 // We need to implement custom qualifier so that the element ordering does not mess the DIFF
315 // dd.overrideElementQualifier(new MultiLevelElementNameAndTextQualifier(100, true));
316 // assertTrue(dd.toString(), dd.similar());
318 //new XMLTestCase() {}.assertXMLEqual(diff, true);
321 private static Document loadDocument(final String xmlPath) throws IOException, SAXException {
322 final InputStream resourceAsStream = NormalizedNodeXmlTranslationTest.class.getResourceAsStream(xmlPath);
323 return requireNonNull(readXmlToDocument(resourceAsStream));
326 private static Document readXmlToDocument(final InputStream xmlContent) throws IOException, SAXException {
327 final Document doc = UntrustedXML.newDocumentBuilder().parse(xmlContent);
328 doc.getDocumentElement().normalize();
332 private static String toString(final Node xml) {
334 final Transformer transformer = TransformerFactory.newInstance().newTransformer();
335 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
336 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
338 final StreamResult result = new StreamResult(new StringWriter());
339 final DOMSource source = new DOMSource(xml);
340 transformer.transform(source, result);
342 return result.getWriter().toString();
343 } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
344 throw new RuntimeException("Unable to serialize xml element " + xml, e);
348 private static DataSchemaNode getSchemaNode(final SchemaContext context, final String moduleName,
349 final String childNodeName) {
350 for (Module module : context.getModules()) {
351 if (module.getName().equals(moduleName)) {
352 DataSchemaNode found = findChildNode(module, childNodeName);
353 checkState(found != null, "Unable to find %s", childNodeName);
357 throw new IllegalStateException("Unable to find child node " + childNodeName);
360 // FIXME: duplicate of NormalizedDataBuilderTest.findChildNode()
361 private static DataSchemaNode findChildNode(final DataNodeContainer container, final String name) {
362 for (DataSchemaNode dataSchemaNode : container.getChildNodes()) {
363 if (dataSchemaNode.getQName().getLocalName().equals(name)) {
364 return dataSchemaNode;
366 if (dataSchemaNode instanceof DataNodeContainer) {
367 DataSchemaNode retVal = findChildNode((DataNodeContainer) dataSchemaNode, name);
368 if (retVal != null) {
371 } else if (dataSchemaNode instanceof ChoiceSchemaNode) {
372 for (CaseSchemaNode caseNode : ((ChoiceSchemaNode) dataSchemaNode).getCases().values()) {
373 DataSchemaNode retVal = findChildNode(caseNode, name);
374 if (retVal != null) {