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;
12 import com.google.common.collect.ImmutableSet;
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.math.BigInteger;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.List;
26 import java.util.Optional;
27 import java.util.function.Function;
28 import javax.xml.parsers.DocumentBuilderFactory;
29 import javax.xml.transform.OutputKeys;
30 import javax.xml.transform.Transformer;
31 import javax.xml.transform.TransformerFactory;
32 import javax.xml.transform.dom.DOMSource;
33 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.junit.runners.Parameterized.Parameter;
39 import org.junit.runners.Parameterized.Parameters;
40 import org.opendaylight.yangtools.yang.common.Empty;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.common.Uint64;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
49 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
52 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
56 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
57 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
58 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
59 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
60 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
61 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetEntryNodeBuilder;
62 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetNodeBuilder;
63 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
64 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
65 import org.w3c.dom.Node;
66 import org.xml.sax.InputSource;
68 @RunWith(Parameterized.class)
69 public class NormalizedNodeStreamReaderWriterTest {
70 enum Unsigned implements Function<String, Number> {
73 public BigInteger apply(final String str) {
74 return new BigInteger(str);
79 public Uint64 apply(final String str) {
80 return Uint64.valueOf(str);
85 @Parameters(name = "{0} {1}")
86 public static Iterable<Object[]> data() {
88 new Object[] { NormalizedNodeStreamVersion.LITHIUM, Unsigned.BIG_INTEGER,
89 1_050_286, 9_577_973, 171, 1_553, 103, 237, 98 },
90 new Object[] { NormalizedNodeStreamVersion.NEON_SR2, Unsigned.BIG_INTEGER,
91 1_049_950, 5_577_993, 161, 1_163, 105, 235, 100 },
92 new Object[] { NormalizedNodeStreamVersion.SODIUM_SR1, Unsigned.BIG_INTEGER,
93 1_049_619, 2_289_103, 139, 826, 103, 229, 99 },
94 new Object[] { NormalizedNodeStreamVersion.SODIUM_SR1, Unsigned.UINT64,
95 1_049_618, 2_289_103, 139, 825, 103, 229, 99 },
96 new Object[] { NormalizedNodeStreamVersion.MAGNESIUM, Unsigned.UINT64,
97 1_049_618, 2_289_103, 139, 825, 103, 229, 99 });
101 public NormalizedNodeStreamVersion version;
103 public Unsigned uint64;
105 public int normalizedNodeStreamingSize;
107 public int hugeEntriesSize;
109 public int yiidStreamingSize;
111 public int nnYiidStreamingSize;
113 public int writePathArgumentSize;
115 public int anyxmlStreamingSize;
117 public int schemaPathSize;
120 public void testNormalizedNodeStreaming() throws IOException {
122 ByteArrayOutputStream bos = new ByteArrayOutputStream();
123 NormalizedNodeDataOutput nnout = version.newDataOutput(ByteStreams.newDataOutput(bos));
125 NormalizedNode<?, ?> testContainer = createTestContainer();
126 nnout.writeNormalizedNode(testContainer);
128 QName toaster = QName.create("http://netconfcentral.org/ns/toaster","2009-11-20","toaster");
129 QName darknessFactor = QName.create("http://netconfcentral.org/ns/toaster","2009-11-20","darknessFactor");
130 QName description = QName.create("http://netconfcentral.org/ns/toaster","2009-11-20","description");
131 ContainerNode toasterNode = Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(toaster))
132 .withChild(ImmutableNodes.leafNode(darknessFactor, "1000"))
133 .withChild(ImmutableNodes.leafNode(description, largeString(20))).build();
135 ContainerNode toasterContainer = Builders.containerBuilder()
136 .withNodeIdentifier(new NodeIdentifier(SchemaContext.NAME)).withChild(toasterNode).build();
137 nnout.writeNormalizedNode(toasterContainer);
139 final byte[] bytes = bos.toByteArray();
140 assertEquals(normalizedNodeStreamingSize, bytes.length);
142 NormalizedNodeDataInput nnin = NormalizedNodeDataInput.newDataInput(ByteStreams.newDataInput(bytes));
144 NormalizedNode<?, ?> node = nnin.readNormalizedNode();
145 Assert.assertEquals(testContainer, node);
147 node = nnin.readNormalizedNode();
148 Assert.assertEquals(toasterContainer, node);
151 private NormalizedNode<?, ?> createTestContainer() {
152 byte[] bytes1 = {1, 2, 3};
153 LeafSetEntryNode<Object> entry1 = ImmutableLeafSetEntryNodeBuilder.create().withNodeIdentifier(
154 new NodeWithValue<>(TestModel.BINARY_LEAF_LIST_QNAME, bytes1)).withValue(bytes1).build();
157 LeafSetEntryNode<Object> entry2 = ImmutableLeafSetEntryNodeBuilder.create().withNodeIdentifier(
158 new NodeWithValue<>(TestModel.BINARY_LEAF_LIST_QNAME, bytes2)).withValue(bytes2).build();
160 return TestModel.createBaseTestContainerBuilder(uint64)
161 .withChild(ImmutableLeafSetNodeBuilder.create().withNodeIdentifier(
162 new NodeIdentifier(TestModel.BINARY_LEAF_LIST_QNAME))
163 .withChild(entry1).withChild(entry2).build())
164 .withChild(ImmutableNodes.leafNode(TestModel.SOME_BINARY_DATA_QNAME, new byte[]{1, 2, 3, 4}))
165 .withChild(ImmutableNodes.leafNode(TestModel.EMPTY_QNAME, Empty.getInstance()))
166 .withChild(Builders.orderedMapBuilder()
167 .withNodeIdentifier(new NodeIdentifier(TestModel.ORDERED_LIST_QNAME))
168 .withChild(ImmutableNodes.mapEntry(TestModel.ORDERED_LIST_ENTRY_QNAME,
169 TestModel.ID_QNAME, 11)).build()).build();
173 public void testYangInstanceIdentifierStreaming() throws IOException {
174 YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.TEST_PATH)
175 .node(TestModel.OUTER_LIST_QNAME).nodeWithKey(
176 TestModel.INNER_LIST_QNAME, TestModel.ID_QNAME, 10).build();
178 ByteArrayOutputStream bos = new ByteArrayOutputStream();
179 NormalizedNodeDataOutput nnout = version.newDataOutput(ByteStreams.newDataOutput(bos));
181 nnout.writeYangInstanceIdentifier(path);
183 final byte[] bytes = bos.toByteArray();
184 assertEquals(yiidStreamingSize, bytes.length);
186 NormalizedNodeDataInput nnin = NormalizedNodeDataInput.newDataInput(ByteStreams.newDataInput(bytes));
188 YangInstanceIdentifier newPath = nnin.readYangInstanceIdentifier();
189 Assert.assertEquals(path, newPath);
193 public void testNormalizedNodeAndYangInstanceIdentifierStreaming() throws IOException {
195 ByteArrayOutputStream bos = new ByteArrayOutputStream();
196 NormalizedNodeDataOutput writer = version.newDataOutput(
197 ByteStreams.newDataOutput(bos));
199 NormalizedNode<?, ?> testContainer = TestModel.createBaseTestContainerBuilder(uint64).build();
200 writer.writeNormalizedNode(testContainer);
202 YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.TEST_PATH)
203 .node(TestModel.OUTER_LIST_QNAME).nodeWithKey(
204 TestModel.INNER_LIST_QNAME, TestModel.ID_QNAME, 10).build();
206 writer.writeYangInstanceIdentifier(path);
208 final byte[] bytes = bos.toByteArray();
209 assertEquals(nnYiidStreamingSize, bytes.length);
211 NormalizedNodeDataInput reader = NormalizedNodeDataInput.newDataInput(ByteStreams.newDataInput(bytes));
213 NormalizedNode<?,?> node = reader.readNormalizedNode();
214 Assert.assertEquals(testContainer, node);
216 YangInstanceIdentifier newPath = reader.readYangInstanceIdentifier();
217 Assert.assertEquals(path, newPath);
222 @Test(expected = InvalidNormalizedNodeStreamException.class, timeout = 10000)
223 public void testInvalidNormalizedNodeStream() throws IOException {
224 byte[] invalidBytes = {1, 2, 3};
225 NormalizedNodeDataInput reader = NormalizedNodeDataInput.newDataInput(ByteStreams.newDataInput(invalidBytes));
227 reader.readNormalizedNode();
230 @Test(expected = InvalidNormalizedNodeStreamException.class, timeout = 10000)
231 public void testInvalidYangInstanceIdentifierStream() throws IOException {
232 byte[] invalidBytes = {1,2,3};
233 NormalizedNodeDataInput reader = NormalizedNodeDataInput.newDataInput(ByteStreams.newDataInput(invalidBytes));
235 reader.readYangInstanceIdentifier();
239 public void testWithSerializable() {
240 NormalizedNode<?, ?> input = TestModel.createTestContainer(uint64);
241 SampleNormalizedNodeSerializable serializable = new SampleNormalizedNodeSerializable(version, input);
242 SampleNormalizedNodeSerializable clone = clone(serializable);
243 Assert.assertEquals(input, clone.getInput());
247 public void testAnyXmlStreaming() throws Exception {
248 String xml = "<foo xmlns=\"http://www.w3.org/TR/html4/\" x=\"123\"><bar>one</bar><bar>two</bar></foo>";
249 final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
250 factory.setNamespaceAware(true);
252 Node xmlNode = factory.newDocumentBuilder().parse(
253 new InputSource(new StringReader(xml))).getDocumentElement();
255 assertEquals("http://www.w3.org/TR/html4/", xmlNode.getNamespaceURI());
257 NormalizedNode<?, ?> anyXmlContainer = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
258 new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).withChild(
259 Builders.anyXmlBuilder().withNodeIdentifier(new NodeIdentifier(TestModel.ANY_XML_QNAME))
260 .withValue(new DOMSource(xmlNode)).build()).build();
262 ByteArrayOutputStream bos = new ByteArrayOutputStream();
263 NormalizedNodeDataOutput nnout = version.newDataOutput(ByteStreams.newDataOutput(bos));
265 nnout.writeNormalizedNode(anyXmlContainer);
267 final byte[] bytes = bos.toByteArray();
268 assertEquals(anyxmlStreamingSize, bytes.length);
270 NormalizedNodeDataInput nnin = NormalizedNodeDataInput.newDataInput(ByteStreams.newDataInput(bytes));
272 ContainerNode deserialized = (ContainerNode)nnin.readNormalizedNode();
274 Optional<DataContainerChild<? extends PathArgument, ?>> child =
275 deserialized.getChild(new NodeIdentifier(TestModel.ANY_XML_QNAME));
276 assertEquals("AnyXml child present", true, child.isPresent());
278 StreamResult xmlOutput = new StreamResult(new StringWriter());
279 Transformer transformer = TransformerFactory.newInstance().newTransformer();
280 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
281 transformer.transform(((DOMSourceAnyxmlNode)child.get()).getValue(), xmlOutput);
283 assertEquals("XML", xml, xmlOutput.getWriter().toString());
284 assertEquals("http://www.w3.org/TR/html4/",
285 ((DOMSourceAnyxmlNode)child.get()).getValue().getNode().getNamespaceURI());
289 public void testSchemaPathSerialization() throws IOException {
290 final SchemaPath expected = SchemaPath.create(true, TestModel.ANY_XML_QNAME);
292 ByteArrayOutputStream bos = new ByteArrayOutputStream();
293 try (NormalizedNodeDataOutput nnout = version.newDataOutput(ByteStreams.newDataOutput(bos))) {
294 nnout.writeSchemaPath(expected);
297 final byte[] bytes = bos.toByteArray();
298 assertEquals(schemaPathSize, bytes.length);
300 NormalizedNodeDataInput nnin = NormalizedNodeDataInput.newDataInput(ByteStreams.newDataInput(bytes));
301 assertEquals(expected, nnin.readSchemaPath());
305 public void testWritePathArgument() throws IOException {
306 final NodeIdentifier expected = new NodeIdentifier(TestModel.BOOLEAN_LEAF_QNAME);
308 ByteArrayOutputStream bos = new ByteArrayOutputStream();
310 try (NormalizedNodeDataOutput nnout = version.newDataOutput(ByteStreams.newDataOutput(bos))) {
311 nnout.writePathArgument(expected);
314 final byte[] bytes = bos.toByteArray();
315 assertEquals(writePathArgumentSize, bytes.length);
317 NormalizedNodeDataInput nnin = NormalizedNodeDataInput.newDataInput(ByteStreams.newDataInput(bytes));
318 assertEquals(expected, nnin.readPathArgument());
322 * This tests the encoding of a MapNode with a lot of entries, each of them having the key leaf (a string)
326 public void testHugeEntries() throws IOException {
327 final CollectionNodeBuilder<MapEntryNode, MapNode> mapBuilder = Builders.mapBuilder()
328 .withNodeIdentifier(new NodeIdentifier(TestModel.TEST_QNAME));
329 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> entryBuilder =
330 Builders.mapEntryBuilder().withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, (byte) 42));
332 for (int i = 0; i < 100_000; ++i) {
333 final String key = "xyzzy" + i;
334 mapBuilder.addChild(entryBuilder
335 .withNodeIdentifier(NodeIdentifierWithPredicates.of(TestModel.TEST_QNAME,
336 TestModel.CHILD_NAME_QNAME, key))
337 .withChild(ImmutableNodes.leafNode(TestModel.CHILD_NAME_QNAME, key))
341 final MapNode expected = mapBuilder.build();
342 final ByteArrayOutputStream bos = new ByteArrayOutputStream();
344 try (NormalizedNodeDataOutput nnout = version.newDataOutput(ByteStreams.newDataOutput(bos))) {
345 nnout.writeNormalizedNode(expected);
348 final byte[] bytes = bos.toByteArray();
349 assertEquals(hugeEntriesSize, bytes.length);
351 NormalizedNodeDataInput nnin = NormalizedNodeDataInput.newDataInput(ByteStreams.newDataInput(bytes));
352 assertEquals(expected, nnin.readNormalizedNode());
356 public void testAugmentationIdentifier() throws IOException {
357 final List<QName> qnames = new ArrayList<>();
358 for (int i = 0; i < 257; ++i) {
359 qnames.add(QName.create(TestModel.TEST_QNAME, "a" + Integer.toHexString(i)));
362 for (int i = 0; i < qnames.size(); ++i) {
363 assertAugmentationIdentifier(AugmentationIdentifier.create(ImmutableSet.copyOf(qnames.subList(0, i))));
366 for (int i = qnames.size(); i < 65536; ++i) {
367 qnames.add(QName.create(TestModel.TEST_QNAME, "a" + Integer.toHexString(i)));
369 assertAugmentationIdentifier(AugmentationIdentifier.create(ImmutableSet.copyOf(qnames)));
372 private void assertAugmentationIdentifier(final AugmentationIdentifier expected) throws IOException {
373 final ByteArrayOutputStream bos = new ByteArrayOutputStream();
374 try (NormalizedNodeDataOutput nnout = version.newDataOutput(ByteStreams.newDataOutput(bos))) {
375 nnout.writePathArgument(expected);
378 final byte[] bytes = bos.toByteArray();
380 NormalizedNodeDataInput nnin = NormalizedNodeDataInput.newDataInput(ByteStreams.newDataInput(bytes));
381 PathArgument arg = nnin.readPathArgument();
382 assertEquals(expected, arg);
385 private static <T extends Serializable> T clone(final T obj) {
386 final ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
387 try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
388 oos.writeObject(obj);
389 } catch (IOException e) {
390 throw new AssertionError("Failed to serialize object", e);
393 final byte[] bytes = baos.toByteArray();
394 try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes))) {
395 return (T) ois.readObject();
396 } catch (ClassNotFoundException | IOException e) {
397 throw new AssertionError("Failed to deserialize object", e);
401 private static String largeString(final int pow) {
402 StringBuilder sb = new StringBuilder("X");
403 for (int i = 0; i < pow; i++) {
406 return sb.toString();