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