083a0497fc520a92bf93fa62c7dfac56fdc2f96a
[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
9 package org.opendaylight.controller.cluster.datastore.node.utils.stream;
10
11 import static org.junit.Assert.assertEquals;
12
13 import com.google.common.base.Optional;
14 import com.google.common.io.ByteStreams;
15 import java.io.ByteArrayOutputStream;
16 import java.io.IOException;
17 import java.io.StringReader;
18 import java.io.StringWriter;
19 import javax.xml.parsers.DocumentBuilderFactory;
20 import javax.xml.transform.OutputKeys;
21 import javax.xml.transform.Transformer;
22 import javax.xml.transform.TransformerFactory;
23 import javax.xml.transform.dom.DOMSource;
24 import javax.xml.transform.stream.StreamResult;
25 import org.apache.commons.lang.SerializationUtils;
26 import org.junit.Assert;
27 import org.junit.Test;
28 import org.opendaylight.controller.cluster.datastore.util.TestModel;
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.NodeWithValue;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
34 import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
37 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
39 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
40 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
41 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
42 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetEntryNodeBuilder;
43 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetNodeBuilder;
44 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
45 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
46 import org.w3c.dom.Node;
47 import org.xml.sax.InputSource;
48
49 public class NormalizedNodeStreamReaderWriterTest {
50
51     @Test
52     public void testNormalizedNodeStreaming() throws IOException {
53
54         ByteArrayOutputStream bos = new ByteArrayOutputStream();
55         NormalizedNodeDataOutput nnout = NormalizedNodeInputOutput.newDataOutput(ByteStreams.newDataOutput(bos));
56
57         NormalizedNode<?, ?> testContainer = createTestContainer();
58         nnout.writeNormalizedNode(testContainer);
59
60         QName toaster = QName.create("http://netconfcentral.org/ns/toaster","2009-11-20","toaster");
61         QName darknessFactor = QName.create("http://netconfcentral.org/ns/toaster","2009-11-20","darknessFactor");
62         QName description = QName.create("http://netconfcentral.org/ns/toaster","2009-11-20","description");
63         ContainerNode toasterNode = Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(toaster))
64                 .withChild(ImmutableNodes.leafNode(darknessFactor, "1000"))
65                 .withChild(ImmutableNodes.leafNode(description, largeString(20))).build();
66
67         ContainerNode toasterContainer = Builders.containerBuilder()
68                 .withNodeIdentifier(new NodeIdentifier(SchemaContext.NAME)).withChild(toasterNode).build();
69         nnout.writeNormalizedNode(toasterContainer);
70
71         NormalizedNodeDataInput nnin = NormalizedNodeInputOutput.newDataInput(ByteStreams.newDataInput(
72             bos.toByteArray()));
73
74         NormalizedNode<?,?> node = nnin.readNormalizedNode();
75         Assert.assertEquals(testContainer, node);
76
77         node = nnin.readNormalizedNode();
78         Assert.assertEquals(toasterContainer, node);
79     }
80
81     private static NormalizedNode<?, ?> createTestContainer() {
82         byte[] bytes1 = {1,2,3};
83         LeafSetEntryNode<Object> entry1 = ImmutableLeafSetEntryNodeBuilder.create().withNodeIdentifier(
84                 new NodeWithValue<>(TestModel.BINARY_LEAF_LIST_QNAME, bytes1)).withValue(bytes1).build();
85
86         byte[] bytes2 = {};
87         LeafSetEntryNode<Object> entry2 = ImmutableLeafSetEntryNodeBuilder.create().withNodeIdentifier(
88                 new NodeWithValue<>(TestModel.BINARY_LEAF_LIST_QNAME, bytes2)).withValue(bytes2).build();
89
90         LeafSetEntryNode<Object> entry3 = ImmutableLeafSetEntryNodeBuilder.create().withNodeIdentifier(
91                 new NodeWithValue<>(TestModel.BINARY_LEAF_LIST_QNAME, null)).withValue(null).build();
92
93         return TestModel.createBaseTestContainerBuilder()
94                 .withChild(ImmutableLeafSetNodeBuilder.create().withNodeIdentifier(
95                         new NodeIdentifier(TestModel.BINARY_LEAF_LIST_QNAME))
96                         .withChild(entry1).withChild(entry2).withChild(entry3).build())
97                 .withChild(ImmutableNodes.leafNode(TestModel.SOME_BINARY_DATA_QNAME, new byte[]{1,2,3,4}))
98                 .withChild(Builders.orderedMapBuilder()
99                       .withNodeIdentifier(new NodeIdentifier(TestModel.ORDERED_LIST_QNAME))
100                       .withChild(ImmutableNodes.mapEntry(TestModel.ORDERED_LIST_ENTRY_QNAME,
101                               TestModel.ID_QNAME, 11)).build()).build();
102     }
103
104     @Test
105     public void testYangInstanceIdentifierStreaming() throws IOException  {
106         YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.TEST_PATH)
107                 .node(TestModel.OUTER_LIST_QNAME).nodeWithKey(
108                         TestModel.INNER_LIST_QNAME, TestModel.ID_QNAME, 10).build();
109
110         ByteArrayOutputStream bos = new ByteArrayOutputStream();
111         NormalizedNodeDataOutput nnout = NormalizedNodeInputOutput.newDataOutput(ByteStreams.newDataOutput(bos));
112
113         nnout.writeYangInstanceIdentifier(path);
114
115         NormalizedNodeDataInput nnin = NormalizedNodeInputOutput.newDataInput(ByteStreams.newDataInput(
116             bos.toByteArray()));
117
118         YangInstanceIdentifier newPath = nnin.readYangInstanceIdentifier();
119         Assert.assertEquals(path, newPath);
120     }
121
122     @Test
123     public void testNormalizedNodeAndYangInstanceIdentifierStreaming() throws IOException {
124
125         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
126         NormalizedNodeOutputStreamWriter writer = new NormalizedNodeOutputStreamWriter(
127             ByteStreams.newDataOutput(byteArrayOutputStream));
128
129         NormalizedNode<?, ?> testContainer = TestModel.createBaseTestContainerBuilder().build();
130         writer.writeNormalizedNode(testContainer);
131
132         YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.TEST_PATH)
133                 .node(TestModel.OUTER_LIST_QNAME).nodeWithKey(
134                         TestModel.INNER_LIST_QNAME, TestModel.ID_QNAME, 10).build();
135
136         writer.writeYangInstanceIdentifier(path);
137
138         NormalizedNodeDataInput reader = NormalizedNodeInputOutput.newDataInput(
139             ByteStreams.newDataInput(byteArrayOutputStream.toByteArray()));
140
141         NormalizedNode<?,?> node = reader.readNormalizedNode();
142         Assert.assertEquals(testContainer, node);
143
144         YangInstanceIdentifier newPath = reader.readYangInstanceIdentifier();
145         Assert.assertEquals(path, newPath);
146
147         writer.close();
148     }
149
150     @Test(expected = InvalidNormalizedNodeStreamException.class, timeout = 10000)
151     public void testInvalidNormalizedNodeStream() throws IOException {
152         byte[] invalidBytes = {1,2,3};
153         NormalizedNodeDataInput reader = NormalizedNodeInputOutput.newDataInput(
154                 ByteStreams.newDataInput(invalidBytes));
155
156         reader.readNormalizedNode();
157     }
158
159     @Test(expected = InvalidNormalizedNodeStreamException.class, timeout = 10000)
160     public void testInvalidYangInstanceIdentifierStream() throws IOException {
161         byte[] invalidBytes = {1,2,3};
162         NormalizedNodeDataInput reader = NormalizedNodeInputOutput.newDataInput(
163             ByteStreams.newDataInput(invalidBytes));
164
165         reader.readYangInstanceIdentifier();
166     }
167
168     @Test
169     public void testWithSerializable() {
170         NormalizedNode<?, ?> input = TestModel.createTestContainer();
171         SampleNormalizedNodeSerializable serializable = new SampleNormalizedNodeSerializable(input);
172         SampleNormalizedNodeSerializable clone =
173                 (SampleNormalizedNodeSerializable)SerializationUtils.clone(serializable);
174
175         Assert.assertEquals(input, clone.getInput());
176     }
177
178     @Test
179     public void testAnyXmlStreaming() throws Exception {
180         String xml = "<foo xmlns=\"http://www.w3.org/TR/html4/\" x=\"123\"><bar>one</bar><bar>two</bar></foo>";
181         final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
182         factory.setNamespaceAware(true);
183
184         Node xmlNode = factory.newDocumentBuilder().parse(
185                 new InputSource(new StringReader(xml))).getDocumentElement();
186
187         assertEquals("http://www.w3.org/TR/html4/", xmlNode.getNamespaceURI());
188
189         NormalizedNode<?, ?> anyXmlContainer = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
190                 new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).withChild(
191                         Builders.anyXmlBuilder().withNodeIdentifier(new NodeIdentifier(TestModel.ANY_XML_QNAME))
192                             .withValue(new DOMSource(xmlNode)).build()).build();
193
194         ByteArrayOutputStream bos = new ByteArrayOutputStream();
195         NormalizedNodeDataOutput nnout = NormalizedNodeInputOutput.newDataOutput(ByteStreams.newDataOutput(bos));
196
197         nnout.writeNormalizedNode(anyXmlContainer);
198
199         NormalizedNodeDataInput nnin = NormalizedNodeInputOutput.newDataInput(ByteStreams.newDataInput(
200             bos.toByteArray()));
201
202         ContainerNode deserialized = (ContainerNode)nnin.readNormalizedNode();
203
204         Optional<DataContainerChild<? extends PathArgument, ?>> child =
205                 deserialized.getChild(new NodeIdentifier(TestModel.ANY_XML_QNAME));
206         assertEquals("AnyXml child present", true, child.isPresent());
207
208         StreamResult xmlOutput = new StreamResult(new StringWriter());
209         Transformer transformer = TransformerFactory.newInstance().newTransformer();
210         transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
211         transformer.transform(((AnyXmlNode)child.get()).getValue(), xmlOutput);
212
213         assertEquals("XML", xml, xmlOutput.getWriter().toString());
214         assertEquals("http://www.w3.org/TR/html4/", ((AnyXmlNode)child.get()).getValue().getNode().getNamespaceURI());
215     }
216
217     @Test
218     public void testSchemaPathSerialization() throws Exception {
219         final SchemaPath expected = SchemaPath.create(true, TestModel.ANY_XML_QNAME);
220
221         ByteArrayOutputStream bos = new ByteArrayOutputStream();
222         NormalizedNodeDataOutput nnout = NormalizedNodeInputOutput.newDataOutput(ByteStreams.newDataOutput(bos));
223         nnout.writeSchemaPath(expected);
224
225         NormalizedNodeDataInput nnin = NormalizedNodeInputOutput.newDataInput(ByteStreams.newDataInput(
226             bos.toByteArray()));
227         SchemaPath actual = nnin.readSchemaPath();
228         assertEquals(expected, actual);
229     }
230
231     private static String largeString(final int pow) {
232         String str = "X";
233         for (int i = 0; i < pow; i++) {
234             StringBuilder buf = new StringBuilder();
235             buf.append(str).append(str);
236             str = buf.toString();
237         }
238         return str;
239     }
240 }