2aa0027e55756b8d81cfe65f29b12044f7bf5c91
[controller.git] / opendaylight / md-sal / sal-clustering-commons / src / main / java / org / opendaylight / controller / cluster / datastore / node / utils / stream / NormalizedNodeInputStreamReader.java
1 /*
2  *
3  *  Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
4  *
5  *  This program and the accompanying materials are made available under the
6  *  terms of the Eclipse Public License v1.0 which accompanies this distribution,
7  *  and is available at http://www.eclipse.org/legal/epl-v10.html
8  *
9  */
10
11 package org.opendaylight.controller.cluster.datastore.node.utils.stream;
12
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Strings;
15 import java.io.DataInput;
16 import java.io.DataInputStream;
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.math.BigDecimal;
20 import java.math.BigInteger;
21 import java.util.ArrayList;
22 import java.util.HashMap;
23 import java.util.HashSet;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Set;
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.Node;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
35 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
38 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
39 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
40 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
41 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 /**
46  * NormalizedNodeInputStreamReader reads the byte stream and constructs the normalized node including its children nodes.
47  * This process goes in recursive manner, where each NodeTypes object signifies the start of the object, except END_NODE.
48  * If a node can have children, then that node's end is calculated based on appearance of END_NODE.
49  *
50  */
51
52 public class NormalizedNodeInputStreamReader implements NormalizedNodeStreamReader {
53
54     private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeInputStreamReader.class);
55
56     private static final String REVISION_ARG = "?revision=";
57
58     private final DataInput input;
59
60     private final Map<Integer, String> codedStringMap = new HashMap<>();
61
62     private QName lastLeafSetQName;
63
64     private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
65                                       Object, LeafNode<Object>> leafBuilder;
66
67     private NormalizedNodeAttrBuilder<NodeWithValue, Object,
68                                       LeafSetEntryNode<Object>> leafSetEntryBuilder;
69
70     private final StringBuilder reusableStringBuilder = new StringBuilder(50);
71
72     public NormalizedNodeInputStreamReader(InputStream stream) throws IOException {
73         Preconditions.checkNotNull(stream);
74         input = new DataInputStream(stream);
75     }
76
77     public NormalizedNodeInputStreamReader(DataInput input) throws IOException {
78         this.input = Preconditions.checkNotNull(input);
79     }
80
81     @Override
82     public NormalizedNode<?, ?> readNormalizedNode() throws IOException {
83         // each node should start with a byte
84         byte nodeType = input.readByte();
85
86         if(nodeType == NodeTypes.END_NODE) {
87             LOG.debug("End node reached. return");
88             return null;
89         }
90
91         switch(nodeType) {
92             case NodeTypes.AUGMENTATION_NODE :
93                 YangInstanceIdentifier.AugmentationIdentifier augIdentifier =
94                     new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
95
96                 LOG.debug("Reading augmentation node {} ", augIdentifier);
97
98                 return addDataContainerChildren(Builders.augmentationBuilder().
99                         withNodeIdentifier(augIdentifier)).build();
100
101             case NodeTypes.LEAF_SET_ENTRY_NODE :
102                 Object value = readObject();
103                 NodeWithValue leafIdentifier = new NodeWithValue(lastLeafSetQName, value);
104
105                 LOG.debug("Reading leaf set entry node {}, value {}", leafIdentifier, value);
106
107                 return leafSetEntryBuilder().withNodeIdentifier(leafIdentifier).withValue(value).build();
108
109             case NodeTypes.MAP_ENTRY_NODE :
110                 NodeIdentifierWithPredicates entryIdentifier = new NodeIdentifierWithPredicates(
111                         readQName(), readKeyValueMap());
112
113                 LOG.debug("Reading map entry node {} ", entryIdentifier);
114
115                 return addDataContainerChildren(Builders.mapEntryBuilder().
116                         withNodeIdentifier(entryIdentifier)).build();
117
118             default :
119                 return readNodeIdentifierDependentNode(nodeType, new NodeIdentifier(readQName()));
120         }
121     }
122
123     private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
124                                       Object, LeafNode<Object>> leafBuilder() {
125         if(leafBuilder == null) {
126             leafBuilder = Builders.leafBuilder();
127         }
128
129         return leafBuilder;
130     }
131
132     private NormalizedNodeAttrBuilder<NodeWithValue, Object,
133                                       LeafSetEntryNode<Object>> leafSetEntryBuilder() {
134         if(leafSetEntryBuilder == null) {
135             leafSetEntryBuilder = Builders.leafSetEntryBuilder();
136         }
137
138         return leafSetEntryBuilder;
139     }
140
141     private NormalizedNode<?, ?> readNodeIdentifierDependentNode(byte nodeType, NodeIdentifier identifier)
142         throws IOException {
143
144         switch(nodeType) {
145             case NodeTypes.LEAF_NODE :
146                 LOG.debug("Read leaf node {}", identifier);
147                 // Read the object value
148                 return leafBuilder().withNodeIdentifier(identifier).withValue(readObject()).build();
149
150             case NodeTypes.ANY_XML_NODE :
151                 LOG.debug("Read xml node");
152                 return Builders.anyXmlBuilder().withValue((Node<?>) readObject()).build();
153
154             case NodeTypes.MAP_NODE :
155                 LOG.debug("Read map node {}", identifier);
156                 return addDataContainerChildren(Builders.mapBuilder().
157                         withNodeIdentifier(identifier)).build();
158
159             case NodeTypes.CHOICE_NODE :
160                 LOG.debug("Read choice node {}", identifier);
161                 return addDataContainerChildren(Builders.choiceBuilder().
162                         withNodeIdentifier(identifier)).build();
163
164             case NodeTypes.ORDERED_MAP_NODE :
165                 LOG.debug("Reading ordered map node {}", identifier);
166                 return addDataContainerChildren(Builders.orderedMapBuilder().
167                         withNodeIdentifier(identifier)).build();
168
169             case NodeTypes.UNKEYED_LIST :
170                 LOG.debug("Read unkeyed list node {}", identifier);
171                 return addDataContainerChildren(Builders.unkeyedListBuilder().
172                         withNodeIdentifier(identifier)).build();
173
174             case NodeTypes.UNKEYED_LIST_ITEM :
175                 LOG.debug("Read unkeyed list item node {}", identifier);
176                 return addDataContainerChildren(Builders.unkeyedListEntryBuilder().
177                         withNodeIdentifier(identifier)).build();
178
179             case NodeTypes.CONTAINER_NODE :
180                 LOG.debug("Read container node {}", identifier);
181                 return addDataContainerChildren(Builders.containerBuilder().
182                         withNodeIdentifier(identifier)).build();
183
184             case NodeTypes.LEAF_SET :
185                 LOG.debug("Read leaf set node {}", identifier);
186                 return addLeafSetChildren(identifier.getNodeType(),
187                         Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
188
189             default :
190                 return null;
191         }
192     }
193
194     private QName readQName() throws IOException {
195         // Read in the same sequence of writing
196         String localName = readCodedString();
197         String namespace = readCodedString();
198         String revision = readCodedString();
199
200         String qName;
201         if(!Strings.isNullOrEmpty(revision)) {
202             qName = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG).
203                         append(revision).append(')').append(localName).toString();
204         } else {
205             qName = reusableStringBuilder.append('(').append(namespace).append(')').
206                         append(localName).toString();
207         }
208
209         reusableStringBuilder.delete(0, reusableStringBuilder.length());
210         return QNameFactory.create(qName);
211     }
212
213
214     private String readCodedString() throws IOException {
215         byte valueType = input.readByte();
216         if(valueType == NormalizedNodeOutputStreamWriter.IS_CODE_VALUE) {
217             return codedStringMap.get(input.readInt());
218         } else if(valueType == NormalizedNodeOutputStreamWriter.IS_STRING_VALUE) {
219             String value = input.readUTF().intern();
220             codedStringMap.put(Integer.valueOf(codedStringMap.size()), value);
221             return value;
222         }
223
224         return null;
225     }
226
227     private Set<QName> readQNameSet() throws IOException{
228         // Read the children count
229         int count = input.readInt();
230         Set<QName> children = new HashSet<>(count);
231         for(int i = 0; i < count; i++) {
232             children.add(readQName());
233         }
234         return children;
235     }
236
237     private Map<QName, Object> readKeyValueMap() throws IOException {
238         int count = input.readInt();
239         Map<QName, Object> keyValueMap = new HashMap<>(count);
240
241         for(int i = 0; i < count; i++) {
242             keyValueMap.put(readQName(), readObject());
243         }
244
245         return keyValueMap;
246     }
247
248     private Object readObject() throws IOException {
249         byte objectType = input.readByte();
250         switch(objectType) {
251             case ValueTypes.BITS_TYPE:
252                 return readObjSet();
253
254             case ValueTypes.BOOL_TYPE :
255                 return Boolean.valueOf(input.readBoolean());
256
257             case ValueTypes.BYTE_TYPE :
258                 return Byte.valueOf(input.readByte());
259
260             case ValueTypes.INT_TYPE :
261                 return Integer.valueOf(input.readInt());
262
263             case ValueTypes.LONG_TYPE :
264                 return Long.valueOf(input.readLong());
265
266             case ValueTypes.QNAME_TYPE :
267                 return readQName();
268
269             case ValueTypes.SHORT_TYPE :
270                 return Short.valueOf(input.readShort());
271
272             case ValueTypes.STRING_TYPE :
273                 return input.readUTF();
274
275             case ValueTypes.BIG_DECIMAL_TYPE :
276                 return new BigDecimal(input.readUTF());
277
278             case ValueTypes.BIG_INTEGER_TYPE :
279                 return new BigInteger(input.readUTF());
280
281             case ValueTypes.BINARY_TYPE :
282                 byte[] bytes = new byte[input.readInt()];
283                 input.readFully(bytes);
284                 return bytes;
285
286             case ValueTypes.YANG_IDENTIFIER_TYPE :
287             return readYangInstanceIdentifier();
288
289             default :
290                 return null;
291         }
292     }
293
294     public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
295         int size = input.readInt();
296
297         List<PathArgument> pathArguments = new ArrayList<>(size);
298
299         for(int i = 0; i < size; i++) {
300             pathArguments.add(readPathArgument());
301         }
302         return YangInstanceIdentifier.create(pathArguments);
303     }
304
305     private Set<String> readObjSet() throws IOException {
306         int count = input.readInt();
307         Set<String> children = new HashSet<>(count);
308         for(int i = 0; i < count; i++) {
309             children.add(readCodedString());
310         }
311         return children;
312     }
313
314     private PathArgument readPathArgument() throws IOException {
315         // read Type
316         int type = input.readByte();
317
318         switch(type) {
319
320             case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
321                 return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
322
323             case PathArgumentTypes.NODE_IDENTIFIER :
324                 return new NodeIdentifier(readQName());
325
326             case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES :
327                 return new NodeIdentifierWithPredicates(readQName(), readKeyValueMap());
328
329             case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
330                 return new NodeWithValue(readQName(), readObject());
331
332             default :
333                 return null;
334         }
335     }
336
337     @SuppressWarnings("unchecked")
338     private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(QName nodeType,
339             ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
340
341         LOG.debug("Reading children of leaf set");
342
343         lastLeafSetQName = nodeType;
344
345         LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNode();
346
347         while(child != null) {
348             builder.withChild(child);
349             child = (LeafSetEntryNode<Object>)readNormalizedNode();
350         }
351         return builder;
352     }
353
354     @SuppressWarnings({ "unchecked", "rawtypes" })
355     private NormalizedNodeContainerBuilder addDataContainerChildren(
356             NormalizedNodeContainerBuilder builder) throws IOException {
357         LOG.debug("Reading data container (leaf nodes) nodes");
358
359         NormalizedNode<?, ?> child = readNormalizedNode();
360
361         while(child != null) {
362             builder.addChild(child);
363             child = readNormalizedNode();
364         }
365         return builder;
366     }
367 }