BUG-4626: create AbstractNormalizedNodeDataOutput
[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             default :
225                 return null;
226         }
227     }
228
229     private QName readQName() throws IOException {
230         // Read in the same sequence of writing
231         String localName = readCodedString();
232         String namespace = readCodedString();
233         String revision = readCodedString();
234
235         String qName;
236         if(!Strings.isNullOrEmpty(revision)) {
237             qName = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG).
238                         append(revision).append(')').append(localName).toString();
239         } else {
240             qName = reusableStringBuilder.append('(').append(namespace).append(')').
241                         append(localName).toString();
242         }
243
244         reusableStringBuilder.delete(0, reusableStringBuilder.length());
245         return QNameFactory.create(qName);
246     }
247
248
249     private String readCodedString() throws IOException {
250         byte valueType = input.readByte();
251         if(valueType == TokenTypes.IS_CODE_VALUE) {
252             return codedStringMap.get(input.readInt());
253         } else if(valueType == TokenTypes.IS_STRING_VALUE) {
254             String value = input.readUTF().intern();
255             codedStringMap.put(Integer.valueOf(codedStringMap.size()), value);
256             return value;
257         }
258
259         return null;
260     }
261
262     private Set<QName> readQNameSet() throws IOException{
263         // Read the children count
264         int count = input.readInt();
265         Set<QName> children = new HashSet<>(count);
266         for(int i = 0; i < count; i++) {
267             children.add(readQName());
268         }
269         return children;
270     }
271
272     private Map<QName, Object> readKeyValueMap() throws IOException {
273         int count = input.readInt();
274         Map<QName, Object> keyValueMap = new HashMap<>(count);
275
276         for(int i = 0; i < count; i++) {
277             keyValueMap.put(readQName(), readObject());
278         }
279
280         return keyValueMap;
281     }
282
283     private Object readObject() throws IOException {
284         byte objectType = input.readByte();
285         switch(objectType) {
286             case ValueTypes.BITS_TYPE:
287                 return readObjSet();
288
289             case ValueTypes.BOOL_TYPE :
290                 return Boolean.valueOf(input.readBoolean());
291
292             case ValueTypes.BYTE_TYPE :
293                 return Byte.valueOf(input.readByte());
294
295             case ValueTypes.INT_TYPE :
296                 return Integer.valueOf(input.readInt());
297
298             case ValueTypes.LONG_TYPE :
299                 return Long.valueOf(input.readLong());
300
301             case ValueTypes.QNAME_TYPE :
302                 return readQName();
303
304             case ValueTypes.SHORT_TYPE :
305                 return Short.valueOf(input.readShort());
306
307             case ValueTypes.STRING_TYPE :
308                 return input.readUTF();
309
310             case ValueTypes.STRING_BYTES_TYPE:
311                 return readStringBytes();
312
313             case ValueTypes.BIG_DECIMAL_TYPE :
314                 return new BigDecimal(input.readUTF());
315
316             case ValueTypes.BIG_INTEGER_TYPE :
317                 return new BigInteger(input.readUTF());
318
319             case ValueTypes.BINARY_TYPE :
320                 byte[] bytes = new byte[input.readInt()];
321                 input.readFully(bytes);
322                 return bytes;
323
324             case ValueTypes.YANG_IDENTIFIER_TYPE :
325                 return readYangInstanceIdentifierInternal();
326
327             default :
328                 return null;
329         }
330     }
331
332     private String readStringBytes() throws IOException {
333         byte[] bytes = new byte[input.readInt()];
334         input.readFully(bytes);
335         return new String(bytes, StandardCharsets.UTF_8);
336     }
337
338     @Override
339     public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
340         readSignatureMarkerAndVersionIfNeeded();
341         return readYangInstanceIdentifierInternal();
342     }
343
344     private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
345         int size = input.readInt();
346
347         List<PathArgument> pathArguments = new ArrayList<>(size);
348
349         for(int i = 0; i < size; i++) {
350             pathArguments.add(readPathArgument());
351         }
352         return YangInstanceIdentifier.create(pathArguments);
353     }
354
355     private Set<String> readObjSet() throws IOException {
356         int count = input.readInt();
357         Set<String> children = new HashSet<>(count);
358         for(int i = 0; i < count; i++) {
359             children.add(readCodedString());
360         }
361         return children;
362     }
363
364     @Override
365     public PathArgument readPathArgument() throws IOException {
366         // read Type
367         int type = input.readByte();
368
369         switch(type) {
370
371             case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
372                 return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
373
374             case PathArgumentTypes.NODE_IDENTIFIER :
375                 return new NodeIdentifier(readQName());
376
377             case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES :
378                 return new NodeIdentifierWithPredicates(readQName(), readKeyValueMap());
379
380             case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
381                 return new NodeWithValue(readQName(), readObject());
382
383             default :
384                 return null;
385         }
386     }
387
388     @SuppressWarnings("unchecked")
389     private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(final QName nodeType,
390             final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
391
392         LOG.debug("Reading children of leaf set");
393
394         lastLeafSetQName = nodeType;
395
396         LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
397
398         while(child != null) {
399             builder.withChild(child);
400             child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
401         }
402         return builder;
403     }
404
405     @SuppressWarnings({ "unchecked", "rawtypes" })
406     private NormalizedNodeContainerBuilder addDataContainerChildren(
407             final NormalizedNodeContainerBuilder builder) throws IOException {
408         LOG.debug("Reading data container (leaf nodes) nodes");
409
410         NormalizedNode<?, ?> child = readNormalizedNodeInternal();
411
412         while(child != null) {
413             builder.addChild(child);
414             child = readNormalizedNodeInternal();
415         }
416         return builder;
417     }
418
419     @Override
420     public void readFully(final byte[] b) throws IOException {
421         readSignatureMarkerAndVersionIfNeeded();
422         input.readFully(b);
423     }
424
425     @Override
426     public void readFully(final byte[] b, final int off, final int len) throws IOException {
427         readSignatureMarkerAndVersionIfNeeded();
428         input.readFully(b, off, len);
429     }
430
431     @Override
432     public int skipBytes(final int n) throws IOException {
433         readSignatureMarkerAndVersionIfNeeded();
434         return input.skipBytes(n);
435     }
436
437     @Override
438     public boolean readBoolean() throws IOException {
439         readSignatureMarkerAndVersionIfNeeded();
440         return input.readBoolean();
441     }
442
443     @Override
444     public byte readByte() throws IOException {
445         readSignatureMarkerAndVersionIfNeeded();
446         return input.readByte();
447     }
448
449     @Override
450     public int readUnsignedByte() throws IOException {
451         readSignatureMarkerAndVersionIfNeeded();
452         return input.readUnsignedByte();
453     }
454
455     @Override
456     public short readShort() throws IOException {
457         readSignatureMarkerAndVersionIfNeeded();
458         return input.readShort();
459     }
460
461     @Override
462     public int readUnsignedShort() throws IOException {
463         readSignatureMarkerAndVersionIfNeeded();
464         return input.readUnsignedShort();
465     }
466
467     @Override
468     public char readChar() throws IOException {
469         readSignatureMarkerAndVersionIfNeeded();
470         return input.readChar();
471     }
472
473     @Override
474     public int readInt() throws IOException {
475         readSignatureMarkerAndVersionIfNeeded();
476         return input.readInt();
477     }
478
479     @Override
480     public long readLong() throws IOException {
481         readSignatureMarkerAndVersionIfNeeded();
482         return input.readLong();
483     }
484
485     @Override
486     public float readFloat() throws IOException {
487         readSignatureMarkerAndVersionIfNeeded();
488         return input.readFloat();
489     }
490
491     @Override
492     public double readDouble() throws IOException {
493         readSignatureMarkerAndVersionIfNeeded();
494         return input.readDouble();
495     }
496
497     @Override
498     public String readLine() throws IOException {
499         readSignatureMarkerAndVersionIfNeeded();
500         return input.readLine();
501     }
502
503     @Override
504     public String readUTF() throws IOException {
505         readSignatureMarkerAndVersionIfNeeded();
506         return input.readUTF();
507     }
508 }