Bug 2062 - StreamWriter APIs loses information about leaf-set ordering
[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
9 package org.opendaylight.controller.cluster.datastore.node.utils.stream;
10
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Strings;
13 import java.io.DataInput;
14 import java.io.DataInputStream;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.math.BigDecimal;
18 import java.math.BigInteger;
19 import java.nio.charset.StandardCharsets;
20 import java.util.ArrayList;
21 import java.util.HashMap;
22 import java.util.HashSet;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Set;
26 import javax.xml.transform.dom.DOMSource;
27 import org.opendaylight.controller.cluster.datastore.node.utils.QNameFactory;
28 import org.opendaylight.yangtools.yang.common.QName;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
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.LeafNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
37 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
38 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
39 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
40 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 /**
45  * NormalizedNodeInputStreamReader reads the byte stream and constructs the normalized node including its children nodes.
46  * This process goes in recursive manner, where each NodeTypes object signifies the start of the object, except END_NODE.
47  * If a node can have children, then that node's end is calculated based on appearance of END_NODE.
48  *
49  */
50
51 public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput, NormalizedNodeStreamReader {
52
53     private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeInputStreamReader.class);
54
55     private static final String REVISION_ARG = "?revision=";
56
57     private final DataInput input;
58
59     private final Map<Integer, String> codedStringMap = new HashMap<>();
60
61     private QName lastLeafSetQName;
62
63     private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
64                                       Object, LeafNode<Object>> leafBuilder;
65
66     private NormalizedNodeAttrBuilder<NodeWithValue, Object,
67                                       LeafSetEntryNode<Object>> leafSetEntryBuilder;
68
69     private final StringBuilder reusableStringBuilder = new StringBuilder(50);
70
71     private boolean readSignatureMarker = true;
72
73     /**
74      * @deprecated Use {@link #NormalizedNodeInputStreamReader(DataInput)} instead.
75      */
76     @Deprecated
77     public NormalizedNodeInputStreamReader(final InputStream stream) throws IOException {
78         this((DataInput) new DataInputStream(Preconditions.checkNotNull(stream)));
79     }
80
81     /**
82      * @deprecated Use {@link NormalizedNodeInputOutput#newDataInput(DataInput)} instead.
83      */
84     @Deprecated
85     public NormalizedNodeInputStreamReader(final DataInput input) {
86         this(input, false);
87     }
88
89     NormalizedNodeInputStreamReader(final DataInput input, final boolean versionChecked) {
90         this.input = Preconditions.checkNotNull(input);
91         readSignatureMarker = !versionChecked;
92     }
93
94     @Override
95     public NormalizedNode<?, ?> readNormalizedNode() throws IOException {
96         readSignatureMarkerAndVersionIfNeeded();
97         return readNormalizedNodeInternal();
98     }
99
100     private void readSignatureMarkerAndVersionIfNeeded() throws IOException {
101         if(readSignatureMarker) {
102             readSignatureMarker = false;
103
104             final byte marker = input.readByte();
105             if (marker != TokenTypes.SIGNATURE_MARKER) {
106                 throw new InvalidNormalizedNodeStreamException(String.format(
107                         "Invalid signature marker: %d", marker));
108             }
109
110             final short version = input.readShort();
111             if (version != TokenTypes.LITHIUM_VERSION) {
112                 throw new InvalidNormalizedNodeStreamException(String.format("Unhandled stream version %s", version));
113             }
114         }
115     }
116
117     private NormalizedNode<?, ?> readNormalizedNodeInternal() throws IOException {
118         // each node should start with a byte
119         byte nodeType = input.readByte();
120
121         if(nodeType == NodeTypes.END_NODE) {
122             LOG.debug("End node reached. return");
123             return null;
124         }
125
126         switch(nodeType) {
127             case NodeTypes.AUGMENTATION_NODE :
128                 YangInstanceIdentifier.AugmentationIdentifier augIdentifier =
129                     new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
130
131                 LOG.debug("Reading augmentation node {} ", augIdentifier);
132
133                 return addDataContainerChildren(Builders.augmentationBuilder().
134                         withNodeIdentifier(augIdentifier)).build();
135
136             case NodeTypes.LEAF_SET_ENTRY_NODE :
137                 Object value = readObject();
138                 NodeWithValue leafIdentifier = new NodeWithValue(lastLeafSetQName, value);
139
140                 LOG.debug("Reading leaf set entry node {}, value {}", leafIdentifier, value);
141
142                 return leafSetEntryBuilder().withNodeIdentifier(leafIdentifier).withValue(value).build();
143
144             case NodeTypes.MAP_ENTRY_NODE :
145                 NodeIdentifierWithPredicates entryIdentifier = new NodeIdentifierWithPredicates(
146                         readQName(), readKeyValueMap());
147
148                 LOG.debug("Reading map entry node {} ", entryIdentifier);
149
150                 return addDataContainerChildren(Builders.mapEntryBuilder().
151                         withNodeIdentifier(entryIdentifier)).build();
152
153             default :
154                 return readNodeIdentifierDependentNode(nodeType, new NodeIdentifier(readQName()));
155         }
156     }
157
158     private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
159                                       Object, LeafNode<Object>> leafBuilder() {
160         if(leafBuilder == null) {
161             leafBuilder = Builders.leafBuilder();
162         }
163
164         return leafBuilder;
165     }
166
167     private NormalizedNodeAttrBuilder<NodeWithValue, Object,
168                                       LeafSetEntryNode<Object>> leafSetEntryBuilder() {
169         if(leafSetEntryBuilder == null) {
170             leafSetEntryBuilder = Builders.leafSetEntryBuilder();
171         }
172
173         return leafSetEntryBuilder;
174     }
175
176     private NormalizedNode<?, ?> readNodeIdentifierDependentNode(final byte nodeType, final NodeIdentifier identifier)
177         throws IOException {
178
179         switch(nodeType) {
180             case NodeTypes.LEAF_NODE :
181                 LOG.debug("Read leaf node {}", identifier);
182                 // Read the object value
183                 return leafBuilder().withNodeIdentifier(identifier).withValue(readObject()).build();
184
185             case NodeTypes.ANY_XML_NODE :
186                 LOG.debug("Read xml node");
187                 return Builders.anyXmlBuilder().withValue((DOMSource) readObject()).build();
188
189             case NodeTypes.MAP_NODE :
190                 LOG.debug("Read map node {}", identifier);
191                 return addDataContainerChildren(Builders.mapBuilder().
192                         withNodeIdentifier(identifier)).build();
193
194             case NodeTypes.CHOICE_NODE :
195                 LOG.debug("Read choice node {}", identifier);
196                 return addDataContainerChildren(Builders.choiceBuilder().
197                         withNodeIdentifier(identifier)).build();
198
199             case NodeTypes.ORDERED_MAP_NODE :
200                 LOG.debug("Reading ordered map node {}", identifier);
201                 return addDataContainerChildren(Builders.orderedMapBuilder().
202                         withNodeIdentifier(identifier)).build();
203
204             case NodeTypes.UNKEYED_LIST :
205                 LOG.debug("Read unkeyed list node {}", identifier);
206                 return addDataContainerChildren(Builders.unkeyedListBuilder().
207                         withNodeIdentifier(identifier)).build();
208
209             case NodeTypes.UNKEYED_LIST_ITEM :
210                 LOG.debug("Read unkeyed list item node {}", identifier);
211                 return addDataContainerChildren(Builders.unkeyedListEntryBuilder().
212                         withNodeIdentifier(identifier)).build();
213
214             case NodeTypes.CONTAINER_NODE :
215                 LOG.debug("Read container node {}", identifier);
216                 return addDataContainerChildren(Builders.containerBuilder().
217                         withNodeIdentifier(identifier)).build();
218
219             case NodeTypes.LEAF_SET :
220                 LOG.debug("Read leaf set node {}", identifier);
221                 return addLeafSetChildren(identifier.getNodeType(),
222                         Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
223
224             case NodeTypes.ORDERED_LEAF_SET:
225                 LOG.debug("Read leaf set node");
226                 ListNodeBuilder<Object, LeafSetEntryNode<Object>> orderedLeafSetBuilder =
227                         Builders.orderedLeafSetBuilder().withNodeIdentifier(identifier);
228                 orderedLeafSetBuilder = addLeafSetChildren(identifier.getNodeType(), orderedLeafSetBuilder);
229                 return orderedLeafSetBuilder.build();
230
231             default :
232                 return null;
233         }
234     }
235
236     private QName readQName() throws IOException {
237         // Read in the same sequence of writing
238         String localName = readCodedString();
239         String namespace = readCodedString();
240         String revision = readCodedString();
241
242         String qName;
243         if(!Strings.isNullOrEmpty(revision)) {
244             qName = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG).
245                         append(revision).append(')').append(localName).toString();
246         } else {
247             qName = reusableStringBuilder.append('(').append(namespace).append(')').
248                         append(localName).toString();
249         }
250
251         reusableStringBuilder.delete(0, reusableStringBuilder.length());
252         return QNameFactory.create(qName);
253     }
254
255
256     private String readCodedString() throws IOException {
257         byte valueType = input.readByte();
258         if(valueType == TokenTypes.IS_CODE_VALUE) {
259             return codedStringMap.get(input.readInt());
260         } else if(valueType == TokenTypes.IS_STRING_VALUE) {
261             String value = input.readUTF().intern();
262             codedStringMap.put(Integer.valueOf(codedStringMap.size()), value);
263             return value;
264         }
265
266         return null;
267     }
268
269     private Set<QName> readQNameSet() throws IOException{
270         // Read the children count
271         int count = input.readInt();
272         Set<QName> children = new HashSet<>(count);
273         for(int i = 0; i < count; i++) {
274             children.add(readQName());
275         }
276         return children;
277     }
278
279     private Map<QName, Object> readKeyValueMap() throws IOException {
280         int count = input.readInt();
281         Map<QName, Object> keyValueMap = new HashMap<>(count);
282
283         for(int i = 0; i < count; i++) {
284             keyValueMap.put(readQName(), readObject());
285         }
286
287         return keyValueMap;
288     }
289
290     private Object readObject() throws IOException {
291         byte objectType = input.readByte();
292         switch(objectType) {
293             case ValueTypes.BITS_TYPE:
294                 return readObjSet();
295
296             case ValueTypes.BOOL_TYPE :
297                 return Boolean.valueOf(input.readBoolean());
298
299             case ValueTypes.BYTE_TYPE :
300                 return Byte.valueOf(input.readByte());
301
302             case ValueTypes.INT_TYPE :
303                 return Integer.valueOf(input.readInt());
304
305             case ValueTypes.LONG_TYPE :
306                 return Long.valueOf(input.readLong());
307
308             case ValueTypes.QNAME_TYPE :
309                 return readQName();
310
311             case ValueTypes.SHORT_TYPE :
312                 return Short.valueOf(input.readShort());
313
314             case ValueTypes.STRING_TYPE :
315                 return input.readUTF();
316
317             case ValueTypes.STRING_BYTES_TYPE:
318                 return readStringBytes();
319
320             case ValueTypes.BIG_DECIMAL_TYPE :
321                 return new BigDecimal(input.readUTF());
322
323             case ValueTypes.BIG_INTEGER_TYPE :
324                 return new BigInteger(input.readUTF());
325
326             case ValueTypes.BINARY_TYPE :
327                 byte[] bytes = new byte[input.readInt()];
328                 input.readFully(bytes);
329                 return bytes;
330
331             case ValueTypes.YANG_IDENTIFIER_TYPE :
332                 return readYangInstanceIdentifierInternal();
333
334             default :
335                 return null;
336         }
337     }
338
339     private String readStringBytes() throws IOException {
340         byte[] bytes = new byte[input.readInt()];
341         input.readFully(bytes);
342         return new String(bytes, StandardCharsets.UTF_8);
343     }
344
345     @Override
346     public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
347         readSignatureMarkerAndVersionIfNeeded();
348         return readYangInstanceIdentifierInternal();
349     }
350
351     private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
352         int size = input.readInt();
353
354         List<PathArgument> pathArguments = new ArrayList<>(size);
355
356         for(int i = 0; i < size; i++) {
357             pathArguments.add(readPathArgument());
358         }
359         return YangInstanceIdentifier.create(pathArguments);
360     }
361
362     private Set<String> readObjSet() throws IOException {
363         int count = input.readInt();
364         Set<String> children = new HashSet<>(count);
365         for(int i = 0; i < count; i++) {
366             children.add(readCodedString());
367         }
368         return children;
369     }
370
371     @Override
372     public PathArgument readPathArgument() throws IOException {
373         // read Type
374         int type = input.readByte();
375
376         switch(type) {
377
378             case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
379                 return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
380
381             case PathArgumentTypes.NODE_IDENTIFIER :
382                 return new NodeIdentifier(readQName());
383
384             case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES :
385                 return new NodeIdentifierWithPredicates(readQName(), readKeyValueMap());
386
387             case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
388                 return new NodeWithValue(readQName(), readObject());
389
390             default :
391                 return null;
392         }
393     }
394
395     @SuppressWarnings("unchecked")
396     private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(final QName nodeType,
397             final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
398
399         LOG.debug("Reading children of leaf set");
400
401         lastLeafSetQName = nodeType;
402
403         LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
404
405         while(child != null) {
406             builder.withChild(child);
407             child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
408         }
409         return builder;
410     }
411
412     @SuppressWarnings({ "unchecked", "rawtypes" })
413     private NormalizedNodeContainerBuilder addDataContainerChildren(
414             final NormalizedNodeContainerBuilder builder) throws IOException {
415         LOG.debug("Reading data container (leaf nodes) nodes");
416
417         NormalizedNode<?, ?> child = readNormalizedNodeInternal();
418
419         while(child != null) {
420             builder.addChild(child);
421             child = readNormalizedNodeInternal();
422         }
423         return builder;
424     }
425
426     @Override
427     public void readFully(final byte[] b) throws IOException {
428         readSignatureMarkerAndVersionIfNeeded();
429         input.readFully(b);
430     }
431
432     @Override
433     public void readFully(final byte[] b, final int off, final int len) throws IOException {
434         readSignatureMarkerAndVersionIfNeeded();
435         input.readFully(b, off, len);
436     }
437
438     @Override
439     public int skipBytes(final int n) throws IOException {
440         readSignatureMarkerAndVersionIfNeeded();
441         return input.skipBytes(n);
442     }
443
444     @Override
445     public boolean readBoolean() throws IOException {
446         readSignatureMarkerAndVersionIfNeeded();
447         return input.readBoolean();
448     }
449
450     @Override
451     public byte readByte() throws IOException {
452         readSignatureMarkerAndVersionIfNeeded();
453         return input.readByte();
454     }
455
456     @Override
457     public int readUnsignedByte() throws IOException {
458         readSignatureMarkerAndVersionIfNeeded();
459         return input.readUnsignedByte();
460     }
461
462     @Override
463     public short readShort() throws IOException {
464         readSignatureMarkerAndVersionIfNeeded();
465         return input.readShort();
466     }
467
468     @Override
469     public int readUnsignedShort() throws IOException {
470         readSignatureMarkerAndVersionIfNeeded();
471         return input.readUnsignedShort();
472     }
473
474     @Override
475     public char readChar() throws IOException {
476         readSignatureMarkerAndVersionIfNeeded();
477         return input.readChar();
478     }
479
480     @Override
481     public int readInt() throws IOException {
482         readSignatureMarkerAndVersionIfNeeded();
483         return input.readInt();
484     }
485
486     @Override
487     public long readLong() throws IOException {
488         readSignatureMarkerAndVersionIfNeeded();
489         return input.readLong();
490     }
491
492     @Override
493     public float readFloat() throws IOException {
494         readSignatureMarkerAndVersionIfNeeded();
495         return input.readFloat();
496     }
497
498     @Override
499     public double readDouble() throws IOException {
500         readSignatureMarkerAndVersionIfNeeded();
501         return input.readDouble();
502     }
503
504     @Override
505     public String readLine() throws IOException {
506         readSignatureMarkerAndVersionIfNeeded();
507         return input.readLine();
508     }
509
510     @Override
511     public String readUTF() throws IOException {
512         readSignatureMarkerAndVersionIfNeeded();
513         return input.readUTF();
514     }
515 }