Abstract infrastructure for normalized nodes translation.
[yangtools.git] / yang / yang-data-impl / src / test / java / org / opendaylight / yangtools / yang / data / impl / schema / transform / dom / serializer / NormalizedNodeXmlTranslationTest.java
1 /*
2  * Copyright (c) 2013 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 package org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.serializer;
9
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.io.StringWriter;
13 import java.net.URI;
14 import java.text.ParseException;
15 import java.text.SimpleDateFormat;
16 import java.util.Arrays;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.Date;
20 import java.util.List;
21 import java.util.Set;
22
23 import javax.xml.parsers.DocumentBuilder;
24 import javax.xml.parsers.DocumentBuilderFactory;
25 import javax.xml.parsers.ParserConfigurationException;
26 import javax.xml.transform.OutputKeys;
27 import javax.xml.transform.Transformer;
28 import javax.xml.transform.TransformerException;
29 import javax.xml.transform.TransformerFactory;
30 import javax.xml.transform.TransformerFactoryConfigurationError;
31 import javax.xml.transform.dom.DOMSource;
32 import javax.xml.transform.stream.StreamResult;
33
34 import org.junit.Assert;
35 import org.junit.Test;
36 import org.junit.runner.RunWith;
37 import org.junit.runners.Parameterized;
38 import org.opendaylight.yangtools.yang.common.QName;
39 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
40 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
41 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
42 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
43 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedDataBuilderTest;
44 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
45 import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
46 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.DomUtils;
47 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.ContainerNodeDomParser;
48 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.Module;
50 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
51 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import org.w3c.dom.Document;
55 import org.w3c.dom.Element;
56 import org.xml.sax.SAXException;
57
58 import com.google.common.base.Function;
59 import com.google.common.base.Preconditions;
60 import com.google.common.collect.Collections2;
61 import com.google.common.collect.Lists;
62 import com.google.common.collect.Sets;
63
64 @RunWith(Parameterized.class)
65 public class NormalizedNodeXmlTranslationTest {
66     private static final Logger logger = LoggerFactory.getLogger(NormalizedNodeXmlTranslationTest.class);
67
68     @Parameterized.Parameters()
69     public static Collection<Object[]> data() {
70         return Arrays.asList(new Object[][]{
71                 {"augment_choice_hell.yang", "augment_choice_hell_ok.xml", augmentChoiceHell()},
72                 {"augment_choice_hell.yang", "augment_choice_hell_ok2.xml", null},
73                 {"test.yang", "simple.xml", null},
74                 {"test.yang", "simple2.xml", null}
75         });
76     }
77
78     public static final String NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:test";
79     private static Date revision;
80     static {
81         try {
82             revision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-03-13");
83         } catch (ParseException e) {
84             throw new RuntimeException(e);
85         }
86     }
87
88     private static ContainerNode augmentChoiceHell() {
89
90         DataContainerNodeBuilder<InstanceIdentifier.NodeIdentifier, ContainerNode> b = Builders.containerBuilder();
91         b.withNodeIdentifier(getNodeIdentifier("container"));
92
93         b.withChild(
94                 Builders.choiceBuilder().withNodeIdentifier(getNodeIdentifier("ch2"))
95                         .withChild(Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("c2Leaf")).withValue("2").build())
96                         .withChild(
97                                 Builders.choiceBuilder().withNodeIdentifier(getNodeIdentifier("c2DeepChoice"))
98                                         .withChild(Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("c2DeepChoiceCase1Leaf2")).withValue("2").build())
99                                         .build()
100                         )
101                         .build()
102         );
103
104         b.withChild(
105                 Builders.choiceBuilder().withNodeIdentifier(getNodeIdentifier("ch3")).withChild(
106                         Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("c3Leaf")).withValue("3").build())
107                 .build());
108
109         b.withChild(
110                 Builders.augmentationBuilder().withNodeIdentifier(getAugmentIdentifier("augLeaf")).withChild(
111                         Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("augLeaf")).withValue("augment").build())
112                 .build());
113
114         b.withChild(
115                 Builders.augmentationBuilder().withNodeIdentifier(getAugmentIdentifier("ch")).withChild(
116                         Builders.choiceBuilder().withNodeIdentifier(getNodeIdentifier("ch"))
117                                 .withChild(
118                                         Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("c1Leaf")).withValue("1").build())
119                                 .withChild(
120                                         Builders.augmentationBuilder().withNodeIdentifier(getAugmentIdentifier("c1Leaf_AnotherAugment", "deepChoice"))
121                                                 .withChild(
122                                                         Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("c1Leaf_AnotherAugment")).withValue("1").build())
123                                                 .withChild(
124                                                         Builders.choiceBuilder().withNodeIdentifier(getNodeIdentifier("deepChoice"))
125                                                                 .withChild(
126                                                                         Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("deepLeafc1")).withValue("1").build()
127                                                                 ).build()
128                                                 ).build()
129                                 ).build()
130         ).build());
131
132         return b.build();
133     }
134
135     private static InstanceIdentifier.NodeIdentifier getNodeIdentifier(String localName) {
136         return new InstanceIdentifier.NodeIdentifier(new QName(URI.create(NAMESPACE), revision, localName));
137     }
138
139     public static InstanceIdentifier.AugmentationIdentifier getAugmentIdentifier(String... childNames) {
140         Set<QName> qn = Sets.newHashSet();
141
142         for (String childName : childNames) {
143             qn.add(getNodeIdentifier(childName).getNodeType());
144         }
145
146         return new InstanceIdentifier.AugmentationIdentifier(null, qn);
147     }
148
149     public NormalizedNodeXmlTranslationTest(String yangPath, String xmlPath, ContainerNode expectedNode) {
150         this.schema = parseTestSchema(yangPath);
151         this.xmlPath = xmlPath;
152         this.containerNode = (ContainerSchemaNode) NormalizedDataBuilderTest.getSchemaNode(schema, "test", "container");
153         this.expectedNode = expectedNode;
154     }
155
156     private final ContainerNode expectedNode;
157     private final ContainerSchemaNode containerNode;
158     private final SchemaContext schema;
159     private final String xmlPath;
160
161
162     SchemaContext parseTestSchema(String... yangPath) {
163         YangParserImpl yangParserImpl = new YangParserImpl();
164         Set<Module> modules = yangParserImpl.parseYangModelsFromStreams(getTestYangs(yangPath));
165         return yangParserImpl.resolveSchemaContext(modules);
166     }
167
168     List<InputStream> getTestYangs(String... yangPaths) {
169
170         return Lists.newArrayList(Collections2.transform(Lists.newArrayList(yangPaths),
171                 new Function<String, InputStream>() {
172                     @Override
173                     public InputStream apply(String input) {
174                         InputStream resourceAsStream = NormalizedDataBuilderTest.class.getResourceAsStream(input);
175                         Preconditions.checkNotNull(resourceAsStream, "File %s was null", resourceAsStream);
176                         return resourceAsStream;
177                     }
178                 }));
179     }
180
181     @Test
182     public void testTranslation() throws Exception {
183         Document doc = loadDocument(xmlPath);
184
185         ContainerNode built = new ContainerNodeDomParser(DomUtils.defaultValueCodecProvider()).parse(
186                 Collections.singletonList(doc.getDocumentElement()), containerNode);
187
188         if (expectedNode != null)
189             junit.framework.Assert.assertEquals(expectedNode, built);
190
191         logger.info("{}", built);
192
193         final Document newDoc = XmlDocumentUtils.getDocument();
194         final NodeSerializerDispatcher<Element> dispatcher = new DomNodeSerializerDispatcher(newDoc, DomUtils.defaultValueCodecProvider());
195
196         Iterable<Element> els = new ContainerNodeDomSerializer(newDoc,
197                 dispatcher).serialize(containerNode, built);
198
199         Element el = els.iterator().next();
200
201         Assert.assertEquals(toString(doc.getDocumentElement()).replaceAll("\\s*", ""),
202                 toString(el).replaceAll("\\s*", ""));
203     }
204
205
206     private Document loadDocument(String xmlPath) throws Exception {
207         InputStream resourceAsStream = NormalizedDataBuilderTest.class.getResourceAsStream(xmlPath);
208
209         Document currentConfigElement = readXmlToDocument(resourceAsStream);
210         Preconditions.checkNotNull(currentConfigElement);
211         return currentConfigElement;
212     }
213
214     private static final DocumentBuilderFactory BUILDERFACTORY;
215
216     static {
217         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
218         factory.setNamespaceAware(true);
219         factory.setCoalescing(true);
220         factory.setIgnoringElementContentWhitespace(true);
221         factory.setIgnoringComments(true);
222         BUILDERFACTORY = factory;
223     }
224
225     private Document readXmlToDocument(InputStream xmlContent) throws IOException, SAXException {
226         DocumentBuilder dBuilder;
227         try {
228             dBuilder = BUILDERFACTORY.newDocumentBuilder();
229         } catch (ParserConfigurationException e) {
230             throw new RuntimeException("Failed to parse XML document", e);
231         }
232         Document doc = dBuilder.parse(xmlContent);
233
234         doc.getDocumentElement().normalize();
235         return doc;
236     }
237
238     public static String toString(Element xml) {
239         try {
240             Transformer transformer = TransformerFactory.newInstance().newTransformer();
241             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
242
243             StreamResult result = new StreamResult(new StringWriter());
244             DOMSource source = new DOMSource(xml);
245             transformer.transform(source, result);
246
247             return result.getWriter().toString();
248         } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
249             throw new RuntimeException("Unable to serialize xml element " + xml, e);
250         }
251     }
252 }