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