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