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