2 * Copyright (c) 2014, 2015 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.codec.binfmt;
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertThrows;
13 import com.google.common.io.ByteStreams;
14 import java.io.ByteArrayInputStream;
15 import java.io.ByteArrayOutputStream;
16 import java.io.IOException;
17 import java.io.ObjectInputStream;
18 import java.io.ObjectOutputStream;
19 import java.io.Serializable;
20 import java.io.StringReader;
21 import java.io.StringWriter;
22 import java.util.Collections;
23 import java.util.Optional;
24 import javax.xml.parsers.DocumentBuilderFactory;
25 import javax.xml.transform.OutputKeys;
26 import javax.xml.transform.Transformer;
27 import javax.xml.transform.TransformerFactory;
28 import javax.xml.transform.dom.DOMSource;
29 import javax.xml.transform.stream.StreamResult;
30 import org.junit.Test;
31 import org.junit.runner.RunWith;
32 import org.junit.runners.Parameterized;
33 import org.junit.runners.Parameterized.Parameter;
34 import org.junit.runners.Parameterized.Parameters;
35 import org.opendaylight.yangtools.yang.common.Empty;
36 import org.opendaylight.yangtools.yang.common.QName;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
41 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
43 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
44 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
46 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
47 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
48 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
49 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
50 import org.w3c.dom.Node;
51 import org.xml.sax.InputSource;
53 @RunWith(Parameterized.class)
54 public class NormalizedNodeStreamReaderWriterTest {
55 @Parameters(name = "{0} {1}")
56 public static Iterable<Object[]> data() {
57 return Collections.singletonList(
58 new Object[] { NormalizedNodeStreamVersion.MAGNESIUM, 1_049_589, 2_289_103, 139, 796, 103, 229, 99 });
62 public NormalizedNodeStreamVersion version;
64 public int normalizedNodeStreamingSize;
66 public int hugeEntriesSize;
68 public int yiidStreamingSize;
70 public int nnYiidStreamingSize;
72 public int writePathArgumentSize;
74 public int anyxmlStreamingSize;
76 public int schemaPathSize;
79 public void testNormalizedNodeStreaming() throws IOException {
80 ByteArrayOutputStream bos = new ByteArrayOutputStream();
81 NormalizedNodeDataOutput nnout = version.newDataOutput(ByteStreams.newDataOutput(bos));
83 ContainerNode testContainer = createTestContainer();
84 nnout.writeNormalizedNode(testContainer);
86 QName toaster = QName.create("http://netconfcentral.org/ns/toaster","2009-11-20","toaster");
87 QName darknessFactor = QName.create("http://netconfcentral.org/ns/toaster","2009-11-20","darknessFactor");
88 QName description = QName.create("http://netconfcentral.org/ns/toaster","2009-11-20","description");
89 ContainerNode toasterNode = Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(toaster))
90 .withChild(ImmutableNodes.leafNode(darknessFactor, "1000"))
91 .withChild(ImmutableNodes.leafNode(description, largeString(20))).build();
93 ContainerNode toasterContainer = Builders.containerBuilder()
94 .withNodeIdentifier(new NodeIdentifier(SchemaContext.NAME)).withChild(toasterNode).build();
95 nnout.writeNormalizedNode(toasterContainer);
97 final byte[] bytes = bos.toByteArray();
98 assertEquals(normalizedNodeStreamingSize, bytes.length);
100 NormalizedNodeDataInput nnin = NormalizedNodeDataInput.newDataInput(ByteStreams.newDataInput(bytes));
102 assertEquals(testContainer, nnin.readNormalizedNode());
103 assertEquals(toasterContainer, nnin.readNormalizedNode());
106 private static ContainerNode createTestContainer() {
107 final byte[] bytes1 = {1, 2, 3};
108 final byte[] bytes2 = {};
110 return TestModel.createBaseTestContainerBuilder()
111 .withChild(Builders.leafSetBuilder()
112 .withNodeIdentifier(new NodeIdentifier(TestModel.BINARY_LEAF_LIST_QNAME))
113 .withChild(Builders.leafSetEntryBuilder()
114 .withNodeIdentifier(new NodeWithValue<>(TestModel.BINARY_LEAF_LIST_QNAME, bytes1))
117 .withChild(Builders.leafSetEntryBuilder()
118 .withNodeIdentifier(new NodeWithValue<>(TestModel.BINARY_LEAF_LIST_QNAME, bytes2))
122 .withChild(ImmutableNodes.leafNode(TestModel.SOME_BINARY_DATA_QNAME, new byte[]{1, 2, 3, 4}))
123 .withChild(ImmutableNodes.leafNode(TestModel.EMPTY_QNAME, Empty.value()))
124 .withChild(Builders.orderedMapBuilder()
125 .withNodeIdentifier(new NodeIdentifier(TestModel.ORDERED_LIST_QNAME))
126 .withChild(ImmutableNodes.mapEntry(TestModel.ORDERED_LIST_ENTRY_QNAME, TestModel.ID_QNAME, 11))
132 public void testYangInstanceIdentifierStreaming() throws IOException {
133 YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.TEST_PATH)
134 .node(TestModel.OUTER_LIST_QNAME).nodeWithKey(
135 TestModel.INNER_LIST_QNAME, TestModel.ID_QNAME, 10).build();
137 ByteArrayOutputStream bos = new ByteArrayOutputStream();
138 NormalizedNodeDataOutput nnout = version.newDataOutput(ByteStreams.newDataOutput(bos));
140 nnout.writeYangInstanceIdentifier(path);
142 final byte[] bytes = bos.toByteArray();
143 assertEquals(yiidStreamingSize, bytes.length);
145 NormalizedNodeDataInput nnin = NormalizedNodeDataInput.newDataInput(ByteStreams.newDataInput(bytes));
146 assertEquals(path, nnin.readYangInstanceIdentifier());
150 public void testNormalizedNodeAndYangInstanceIdentifierStreaming() throws IOException {
151 final NormalizedNode testContainer = TestModel.createBaseTestContainerBuilder().build();
152 final YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.TEST_PATH)
153 .node(TestModel.OUTER_LIST_QNAME)
154 .nodeWithKey(TestModel.INNER_LIST_QNAME, TestModel.ID_QNAME, 10)
157 final ByteArrayOutputStream bos = new ByteArrayOutputStream();
158 try (NormalizedNodeDataOutput writer = version.newDataOutput(ByteStreams.newDataOutput(bos))) {
159 writer.writeNormalizedNode(testContainer);
160 writer.writeYangInstanceIdentifier(path);
163 final byte[] bytes = bos.toByteArray();
164 assertEquals(nnYiidStreamingSize, bytes.length);
166 final NormalizedNodeDataInput reader = NormalizedNodeDataInput.newDataInput(ByteStreams.newDataInput(bytes));
167 assertEquals(testContainer, reader.readNormalizedNode());
168 assertEquals(path, reader.readYangInstanceIdentifier());
172 public void testInvalidNormalizedNodeStream() throws IOException {
173 final InvalidNormalizedNodeStreamException ex = assertThrows(InvalidNormalizedNodeStreamException.class,
174 () -> NormalizedNodeDataInput.newDataInput(ByteStreams.newDataInput(new byte[] { 1, 2, 3})));
175 assertEquals("Invalid signature marker: 1", ex.getMessage());
179 public void testWithSerializable() {
180 NormalizedNode input = TestModel.createTestContainer();
181 SampleNormalizedNodeSerializable serializable = new SampleNormalizedNodeSerializable(version, input);
182 SampleNormalizedNodeSerializable clone = clone(serializable);
183 assertEquals(input, clone.getInput());
187 public void testAnyXmlStreaming() throws Exception {
188 String xml = "<foo xmlns=\"http://www.w3.org/TR/html4/\" x=\"123\"><bar>one</bar><bar>two</bar></foo>";
189 final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
190 factory.setNamespaceAware(true);
192 Node xmlNode = factory.newDocumentBuilder().parse(
193 new InputSource(new StringReader(xml))).getDocumentElement();
195 assertEquals("http://www.w3.org/TR/html4/", xmlNode.getNamespaceURI());
197 ContainerNode anyXmlContainer = Builders.containerBuilder()
198 .withNodeIdentifier(new NodeIdentifier(TestModel.TEST_QNAME))
199 .withChild(Builders.anyXmlBuilder()
200 .withNodeIdentifier(new NodeIdentifier(TestModel.ANY_XML_QNAME))
201 .withValue(new DOMSource(xmlNode))
205 ByteArrayOutputStream bos = new ByteArrayOutputStream();
206 NormalizedNodeDataOutput nnout = version.newDataOutput(ByteStreams.newDataOutput(bos));
208 nnout.writeNormalizedNode(anyXmlContainer);
210 final byte[] bytes = bos.toByteArray();
211 assertEquals(anyxmlStreamingSize, bytes.length);
213 NormalizedNodeDataInput nnin = NormalizedNodeDataInput.newDataInput(ByteStreams.newDataInput(bytes));
215 ContainerNode deserialized = (ContainerNode)nnin.readNormalizedNode();
217 Optional<DataContainerChild> child = deserialized.findChildByArg(new NodeIdentifier(TestModel.ANY_XML_QNAME));
218 assertEquals("AnyXml child present", true, child.isPresent());
220 StreamResult xmlOutput = new StreamResult(new StringWriter());
221 Transformer transformer = TransformerFactory.newInstance().newTransformer();
222 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
223 transformer.transform(((DOMSourceAnyxmlNode)child.orElseThrow()).body(), xmlOutput);
225 assertEquals("XML", xml, xmlOutput.getWriter().toString());
226 assertEquals("http://www.w3.org/TR/html4/",
227 ((DOMSourceAnyxmlNode)child.orElseThrow()).body().getNode().getNamespaceURI());
231 public void testSchemaPathSerialization() throws IOException {
232 final Absolute expected = Absolute.of(TestModel.ANY_XML_QNAME);
234 ByteArrayOutputStream bos = new ByteArrayOutputStream();
235 try (NormalizedNodeDataOutput nnout = version.newDataOutput(ByteStreams.newDataOutput(bos))) {
236 nnout.writeSchemaNodeIdentifier(expected);
239 final byte[] bytes = bos.toByteArray();
240 assertEquals(schemaPathSize, bytes.length);
242 NormalizedNodeDataInput nnin = NormalizedNodeDataInput.newDataInput(ByteStreams.newDataInput(bytes));
243 assertEquals(expected, nnin.readSchemaNodeIdentifier());
247 public void testWritePathArgument() throws IOException {
248 final NodeIdentifier expected = new NodeIdentifier(TestModel.BOOLEAN_LEAF_QNAME);
250 ByteArrayOutputStream bos = new ByteArrayOutputStream();
252 try (NormalizedNodeDataOutput nnout = version.newDataOutput(ByteStreams.newDataOutput(bos))) {
253 nnout.writePathArgument(expected);
256 final byte[] bytes = bos.toByteArray();
257 assertEquals(writePathArgumentSize, bytes.length);
259 NormalizedNodeDataInput nnin = NormalizedNodeDataInput.newDataInput(ByteStreams.newDataInput(bytes));
260 assertEquals(expected, nnin.readPathArgument());
264 * This tests the encoding of a MapNode with a lot of entries, each of them having the key leaf (a string)
268 public void testHugeEntries() throws IOException {
269 final var mapBuilder = Builders.mapBuilder().withNodeIdentifier(new NodeIdentifier(TestModel.TEST_QNAME));
270 final var entryBuilder = Builders.mapEntryBuilder()
271 .withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, (byte) 42));
273 for (int i = 0; i < 100_000; ++i) {
274 final String key = "xyzzy" + i;
275 mapBuilder.addChild(entryBuilder
276 .withNodeIdentifier(NodeIdentifierWithPredicates.of(TestModel.TEST_QNAME,
277 TestModel.CHILD_NAME_QNAME, key))
278 .withChild(ImmutableNodes.leafNode(TestModel.CHILD_NAME_QNAME, key))
282 final SystemMapNode expected = mapBuilder.build();
283 final ByteArrayOutputStream bos = new ByteArrayOutputStream();
285 try (NormalizedNodeDataOutput nnout = version.newDataOutput(ByteStreams.newDataOutput(bos))) {
286 nnout.writeNormalizedNode(expected);
289 final byte[] bytes = bos.toByteArray();
290 assertEquals(hugeEntriesSize, bytes.length);
292 NormalizedNodeDataInput nnin = NormalizedNodeDataInput.newDataInput(ByteStreams.newDataInput(bytes));
293 assertEquals(expected, nnin.readNormalizedNode());
296 private static <T extends Serializable> T clone(final T obj) {
297 final ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
298 try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
299 oos.writeObject(obj);
300 } catch (IOException e) {
301 throw new AssertionError("Failed to serialize object", e);
304 final byte[] bytes = baos.toByteArray();
305 try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes))) {
306 return (T) ois.readObject();
307 } catch (ClassNotFoundException | IOException e) {
308 throw new AssertionError("Failed to deserialize object", e);
312 private static String largeString(final int pow) {
313 StringBuilder sb = new StringBuilder("X");
314 for (int i = 0; i < pow; i++) {
317 return sb.toString();