Separate lazy-versioned NormalizedNodeDataInput
[controller.git] / opendaylight / md-sal / sal-clustering-commons / src / main / java / org / opendaylight / controller / cluster / datastore / node / utils / stream / LithiumNormalizedNodeInputStreamReader.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 java.util.Objects.requireNonNull;
11
12 import com.google.common.base.Strings;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.ImmutableList.Builder;
15 import java.io.DataInput;
16 import java.io.IOException;
17 import java.io.StringReader;
18 import java.math.BigDecimal;
19 import java.math.BigInteger;
20 import java.nio.charset.StandardCharsets;
21 import java.util.ArrayList;
22 import java.util.HashSet;
23 import java.util.List;
24 import java.util.Set;
25 import javax.xml.parsers.DocumentBuilderFactory;
26 import javax.xml.parsers.ParserConfigurationException;
27 import javax.xml.transform.dom.DOMSource;
28 import org.eclipse.jdt.annotation.NonNull;
29 import org.opendaylight.controller.cluster.datastore.node.utils.QNameFactory;
30 import org.opendaylight.yangtools.util.ImmutableOffsetMapTemplate;
31 import org.opendaylight.yangtools.yang.common.Empty;
32 import org.opendaylight.yangtools.yang.common.QName;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
39 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
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.builder.api.ListNodeBuilder;
44 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
45 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
46 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.w3c.dom.Element;
50 import org.xml.sax.InputSource;
51 import org.xml.sax.SAXException;
52
53 /**
54  * NormalizedNodeInputStreamReader reads the byte stream and constructs the normalized node including its children
55  * nodes. This process goes in recursive manner, where each NodeTypes object signifies the start of the object, except
56  * END_NODE. If a node can have children, then that node's end is calculated based on appearance of END_NODE.
57  */
58 class LithiumNormalizedNodeInputStreamReader extends ForwardingDataInput implements NormalizedNodeDataInput {
59
60     private static final Logger LOG = LoggerFactory.getLogger(LithiumNormalizedNodeInputStreamReader.class);
61
62     private final @NonNull DataInput input;
63
64     private final List<String> codedStringMap = new ArrayList<>();
65
66     private QName lastLeafSetQName;
67
68     private NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder;
69
70     @SuppressWarnings("rawtypes")
71     private NormalizedNodeBuilder<NodeWithValue, Object, LeafSetEntryNode<Object>> leafSetEntryBuilder;
72
73     LithiumNormalizedNodeInputStreamReader(final DataInput input) {
74         this.input = requireNonNull(input);
75     }
76
77     @Override
78     final DataInput delegate() {
79         return input;
80     }
81
82     @Override
83     public NormalizedNodeStreamVersion getVersion() throws IOException {
84         return NormalizedNodeStreamVersion.LITHIUM;
85     }
86
87     @Override
88     public NormalizedNode<?, ?> readNormalizedNode() throws IOException {
89         return readNormalizedNodeInternal();
90     }
91
92     private NormalizedNode<?, ?> readNormalizedNodeInternal() throws IOException {
93         // each node should start with a byte
94         byte nodeType = input.readByte();
95
96         if (nodeType == NodeTypes.END_NODE) {
97             LOG.trace("End node reached. return");
98             lastLeafSetQName = null;
99             return null;
100         }
101
102         switch (nodeType) {
103             case NodeTypes.AUGMENTATION_NODE:
104                 AugmentationIdentifier augIdentifier = readAugmentationIdentifier();
105                 LOG.trace("Reading augmentation node {} ", augIdentifier);
106                 return addDataContainerChildren(Builders.augmentationBuilder().withNodeIdentifier(augIdentifier))
107                         .build();
108
109             case NodeTypes.LEAF_SET_ENTRY_NODE:
110                 final QName name = lastLeafSetQName != null ? lastLeafSetQName : readQName();
111                 final Object value = readObject();
112                 final NodeWithValue<Object> leafIdentifier = new NodeWithValue<>(name, value);
113                 LOG.trace("Reading leaf set entry node {}, value {}", leafIdentifier, value);
114                 return leafSetEntryBuilder().withNodeIdentifier(leafIdentifier).withValue(value).build();
115
116             case NodeTypes.MAP_ENTRY_NODE:
117                 final NodeIdentifierWithPredicates entryIdentifier = readNormalizedNodeWithPredicates();
118                 LOG.trace("Reading map entry node {} ", entryIdentifier);
119                 return addDataContainerChildren(Builders.mapEntryBuilder().withNodeIdentifier(entryIdentifier))
120                         .build();
121
122             default:
123                 return readNodeIdentifierDependentNode(nodeType, readNodeIdentifier());
124         }
125     }
126
127     private NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder() {
128         if (leafBuilder == null) {
129             leafBuilder = Builders.leafBuilder();
130         }
131
132         return leafBuilder;
133     }
134
135     @SuppressWarnings("rawtypes")
136     private NormalizedNodeBuilder<NodeWithValue, Object, LeafSetEntryNode<Object>> leafSetEntryBuilder() {
137         if (leafSetEntryBuilder == null) {
138             leafSetEntryBuilder = Builders.leafSetEntryBuilder();
139         }
140
141         return leafSetEntryBuilder;
142     }
143
144     private NormalizedNode<?, ?> readNodeIdentifierDependentNode(final byte nodeType, final NodeIdentifier identifier)
145         throws IOException {
146
147         switch (nodeType) {
148             case NodeTypes.LEAF_NODE:
149                 LOG.trace("Read leaf node {}", identifier);
150                 // Read the object value
151                 return leafBuilder().withNodeIdentifier(identifier).withValue(readObject()).build();
152
153             case NodeTypes.ANY_XML_NODE:
154                 LOG.trace("Read xml node");
155                 return Builders.anyXmlBuilder().withNodeIdentifier(identifier).withValue(readDOMSource()).build();
156
157             case NodeTypes.MAP_NODE:
158                 LOG.trace("Read map node {}", identifier);
159                 return addDataContainerChildren(Builders.mapBuilder().withNodeIdentifier(identifier)).build();
160
161             case NodeTypes.CHOICE_NODE:
162                 LOG.trace("Read choice node {}", identifier);
163                 return addDataContainerChildren(Builders.choiceBuilder().withNodeIdentifier(identifier)).build();
164
165             case NodeTypes.ORDERED_MAP_NODE:
166                 LOG.trace("Reading ordered map node {}", identifier);
167                 return addDataContainerChildren(Builders.orderedMapBuilder().withNodeIdentifier(identifier)).build();
168
169             case NodeTypes.UNKEYED_LIST:
170                 LOG.trace("Read unkeyed list node {}", identifier);
171                 return addDataContainerChildren(Builders.unkeyedListBuilder().withNodeIdentifier(identifier)).build();
172
173             case NodeTypes.UNKEYED_LIST_ITEM:
174                 LOG.trace("Read unkeyed list item node {}", identifier);
175                 return addDataContainerChildren(Builders.unkeyedListEntryBuilder()
176                         .withNodeIdentifier(identifier)).build();
177
178             case NodeTypes.CONTAINER_NODE:
179                 LOG.trace("Read container node {}", identifier);
180                 return addDataContainerChildren(Builders.containerBuilder().withNodeIdentifier(identifier)).build();
181
182             case NodeTypes.LEAF_SET:
183                 LOG.trace("Read leaf set node {}", identifier);
184                 return addLeafSetChildren(identifier.getNodeType(),
185                         Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
186
187             case NodeTypes.ORDERED_LEAF_SET:
188                 LOG.trace("Read ordered leaf set node {}", identifier);
189                 return addLeafSetChildren(identifier.getNodeType(),
190                         Builders.orderedLeafSetBuilder().withNodeIdentifier(identifier)).build();
191
192             default:
193                 return null;
194         }
195     }
196
197     private DOMSource readDOMSource() throws IOException {
198         String xml = readObject().toString();
199         try {
200             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
201             factory.setNamespaceAware(true);
202             Element node = factory.newDocumentBuilder().parse(
203                     new InputSource(new StringReader(xml))).getDocumentElement();
204             return new DOMSource(node);
205         } catch (SAXException | ParserConfigurationException e) {
206             throw new IOException("Error parsing XML: " + xml, e);
207         }
208     }
209
210     QName readQName() throws IOException {
211         // Read in the same sequence of writing
212         String localName = readCodedString();
213         String namespace = readCodedString();
214         String revision = Strings.emptyToNull(readCodedString());
215
216         return QNameFactory.create(new QNameFactory.Key(localName, namespace, revision));
217     }
218
219
220     private String readCodedString() throws IOException {
221         final byte valueType = input.readByte();
222         switch (valueType) {
223             case TokenTypes.IS_NULL_VALUE:
224                 return null;
225             case TokenTypes.IS_CODE_VALUE:
226                 final int code = input.readInt();
227                 try {
228                     return codedStringMap.get(code);
229                 } catch (IndexOutOfBoundsException e) {
230                     throw new IOException("String code " + code + " was not found", e);
231                 }
232             case TokenTypes.IS_STRING_VALUE:
233                 final String value = input.readUTF().intern();
234                 codedStringMap.add(value);
235                 return value;
236             default:
237                 throw new IOException("Unhandled string value type " + valueType);
238         }
239     }
240
241     private Set<QName> readQNameSet() throws IOException {
242         // Read the children count
243         int count = input.readInt();
244         Set<QName> children = new HashSet<>(count);
245         for (int i = 0; i < count; i++) {
246             children.add(readQName());
247         }
248         return children;
249     }
250
251     AugmentationIdentifier readAugmentationIdentifier() throws IOException {
252         return new AugmentationIdentifier(readQNameSet());
253     }
254
255     private NodeIdentifier readNodeIdentifier() throws IOException {
256         // FIXME: we should have a cache for these, too
257         return new NodeIdentifier(readQName());
258     }
259
260     private NodeIdentifierWithPredicates readNormalizedNodeWithPredicates() throws IOException {
261         final QName qname = readQName();
262         final int count = input.readInt();
263         switch (count) {
264             case 0:
265                 return new NodeIdentifierWithPredicates(qname);
266             case 1:
267                 return new NodeIdentifierWithPredicates(qname, readQName(), readObject());
268             default:
269                 // ImmutableList is used by ImmutableOffsetMapTemplate for lookups, hence we use that.
270                 final Builder<QName> keys = ImmutableList.builderWithExpectedSize(count);
271                 final Object[] values = new Object[count];
272                 for (int i = 0; i < count; i++) {
273                     keys.add(readQName());
274                     values[i] = readObject();
275                 }
276
277                 return new NodeIdentifierWithPredicates(qname, ImmutableOffsetMapTemplate.ordered(keys.build())
278                     .instantiateWithValues(values));
279         }
280     }
281
282     private Object readObject() throws IOException {
283         byte objectType = input.readByte();
284         switch (objectType) {
285             case ValueTypes.BITS_TYPE:
286                 return readObjSet();
287
288             case ValueTypes.BOOL_TYPE:
289                 return input.readBoolean();
290
291             case ValueTypes.BYTE_TYPE:
292                 return input.readByte();
293
294             case ValueTypes.INT_TYPE:
295                 return input.readInt();
296
297             case ValueTypes.LONG_TYPE:
298                 return input.readLong();
299
300             case ValueTypes.QNAME_TYPE:
301                 return readQName();
302
303             case ValueTypes.SHORT_TYPE:
304                 return input.readShort();
305
306             case ValueTypes.STRING_TYPE:
307                 return input.readUTF();
308
309             case ValueTypes.STRING_BYTES_TYPE:
310                 return readStringBytes();
311
312             case ValueTypes.BIG_DECIMAL_TYPE:
313                 return new BigDecimal(input.readUTF());
314
315             case ValueTypes.BIG_INTEGER_TYPE:
316                 return new BigInteger(input.readUTF());
317
318             case ValueTypes.BINARY_TYPE:
319                 byte[] bytes = new byte[input.readInt()];
320                 input.readFully(bytes);
321                 return bytes;
322
323             case ValueTypes.YANG_IDENTIFIER_TYPE:
324                 return readYangInstanceIdentifierInternal();
325
326             case ValueTypes.EMPTY_TYPE:
327             // Leaf nodes no longer allow null values and thus we no longer emit null values. Previously, the "empty"
328             // yang type was represented as null so we translate an incoming null value to Empty. It was possible for
329             // a BI user to set a string leaf to null and we're rolling the dice here but the chances for that are
330             // very low. We'd have to know the yang type but, even if we did, we can't let a null value pass upstream
331             // so we'd have to drop the leaf which might cause other issues.
332             case ValueTypes.NULL_TYPE:
333                 return Empty.getInstance();
334
335             default:
336                 return null;
337         }
338     }
339
340     private String readStringBytes() throws IOException {
341         byte[] bytes = new byte[input.readInt()];
342         input.readFully(bytes);
343         return new String(bytes, StandardCharsets.UTF_8);
344     }
345
346     @Override
347     public SchemaPath readSchemaPath() throws IOException {
348         final boolean absolute = input.readBoolean();
349         final int size = input.readInt();
350
351         final Builder<QName> qnames = ImmutableList.builderWithExpectedSize(size);
352         for (int i = 0; i < size; ++i) {
353             qnames.add(readQName());
354         }
355         return SchemaPath.create(qnames.build(), absolute);
356     }
357
358     @Override
359     public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
360         return readYangInstanceIdentifierInternal();
361     }
362
363     private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
364         int size = input.readInt();
365         final Builder<PathArgument> pathArguments = ImmutableList.builderWithExpectedSize(size);
366         for (int i = 0; i < size; i++) {
367             pathArguments.add(readPathArgument());
368         }
369         return YangInstanceIdentifier.create(pathArguments.build());
370     }
371
372     private Set<String> readObjSet() throws IOException {
373         int count = input.readInt();
374         Set<String> children = new HashSet<>(count);
375         for (int i = 0; i < count; i++) {
376             children.add(readCodedString());
377         }
378         return children;
379     }
380
381     @Override
382     public PathArgument readPathArgument() throws IOException {
383         // read Type
384         int type = input.readByte();
385
386         switch (type) {
387             case PathArgumentTypes.AUGMENTATION_IDENTIFIER:
388                 return readAugmentationIdentifier();
389             case PathArgumentTypes.NODE_IDENTIFIER:
390                 return readNodeIdentifier();
391             case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES:
392                 return readNormalizedNodeWithPredicates();
393             case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE:
394                 return new NodeWithValue<>(readQName(), readObject());
395             default:
396                 // FIXME: throw hard error
397                 return null;
398         }
399     }
400
401     @SuppressWarnings("unchecked")
402     private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(final QName nodeType,
403             final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
404
405         LOG.trace("Reading children of leaf set");
406
407         lastLeafSetQName = nodeType;
408
409         LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
410
411         while (child != null) {
412             builder.withChild(child);
413             child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
414         }
415         return builder;
416     }
417
418     @SuppressWarnings({ "unchecked", "rawtypes" })
419     private NormalizedNodeContainerBuilder addDataContainerChildren(
420             final NormalizedNodeContainerBuilder builder) throws IOException {
421         LOG.trace("Reading data container (leaf nodes) nodes");
422
423         NormalizedNode<?, ?> child = readNormalizedNodeInternal();
424
425         while (child != null) {
426             builder.addChild(child);
427             child = readNormalizedNodeInternal();
428         }
429         return builder;
430     }
431 }