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