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