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