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