2 * Copyright (c) 2013 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
8 package org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.serializer;
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.io.StringWriter;
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;
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;
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;
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;
64 @RunWith(Parameterized.class)
65 public class NormalizedNodeXmlTranslationTest {
66 private static final Logger logger = LoggerFactory.getLogger(NormalizedNodeXmlTranslationTest.class);
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}
78 public static final String NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:test";
79 private static Date revision;
82 revision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-03-13");
83 } catch (ParseException e) {
84 throw new RuntimeException(e);
88 private static ContainerNode augmentChoiceHell() {
90 DataContainerNodeBuilder<InstanceIdentifier.NodeIdentifier, ContainerNode> b = Builders.containerBuilder();
91 b.withNodeIdentifier(getNodeIdentifier("container"));
94 Builders.choiceBuilder().withNodeIdentifier(getNodeIdentifier("ch2"))
95 .withChild(Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("c2Leaf")).withValue("2").build())
97 Builders.choiceBuilder().withNodeIdentifier(getNodeIdentifier("c2DeepChoice"))
98 .withChild(Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("c2DeepChoiceCase1Leaf2")).withValue("2").build())
105 Builders.choiceBuilder().withNodeIdentifier(getNodeIdentifier("ch3")).withChild(
106 Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("c3Leaf")).withValue("3").build())
110 Builders.augmentationBuilder().withNodeIdentifier(getAugmentIdentifier("augLeaf")).withChild(
111 Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("augLeaf")).withValue("augment").build())
115 Builders.augmentationBuilder().withNodeIdentifier(getAugmentIdentifier("ch")).withChild(
116 Builders.choiceBuilder().withNodeIdentifier(getNodeIdentifier("ch"))
118 Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("c1Leaf")).withValue("1").build())
120 Builders.augmentationBuilder().withNodeIdentifier(getAugmentIdentifier("c1Leaf_AnotherAugment", "deepChoice"))
122 Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("c1Leaf_AnotherAugment")).withValue("1").build())
124 Builders.choiceBuilder().withNodeIdentifier(getNodeIdentifier("deepChoice"))
126 Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("deepLeafc1")).withValue("1").build()
135 private static InstanceIdentifier.NodeIdentifier getNodeIdentifier(String localName) {
136 return new InstanceIdentifier.NodeIdentifier(new QName(URI.create(NAMESPACE), revision, localName));
139 public static InstanceIdentifier.AugmentationIdentifier getAugmentIdentifier(String... childNames) {
140 Set<QName> qn = Sets.newHashSet();
142 for (String childName : childNames) {
143 qn.add(getNodeIdentifier(childName).getNodeType());
146 return new InstanceIdentifier.AugmentationIdentifier(null, qn);
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;
156 private final ContainerNode expectedNode;
157 private final ContainerSchemaNode containerNode;
158 private final SchemaContext schema;
159 private final String xmlPath;
162 SchemaContext parseTestSchema(String... yangPath) {
163 YangParserImpl yangParserImpl = new YangParserImpl();
164 Set<Module> modules = yangParserImpl.parseYangModelsFromStreams(getTestYangs(yangPath));
165 return yangParserImpl.resolveSchemaContext(modules);
168 List<InputStream> getTestYangs(String... yangPaths) {
170 return Lists.newArrayList(Collections2.transform(Lists.newArrayList(yangPaths),
171 new Function<String, InputStream>() {
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;
182 public void testTranslation() throws Exception {
183 Document doc = loadDocument(xmlPath);
185 ContainerNode built = new ContainerNodeDomParser(DomUtils.defaultValueCodecProvider()).parse(
186 Collections.singletonList(doc.getDocumentElement()), containerNode);
188 if (expectedNode != null)
189 junit.framework.Assert.assertEquals(expectedNode, built);
191 logger.info("{}", built);
193 final Document newDoc = XmlDocumentUtils.getDocument();
194 final NodeSerializerDispatcher<Element> dispatcher = new DomNodeSerializerDispatcher(newDoc, DomUtils.defaultValueCodecProvider());
196 Iterable<Element> els = new ContainerNodeDomSerializer(newDoc,
197 dispatcher).serialize(containerNode, built);
199 Element el = els.iterator().next();
201 Assert.assertEquals(toString(doc.getDocumentElement()).replaceAll("\\s*", ""),
202 toString(el).replaceAll("\\s*", ""));
206 private Document loadDocument(String xmlPath) throws Exception {
207 InputStream resourceAsStream = NormalizedDataBuilderTest.class.getResourceAsStream(xmlPath);
209 Document currentConfigElement = readXmlToDocument(resourceAsStream);
210 Preconditions.checkNotNull(currentConfigElement);
211 return currentConfigElement;
214 private static final DocumentBuilderFactory BUILDERFACTORY;
217 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
218 factory.setNamespaceAware(true);
219 factory.setCoalescing(true);
220 factory.setIgnoringElementContentWhitespace(true);
221 factory.setIgnoringComments(true);
222 BUILDERFACTORY = factory;
225 private Document readXmlToDocument(InputStream xmlContent) throws IOException, SAXException {
226 DocumentBuilder dBuilder;
228 dBuilder = BUILDERFACTORY.newDocumentBuilder();
229 } catch (ParserConfigurationException e) {
230 throw new RuntimeException("Failed to parse XML document", e);
232 Document doc = dBuilder.parse(xmlContent);
234 doc.getDocumentElement().normalize();
238 public static String toString(Element xml) {
240 Transformer transformer = TransformerFactory.newInstance().newTransformer();
241 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
243 StreamResult result = new StreamResult(new StringWriter());
244 DOMSource source = new DOMSource(xml);
245 transformer.transform(source, result);
247 return result.getWriter().toString();
248 } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
249 throw new RuntimeException("Unable to serialize xml element " + xml, e);