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