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