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