Address trivial eclipse warnings
[yangtools.git] / yang / yang-data-impl / src / test / java / org / opendaylight / yangtools / yang / data / impl / codec / xml / XmlStreamUtilsTest.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.impl.codec.xml;
10
11 import static org.hamcrest.CoreMatchers.containsString;
12 import static org.junit.Assert.assertEquals;
13 import static org.junit.Assert.assertNotNull;
14 import static org.junit.Assert.assertThat;
15 import static org.junit.Assert.assertTrue;
16
17 import com.google.common.base.Optional;
18 import com.google.common.collect.Maps;
19 import java.io.ByteArrayOutputStream;
20 import java.io.File;
21 import java.io.FileNotFoundException;
22 import java.net.URI;
23 import java.net.URISyntaxException;
24 import java.util.AbstractMap;
25 import java.util.Date;
26 import java.util.Map;
27 import java.util.regex.Matcher;
28 import java.util.regex.Pattern;
29 import javax.xml.stream.XMLOutputFactory;
30 import javax.xml.stream.XMLStreamWriter;
31 import org.custommonkey.xmlunit.Diff;
32 import org.custommonkey.xmlunit.XMLUnit;
33 import org.junit.BeforeClass;
34 import org.junit.Ignore;
35 import org.junit.Test;
36 import org.opendaylight.yangtools.yang.common.QName;
37 import org.opendaylight.yangtools.yang.common.QNameModule;
38 import org.opendaylight.yangtools.yang.data.impl.TestUtils;
39 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
40 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.Module;
43 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
44 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
45 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
46 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
47 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
48 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
50 import org.w3c.dom.Document;
51
52 public class XmlStreamUtilsTest {
53
54     public static final XMLOutputFactory XML_OUTPUT_FACTORY = XMLOutputFactory.newFactory();
55
56     private static SchemaContext schemaContext;
57     private static Module leafRefModule;
58
59     @BeforeClass
60     public static void initialize() throws URISyntaxException, FileNotFoundException, ReactorException {
61         final File file = new File(XmlStreamUtils.class.getResource("/leafref-test.yang").toURI());
62         schemaContext = TestUtils.parseYangSources(file);
63         assertNotNull(schemaContext);
64         assertEquals(1, schemaContext.getModules().size());
65         leafRefModule = schemaContext.getModules().iterator().next();
66         assertNotNull(leafRefModule);
67     }
68
69     @Test
70     public void testWriteAttribute() throws Exception {
71         final ByteArrayOutputStream out = new ByteArrayOutputStream();
72         final XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(out);
73         writer.writeStartElement("element");
74
75         QName name = getAttrQName("namespace", "2012-12-12", "attr", Optional.of("prefix"));
76         final Map.Entry<QName, String> attributeEntry = new AbstractMap.SimpleEntry<>(name, "value");
77
78         name = getAttrQName("namespace2", "2012-12-12", "attr", Optional.absent());
79         final Map.Entry<QName, String> attributeEntryNoPrefix = new AbstractMap.SimpleEntry<>(name, "value");
80
81         final RandomPrefix randomPrefix = new RandomPrefix();
82         XmlStreamUtils.writeAttribute(writer, attributeEntry, randomPrefix);
83         XmlStreamUtils.writeAttribute(writer, attributeEntryNoPrefix, randomPrefix);
84
85         writer.writeEndElement();
86         writer.close();
87         out.close();
88
89         final String xmlAsString = new String(out.toByteArray());
90
91         final Map<String, String> mappedPrefixes = mapPrefixed(randomPrefix.getPrefixes());
92         assertEquals(2, mappedPrefixes.size());
93         final String randomPrefixValue = mappedPrefixes.get("namespace2");
94
95         final String expectedXmlAsString = "<element xmlns:a=\"namespace\" a:attr=\"value\" xmlns:" + randomPrefixValue
96                 + "=\"namespace2\" " + randomPrefixValue + ":attr=\"value\"></element>";
97
98         XMLUnit.setIgnoreAttributeOrder(true);
99         final Document control = XMLUnit.buildControlDocument(expectedXmlAsString);
100         final Document test = XMLUnit.buildTestDocument(xmlAsString);
101         final Diff diff = XMLUnit.compareXML(control, test);
102
103         final boolean identical = diff.identical();
104         assertTrue("Xml differs: " + diff.toString(), identical);
105     }
106
107     @Test
108     public void testWriteIdentityRef() throws Exception {
109         final ByteArrayOutputStream out = new ByteArrayOutputStream();
110         final XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(out);
111
112         writer.writeStartElement("element");
113         final QNameModule parent = QNameModule.create(URI.create("parent:uri"), new Date());
114         XmlStreamUtils.write(writer, null, QName.create(parent, "identity"), Optional.of(parent));
115         writer.writeEndElement();
116
117         writer.writeStartElement("elementDifferent");
118         XmlStreamUtils.write(writer, null, QName.create("different:namespace", "identity"), Optional.of(parent));
119         writer.writeEndElement();
120
121         writer.close();
122         out.close();
123
124         final String xmlAsString = new String(out.toByteArray()).replaceAll("\\s*", "");
125         assertThat(xmlAsString, containsString("element>identity"));
126
127         final Pattern prefixedIdentityPattern = Pattern.compile(".*\"different:namespace\">(.*):identity.*");
128         final Matcher matcher = prefixedIdentityPattern.matcher(xmlAsString);
129         assertTrue("Xml: " + xmlAsString + " should match: " + prefixedIdentityPattern, matcher.matches());
130     }
131
132     /**
133      * One leafref reference to other leafref via relative references
134      */
135     @Test
136     public void testLeafRefRelativeChaining() {
137         getTargetNodeForLeafRef("leafname3", StringTypeDefinition.class);
138     }
139
140     @Test
141     public void testLeafRefRelative() {
142         getTargetNodeForLeafRef("pointToStringLeaf", StringTypeDefinition.class);
143     }
144
145     @Test
146     public void testLeafRefAbsoluteWithSameTarget() {
147         getTargetNodeForLeafRef("absname", InstanceIdentifierTypeDefinition.class);
148     }
149
150     /**
151      * Tests relative path with double point inside path (e. g. "../../lf:interface/../lf:cont2/lf:stringleaf")
152      */
153     @Ignore
154     // ignored because this isn't implemented
155     @Test
156     public void testLeafRefWithDoublePointInPath() {
157         getTargetNodeForLeafRef("lf-with-double-point-inside", StringTypeDefinition.class);
158     }
159
160     @Test
161     public void testLeafRefRelativeAndAbsoluteWithSameTarget() {
162         final TypeDefinition<?> targetNodeForAbsname = getTargetNodeForLeafRef("absname",
163             InstanceIdentifierTypeDefinition.class);
164         final TypeDefinition<?> targetNodeForRelname = getTargetNodeForLeafRef("relname",
165             InstanceIdentifierTypeDefinition.class);
166         assertEquals(targetNodeForAbsname, targetNodeForRelname);
167     }
168
169     private TypeDefinition<?> getTargetNodeForLeafRef(final String nodeName, final Class<?> clas) {
170         final LeafSchemaNode schemaNode = findSchemaNodeWithLeafrefType(leafRefModule, nodeName);
171         assertNotNull(schemaNode);
172         final LeafrefTypeDefinition leafrefTypedef = findLeafrefType(schemaNode);
173         assertNotNull(leafrefTypedef);
174         final TypeDefinition<?> targetBaseType = SchemaContextUtil.getBaseTypeForLeafRef(leafrefTypedef, schemaContext,
175                 schemaNode);
176         assertTrue("Wrong class found.", clas.isInstance(targetBaseType));
177         return targetBaseType;
178     }
179
180     private static Map<String, String> mapPrefixed(final Iterable<Map.Entry<URI, String>> prefixes) {
181         final Map<String, String> mappedPrefixes = Maps.newHashMap();
182         for (final Map.Entry<URI, String> prefix : prefixes) {
183             mappedPrefixes.put(prefix.getKey().toString(), prefix.getValue());
184         }
185         return mappedPrefixes;
186     }
187
188     private static QName getAttrQName(final String namespace, final String revision, final String localName,
189             final Optional<String> prefix) {
190         if (prefix.isPresent()) {
191             final QName moduleQName = QName.create(namespace, revision, "module");
192             final QNameModule module = QNameModule.create(moduleQName.getNamespace(), moduleQName.getRevision());
193             return QName.create(module, localName);
194         }
195         return QName.create(namespace, revision, localName);
196     }
197
198     private LeafSchemaNode findSchemaNodeWithLeafrefType(final DataNodeContainer module, final String nodeName) {
199         for (final DataSchemaNode childNode : module.getChildNodes()) {
200             if (childNode instanceof DataNodeContainer) {
201                 LeafSchemaNode leafrefFromRecursion = findSchemaNodeWithLeafrefType((DataNodeContainer) childNode,
202                         nodeName);
203                 if (leafrefFromRecursion != null) {
204                     return leafrefFromRecursion;
205                 }
206             } else if (childNode.getQName().getLocalName().equals(nodeName) && childNode instanceof LeafSchemaNode) {
207                 final TypeDefinition<?> leafSchemaNodeType = ((LeafSchemaNode) childNode).getType();
208                 if (leafSchemaNodeType instanceof LeafrefTypeDefinition) {
209                     return (LeafSchemaNode) childNode;
210                 }
211             }
212         }
213         return null;
214     }
215
216     private static LeafrefTypeDefinition findLeafrefType(final LeafSchemaNode schemaNode) {
217         final TypeDefinition<?> type = schemaNode.getType();
218         if (type instanceof LeafrefTypeDefinition) {
219             return (LeafrefTypeDefinition) type;
220         }
221         return null;
222     }
223 }