Bug 1441: Bug fixes, clean-up and test migration
[yangtools.git] / yang / yang-data-codec-xml / src / test / java / org / opendaylight / yangtools / yang / data / codec / xml / Bug5446Test.java
1 /*
2  * Copyright (c) 2016 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
9 package org.opendaylight.yangtools.yang.data.codec.xml;
10
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.io.BaseEncoding;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.io.StringWriter;
17 import java.net.URI;
18 import javax.xml.parsers.DocumentBuilder;
19 import javax.xml.parsers.DocumentBuilderFactory;
20 import javax.xml.parsers.ParserConfigurationException;
21 import javax.xml.stream.XMLOutputFactory;
22 import javax.xml.stream.XMLStreamException;
23 import javax.xml.stream.XMLStreamWriter;
24 import javax.xml.transform.OutputKeys;
25 import javax.xml.transform.Transformer;
26 import javax.xml.transform.TransformerException;
27 import javax.xml.transform.TransformerFactory;
28 import javax.xml.transform.TransformerFactoryConfigurationError;
29 import javax.xml.transform.dom.DOMResult;
30 import javax.xml.transform.dom.DOMSource;
31 import javax.xml.transform.stream.StreamResult;
32 import org.custommonkey.xmlunit.XMLTestCase;
33 import org.custommonkey.xmlunit.XMLUnit;
34 import org.junit.Test;
35 import org.opendaylight.yangtools.yang.common.QName;
36 import org.opendaylight.yangtools.yang.common.QNameModule;
37 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
40 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
42 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
43 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
44 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
45 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
46 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
47 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
48 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
49 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
50 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
51 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangStatementSourceImpl;
52 import org.w3c.dom.Document;
53 import org.w3c.dom.Node;
54 import org.xml.sax.SAXException;
55
56 public class Bug5446Test extends XMLTestCase {
57     private static final XMLOutputFactory XML_FACTORY;
58     private static final DocumentBuilderFactory BUILDERFACTORY;
59
60     static {
61         XML_FACTORY = XMLOutputFactory.newFactory();
62         XML_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, false);
63
64         BUILDERFACTORY = DocumentBuilderFactory.newInstance();
65         BUILDERFACTORY.setNamespaceAware(true);
66         BUILDERFACTORY.setCoalescing(true);
67         BUILDERFACTORY.setIgnoringElementContentWhitespace(true);
68         BUILDERFACTORY.setIgnoringComments(true);
69     }
70
71     private QNameModule fooModuleQName;
72     private QName rootQName;
73     private QName ipAddressQName;
74     private SchemaContext schemaContext;
75
76     public Bug5446Test() throws Exception {
77         fooModuleQName = QNameModule.create(new URI("foo"), SimpleDateFormatUtil.getRevisionFormat()
78                 .parse("2015-11-05"));
79         rootQName = QName.create(fooModuleQName, "root");
80         ipAddressQName = QName.create(fooModuleQName, "ip-address");
81
82         CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
83         reactor.addSource(new YangStatementSourceImpl("/bug5446/yang/foo.yang", false));
84
85         schemaContext = reactor.buildEffective();
86     }
87
88     @Test
89     public void test() throws Exception {
90         final Document doc = loadDocument("/bug5446/xml/foo.xml");
91
92         final ContainerNode docNode = createDocNode();
93
94         Optional<DataContainerChild<? extends PathArgument, ?>> root = docNode.getChild(new NodeIdentifier(rootQName));
95         assertTrue(root.orNull() instanceof ContainerNode);
96
97         Optional<DataContainerChild<? extends PathArgument, ?>> child = ((ContainerNode) root.orNull())
98                 .getChild(new NodeIdentifier(ipAddressQName));
99         assertTrue(child.orNull() instanceof LeafNode);
100         LeafNode<?> ipAdress = (LeafNode<?>) child.get();
101
102         Object value = ipAdress.getValue();
103         assertTrue(value instanceof byte[]);
104         assertEquals("fwAAAQ==", BaseEncoding.base64().encode((byte[]) value));
105
106         DOMResult serializationResult = writeNormalizedNode(docNode, schemaContext);
107         assertNotNull(serializationResult);
108
109         XMLUnit.setIgnoreWhitespace(true);
110         XMLUnit.setIgnoreComments(true);
111         XMLUnit.setIgnoreAttributeOrder(true);
112         XMLUnit.setNormalize(true);
113
114         String expectedXMLString = toString(doc.getDocumentElement().getElementsByTagName("root").item(0));
115         String serializationResultXMLString = toString(serializationResult.getNode());
116
117         assertXMLEqual(expectedXMLString, serializationResultXMLString);
118     }
119
120     private ContainerNode createDocNode() {
121         LeafNode<byte[]> ipAddress = ImmutableNodes.leafNode(ipAddressQName, BaseEncoding.base64().decode("fwAAAQ=="));
122         ContainerNode root = ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(rootQName))
123                 .withChild(ipAddress).build();
124         return ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(rootQName)).withChild(root)
125                 .build();
126     }
127
128     private static DOMResult writeNormalizedNode(final ContainerNode normalized, final SchemaContext context)
129             throws IOException, XMLStreamException {
130         final Document doc = getDocument();
131         final DOMResult result = new DOMResult(doc);
132         NormalizedNodeWriter normalizedNodeWriter = null;
133         NormalizedNodeStreamWriter normalizedNodeStreamWriter = null;
134         XMLStreamWriter writer = null;
135         try {
136             writer = XML_FACTORY.createXMLStreamWriter(result);
137             normalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(writer, context);
138             normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(normalizedNodeStreamWriter);
139
140             for (NormalizedNode<?, ?> child : normalized.getValue()) {
141                 normalizedNodeWriter.write(child);
142             }
143
144             normalizedNodeWriter.flush();
145         } finally {
146             if (normalizedNodeWriter != null) {
147                 normalizedNodeWriter.close();
148             }
149             if (normalizedNodeStreamWriter != null) {
150                 normalizedNodeStreamWriter.close();
151             }
152             if (writer != null) {
153                 writer.close();
154             }
155         }
156
157         return result;
158     }
159
160     private static Document loadDocument(final String xmlPath) throws IOException, SAXException {
161         final InputStream resourceAsStream = Bug5446Test.class.getResourceAsStream(xmlPath);
162         final Document currentConfigElement = readXmlToDocument(resourceAsStream);
163         Preconditions.checkNotNull(currentConfigElement);
164         return currentConfigElement;
165     }
166
167     private static Document readXmlToDocument(final InputStream xmlContent) throws IOException, SAXException {
168         final DocumentBuilder dBuilder;
169         try {
170             dBuilder = BUILDERFACTORY.newDocumentBuilder();
171         } catch (final ParserConfigurationException e) {
172             throw new RuntimeException("Failed to parse XML document", e);
173         }
174         final Document doc = dBuilder.parse(xmlContent);
175
176         doc.getDocumentElement().normalize();
177         return doc;
178     }
179
180     private static String toString(final Node xml) {
181         try {
182             final Transformer transformer = TransformerFactory.newInstance().newTransformer();
183             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
184             transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
185
186             final StreamResult result = new StreamResult(new StringWriter());
187             final DOMSource source = new DOMSource(xml);
188             transformer.transform(source, result);
189
190             return result.getWriter().toString();
191         } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
192             throw new RuntimeException("Unable to serialize xml element " + xml, e);
193         }
194     }
195
196     private static Document getDocument() {
197         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
198         Document doc = null;
199         try {
200             DocumentBuilder bob = dbf.newDocumentBuilder();
201             doc = bob.newDocument();
202         } catch (ParserConfigurationException e) {
203             throw new RuntimeException(e);
204         }
205         return doc;
206     }
207 }