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