1e57eb4b7ebbb240fed1b6b1e69e0e0fc0090c86
[controller.git] / opendaylight / md-sal / sal-clustering-commons / src / test / java / org / opendaylight / controller / cluster / datastore / node / utils / stream / NormalizedNodeStreamReaderWriterTest.java
1 /*
2  * Copyright (c) 2014, 2015 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 package org.opendaylight.controller.cluster.datastore.node.utils.stream;
9
10 import static org.junit.Assert.assertEquals;
11
12 import com.google.common.io.ByteStreams;
13 import java.io.ByteArrayOutputStream;
14 import java.io.IOException;
15 import java.io.StringReader;
16 import java.io.StringWriter;
17 import java.util.Optional;
18 import javax.xml.parsers.DocumentBuilderFactory;
19 import javax.xml.transform.OutputKeys;
20 import javax.xml.transform.Transformer;
21 import javax.xml.transform.TransformerFactory;
22 import javax.xml.transform.dom.DOMSource;
23 import javax.xml.transform.stream.StreamResult;
24 import org.apache.commons.lang.SerializationUtils;
25 import org.junit.Assert;
26 import org.junit.Test;
27 import org.opendaylight.controller.cluster.datastore.util.TestModel;
28 import org.opendaylight.yangtools.yang.common.Empty;
29 import org.opendaylight.yangtools.yang.common.QName;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
35 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
38 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
42 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
43 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
44 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
45 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
46 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
47 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetEntryNodeBuilder;
48 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetNodeBuilder;
49 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
50 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
51 import org.w3c.dom.Node;
52 import org.xml.sax.InputSource;
53
54 public class NormalizedNodeStreamReaderWriterTest {
55
56     @Test
57     public void testNormalizedNodeStreaming() throws IOException {
58
59         ByteArrayOutputStream bos = new ByteArrayOutputStream();
60         NormalizedNodeDataOutput nnout = NormalizedNodeInputOutput.newDataOutput(ByteStreams.newDataOutput(bos));
61
62         NormalizedNode<?, ?> testContainer = createTestContainer();
63         nnout.writeNormalizedNode(testContainer);
64
65         QName toaster = QName.create("http://netconfcentral.org/ns/toaster","2009-11-20","toaster");
66         QName darknessFactor = QName.create("http://netconfcentral.org/ns/toaster","2009-11-20","darknessFactor");
67         QName description = QName.create("http://netconfcentral.org/ns/toaster","2009-11-20","description");
68         ContainerNode toasterNode = Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(toaster))
69                 .withChild(ImmutableNodes.leafNode(darknessFactor, "1000"))
70                 .withChild(ImmutableNodes.leafNode(description, largeString(20))).build();
71
72         ContainerNode toasterContainer = Builders.containerBuilder()
73                 .withNodeIdentifier(new NodeIdentifier(SchemaContext.NAME)).withChild(toasterNode).build();
74         nnout.writeNormalizedNode(toasterContainer);
75
76         final byte[] bytes = bos.toByteArray();
77         assertEquals(1049619, bytes.length);
78
79         NormalizedNodeDataInput nnin = NormalizedNodeInputOutput.newDataInput(ByteStreams.newDataInput(bytes));
80
81         NormalizedNode<?, ?> node = nnin.readNormalizedNode();
82         Assert.assertEquals(testContainer, node);
83
84         node = nnin.readNormalizedNode();
85         Assert.assertEquals(toasterContainer, node);
86     }
87
88     private static NormalizedNode<?, ?> createTestContainer() {
89         byte[] bytes1 = {1, 2, 3};
90         LeafSetEntryNode<Object> entry1 = ImmutableLeafSetEntryNodeBuilder.create().withNodeIdentifier(
91                 new NodeWithValue<>(TestModel.BINARY_LEAF_LIST_QNAME, bytes1)).withValue(bytes1).build();
92
93         byte[] bytes2 = {};
94         LeafSetEntryNode<Object> entry2 = ImmutableLeafSetEntryNodeBuilder.create().withNodeIdentifier(
95                 new NodeWithValue<>(TestModel.BINARY_LEAF_LIST_QNAME, bytes2)).withValue(bytes2).build();
96
97         return TestModel.createBaseTestContainerBuilder()
98                 .withChild(ImmutableLeafSetNodeBuilder.create().withNodeIdentifier(
99                         new NodeIdentifier(TestModel.BINARY_LEAF_LIST_QNAME))
100                         .withChild(entry1).withChild(entry2).build())
101                 .withChild(ImmutableNodes.leafNode(TestModel.SOME_BINARY_DATA_QNAME, new byte[]{1, 2, 3, 4}))
102                 .withChild(ImmutableNodes.leafNode(TestModel.EMPTY_QNAME, Empty.getInstance()))
103                 .withChild(Builders.orderedMapBuilder()
104                       .withNodeIdentifier(new NodeIdentifier(TestModel.ORDERED_LIST_QNAME))
105                       .withChild(ImmutableNodes.mapEntry(TestModel.ORDERED_LIST_ENTRY_QNAME,
106                               TestModel.ID_QNAME, 11)).build()).build();
107     }
108
109     @Test
110     public void testYangInstanceIdentifierStreaming() throws IOException  {
111         YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.TEST_PATH)
112                 .node(TestModel.OUTER_LIST_QNAME).nodeWithKey(
113                         TestModel.INNER_LIST_QNAME, TestModel.ID_QNAME, 10).build();
114
115         ByteArrayOutputStream bos = new ByteArrayOutputStream();
116         NormalizedNodeDataOutput nnout = NormalizedNodeInputOutput.newDataOutput(ByteStreams.newDataOutput(bos));
117
118         nnout.writeYangInstanceIdentifier(path);
119
120         final byte[] bytes = bos.toByteArray();
121         assertEquals(139, bytes.length);
122
123         NormalizedNodeDataInput nnin = NormalizedNodeInputOutput.newDataInput(ByteStreams.newDataInput(bytes));
124
125         YangInstanceIdentifier newPath = nnin.readYangInstanceIdentifier();
126         Assert.assertEquals(path, newPath);
127     }
128
129     @Test
130     public void testNormalizedNodeAndYangInstanceIdentifierStreaming() throws IOException {
131
132         ByteArrayOutputStream bos = new ByteArrayOutputStream();
133         NormalizedNodeDataOutput writer = NormalizedNodeInputOutput.newDataOutput(
134             ByteStreams.newDataOutput(bos));
135
136         NormalizedNode<?, ?> testContainer = TestModel.createBaseTestContainerBuilder().build();
137         writer.writeNormalizedNode(testContainer);
138
139         YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.TEST_PATH)
140                 .node(TestModel.OUTER_LIST_QNAME).nodeWithKey(
141                         TestModel.INNER_LIST_QNAME, TestModel.ID_QNAME, 10).build();
142
143         writer.writeYangInstanceIdentifier(path);
144
145         final byte[] bytes = bos.toByteArray();
146         assertEquals(826, bytes.length);
147
148         NormalizedNodeDataInput reader = NormalizedNodeInputOutput.newDataInput(ByteStreams.newDataInput(bytes));
149
150         NormalizedNode<?,?> node = reader.readNormalizedNode();
151         Assert.assertEquals(testContainer, node);
152
153         YangInstanceIdentifier newPath = reader.readYangInstanceIdentifier();
154         Assert.assertEquals(path, newPath);
155
156         writer.close();
157     }
158
159     @Test(expected = InvalidNormalizedNodeStreamException.class, timeout = 10000)
160     public void testInvalidNormalizedNodeStream() throws IOException {
161         byte[] invalidBytes = {1, 2, 3};
162         NormalizedNodeDataInput reader = NormalizedNodeInputOutput.newDataInput(
163                 ByteStreams.newDataInput(invalidBytes));
164
165         reader.readNormalizedNode();
166     }
167
168     @Test(expected = InvalidNormalizedNodeStreamException.class, timeout = 10000)
169     public void testInvalidYangInstanceIdentifierStream() throws IOException {
170         byte[] invalidBytes = {1,2,3};
171         NormalizedNodeDataInput reader = NormalizedNodeInputOutput.newDataInput(
172             ByteStreams.newDataInput(invalidBytes));
173
174         reader.readYangInstanceIdentifier();
175     }
176
177     @Test
178     public void testWithSerializable() {
179         NormalizedNode<?, ?> input = TestModel.createTestContainer();
180         SampleNormalizedNodeSerializable serializable = new SampleNormalizedNodeSerializable(input);
181         SampleNormalizedNodeSerializable clone =
182                 (SampleNormalizedNodeSerializable)SerializationUtils.clone(serializable);
183
184         Assert.assertEquals(input, clone.getInput());
185     }
186
187     @Test
188     public void testAnyXmlStreaming() throws Exception {
189         String xml = "<foo xmlns=\"http://www.w3.org/TR/html4/\" x=\"123\"><bar>one</bar><bar>two</bar></foo>";
190         final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
191         factory.setNamespaceAware(true);
192
193         Node xmlNode = factory.newDocumentBuilder().parse(
194                 new InputSource(new StringReader(xml))).getDocumentElement();
195
196         assertEquals("http://www.w3.org/TR/html4/", xmlNode.getNamespaceURI());
197
198         NormalizedNode<?, ?> anyXmlContainer = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
199                 new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).withChild(
200                         Builders.anyXmlBuilder().withNodeIdentifier(new NodeIdentifier(TestModel.ANY_XML_QNAME))
201                             .withValue(new DOMSource(xmlNode)).build()).build();
202
203         ByteArrayOutputStream bos = new ByteArrayOutputStream();
204         NormalizedNodeDataOutput nnout = NormalizedNodeInputOutput.newDataOutput(ByteStreams.newDataOutput(bos));
205
206         nnout.writeNormalizedNode(anyXmlContainer);
207
208         final byte[] bytes = bos.toByteArray();
209         assertEquals(229, bytes.length);
210
211         NormalizedNodeDataInput nnin = NormalizedNodeInputOutput.newDataInput(ByteStreams.newDataInput(bytes));
212
213         ContainerNode deserialized = (ContainerNode)nnin.readNormalizedNode();
214
215         Optional<DataContainerChild<? extends PathArgument, ?>> child =
216                 deserialized.getChild(new NodeIdentifier(TestModel.ANY_XML_QNAME));
217         assertEquals("AnyXml child present", true, child.isPresent());
218
219         StreamResult xmlOutput = new StreamResult(new StringWriter());
220         Transformer transformer = TransformerFactory.newInstance().newTransformer();
221         transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
222         transformer.transform(((DOMSourceAnyxmlNode)child.get()).getValue(), xmlOutput);
223
224         assertEquals("XML", xml, xmlOutput.getWriter().toString());
225         assertEquals("http://www.w3.org/TR/html4/",
226             ((DOMSourceAnyxmlNode)child.get()).getValue().getNode().getNamespaceURI());
227     }
228
229     @Test
230     public void testSchemaPathSerialization() throws IOException {
231         final SchemaPath expected = SchemaPath.create(true, TestModel.ANY_XML_QNAME);
232
233         ByteArrayOutputStream bos = new ByteArrayOutputStream();
234         try (NormalizedNodeDataOutput nnout = NormalizedNodeInputOutput.newDataOutput(ByteStreams.newDataOutput(bos))) {
235             nnout.writeSchemaPath(expected);
236         }
237
238         final byte[] bytes = bos.toByteArray();
239         assertEquals(99, bytes.length);
240
241         NormalizedNodeDataInput nnin = NormalizedNodeInputOutput.newDataInput(ByteStreams.newDataInput(bytes));
242         assertEquals(expected, nnin.readSchemaPath());
243     }
244
245     @Test
246     public void testWritePathArgument() throws IOException {
247         final NodeIdentifier expected = new NodeIdentifier(TestModel.BOOLEAN_LEAF_QNAME);
248
249         ByteArrayOutputStream bos = new ByteArrayOutputStream();
250
251         try (NormalizedNodeDataOutput nnout = NormalizedNodeInputOutput.newDataOutput(ByteStreams.newDataOutput(bos))) {
252             nnout.writePathArgument(expected);
253         }
254
255         final byte[] bytes = bos.toByteArray();
256         assertEquals(103, bytes.length);
257
258         NormalizedNodeDataInput nnin = NormalizedNodeInputOutput.newDataInput(ByteStreams.newDataInput(bytes));
259         assertEquals(expected, nnin.readPathArgument());
260     }
261
262     /*
263      * This tests the encoding of a MapNode with a lot of entries, each of them having the key leaf (a string)
264      * and an integer.
265      */
266     @Test
267     public void testHugeEntries() throws IOException {
268         final CollectionNodeBuilder<MapEntryNode, MapNode> mapBuilder = Builders.mapBuilder()
269                 .withNodeIdentifier(new NodeIdentifier(TestModel.TEST_QNAME));
270         final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> entryBuilder =
271                 Builders.mapEntryBuilder().withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, (byte) 42));
272
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))
279                 .build());
280         }
281
282         final MapNode expected = mapBuilder.build();
283         final ByteArrayOutputStream bos = new ByteArrayOutputStream();
284
285         try (NormalizedNodeDataOutput nnout = NormalizedNodeInputOutput.newDataOutput(ByteStreams.newDataOutput(bos))) {
286             nnout.writeNormalizedNode(expected);
287         }
288
289         final byte[] bytes = bos.toByteArray();
290         assertEquals(2_289_103, bytes.length);
291
292         NormalizedNodeDataInput nnin = NormalizedNodeInputOutput.newDataInput(ByteStreams.newDataInput(bytes));
293         assertEquals(expected, nnin.readNormalizedNode());
294     }
295
296     private static String largeString(final int pow) {
297         StringBuilder sb = new StringBuilder("X");
298         for (int i = 0; i < pow; i++) {
299             sb.append(sb);
300         }
301         return sb.toString();
302     }
303 }