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