Centralize read{Augmentation,Node}Identifier() methods
[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.NormalizedNodeAttrBuilder;
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 NormalizedNodeAttrBuilder<NodeIdentifier, 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 = 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 NormalizedNodeAttrBuilder<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 NormalizedNodeAttrBuilder<NodeWithValue, Object,
147                                       LeafSetEntryNode<Object>> leafSetEntryBuilder() {
148         if (leafSetEntryBuilder == null) {
149             leafSetEntryBuilder = Builders.leafSetEntryBuilder();
150         }
151
152         return leafSetEntryBuilder;
153     }
154
155     private NormalizedNode<?, ?> readNodeIdentifierDependentNode(final byte nodeType, final NodeIdentifier identifier)
156         throws IOException {
157
158         switch (nodeType) {
159             case NodeTypes.LEAF_NODE:
160                 LOG.trace("Read leaf node {}", identifier);
161                 // Read the object value
162                 return leafBuilder().withNodeIdentifier(identifier).withValue(readObject()).build();
163
164             case NodeTypes.ANY_XML_NODE:
165                 LOG.trace("Read xml node");
166                 return Builders.anyXmlBuilder().withNodeIdentifier(identifier).withValue(readDOMSource()).build();
167
168             case NodeTypes.MAP_NODE:
169                 LOG.trace("Read map node {}", identifier);
170                 return addDataContainerChildren(Builders.mapBuilder().withNodeIdentifier(identifier)).build();
171
172             case NodeTypes.CHOICE_NODE:
173                 LOG.trace("Read choice node {}", identifier);
174                 return addDataContainerChildren(Builders.choiceBuilder().withNodeIdentifier(identifier)).build();
175
176             case NodeTypes.ORDERED_MAP_NODE:
177                 LOG.trace("Reading ordered map node {}", identifier);
178                 return addDataContainerChildren(Builders.orderedMapBuilder().withNodeIdentifier(identifier)).build();
179
180             case NodeTypes.UNKEYED_LIST:
181                 LOG.trace("Read unkeyed list node {}", identifier);
182                 return addDataContainerChildren(Builders.unkeyedListBuilder().withNodeIdentifier(identifier)).build();
183
184             case NodeTypes.UNKEYED_LIST_ITEM:
185                 LOG.trace("Read unkeyed list item node {}", identifier);
186                 return addDataContainerChildren(Builders.unkeyedListEntryBuilder()
187                         .withNodeIdentifier(identifier)).build();
188
189             case NodeTypes.CONTAINER_NODE:
190                 LOG.trace("Read container node {}", identifier);
191                 return addDataContainerChildren(Builders.containerBuilder().withNodeIdentifier(identifier)).build();
192
193             case NodeTypes.LEAF_SET:
194                 LOG.trace("Read leaf set node {}", identifier);
195                 return addLeafSetChildren(identifier.getNodeType(),
196                         Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
197
198             case NodeTypes.ORDERED_LEAF_SET:
199                 LOG.trace("Read ordered leaf set node {}", identifier);
200                 return addLeafSetChildren(identifier.getNodeType(),
201                         Builders.orderedLeafSetBuilder().withNodeIdentifier(identifier)).build();
202
203             default:
204                 return null;
205         }
206     }
207
208     private DOMSource readDOMSource() throws IOException {
209         String xml = readObject().toString();
210         try {
211             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
212             factory.setNamespaceAware(true);
213             Element node = factory.newDocumentBuilder().parse(
214                     new InputSource(new StringReader(xml))).getDocumentElement();
215             return new DOMSource(node);
216         } catch (SAXException | ParserConfigurationException e) {
217             throw new IOException("Error parsing XML: " + xml, e);
218         }
219     }
220
221     private QName readQName() throws IOException {
222         // Read in the same sequence of writing
223         String localName = readCodedString();
224         String namespace = readCodedString();
225         String revision = Strings.emptyToNull(readCodedString());
226
227         return QNameFactory.create(new QNameFactory.Key(localName, namespace, revision));
228     }
229
230
231     private String readCodedString() throws IOException {
232         final byte valueType = input.readByte();
233         switch (valueType) {
234             case TokenTypes.IS_NULL_VALUE:
235                 return null;
236             case TokenTypes.IS_CODE_VALUE:
237                 final int code = input.readInt();
238                 try {
239                     return codedStringMap.get(code);
240                 } catch (IndexOutOfBoundsException e) {
241                     throw new IOException("String code " + code + " was not found", e);
242                 }
243             case TokenTypes.IS_STRING_VALUE:
244                 final String value = input.readUTF().intern();
245                 codedStringMap.add(value);
246                 return value;
247             default:
248                 throw new IOException("Unhandled string value type " + valueType);
249         }
250     }
251
252     private Set<QName> readQNameSet() throws IOException {
253         // Read the children count
254         int count = input.readInt();
255         Set<QName> children = new HashSet<>(count);
256         for (int i = 0; i < count; i++) {
257             children.add(readQName());
258         }
259         return children;
260     }
261
262     private AugmentationIdentifier readAugmentationIdentifier() throws IOException {
263         // FIXME: we should have a cache for these, too
264         return new AugmentationIdentifier(readQNameSet());
265     }
266
267     private NodeIdentifier readNodeIdentifier() throws IOException {
268         // FIXME: we should have a cache for these, too
269         return new NodeIdentifier(readQName());
270     }
271
272     private NodeIdentifierWithPredicates readNormalizedNodeWithPredicates() throws IOException {
273         final QName qname = readQName();
274         final int count = input.readInt();
275         switch (count) {
276             case 0:
277                 return new NodeIdentifierWithPredicates(qname);
278             case 1:
279                 return new NodeIdentifierWithPredicates(qname, readQName(), readObject());
280             default:
281                 // ImmutableList is used by ImmutableOffsetMapTemplate for lookups, hence we use that.
282                 final Builder<QName> keys = ImmutableList.builderWithExpectedSize(count);
283                 final Object[] values = new Object[count];
284                 for (int i = 0; i < count; i++) {
285                     keys.add(readQName());
286                     values[i] = readObject();
287                 }
288
289                 return new NodeIdentifierWithPredicates(qname, ImmutableOffsetMapTemplate.ordered(keys.build())
290                     .instantiateWithValues(values));
291         }
292     }
293
294     private Object readObject() throws IOException {
295         byte objectType = input.readByte();
296         switch (objectType) {
297             case ValueTypes.BITS_TYPE:
298                 return readObjSet();
299
300             case ValueTypes.BOOL_TYPE:
301                 return input.readBoolean();
302
303             case ValueTypes.BYTE_TYPE:
304                 return input.readByte();
305
306             case ValueTypes.INT_TYPE:
307                 return input.readInt();
308
309             case ValueTypes.LONG_TYPE:
310                 return input.readLong();
311
312             case ValueTypes.QNAME_TYPE:
313                 return readQName();
314
315             case ValueTypes.SHORT_TYPE:
316                 return input.readShort();
317
318             case ValueTypes.STRING_TYPE:
319                 return input.readUTF();
320
321             case ValueTypes.STRING_BYTES_TYPE:
322                 return readStringBytes();
323
324             case ValueTypes.BIG_DECIMAL_TYPE:
325                 return new BigDecimal(input.readUTF());
326
327             case ValueTypes.BIG_INTEGER_TYPE:
328                 return new BigInteger(input.readUTF());
329
330             case ValueTypes.BINARY_TYPE:
331                 byte[] bytes = new byte[input.readInt()];
332                 input.readFully(bytes);
333                 return bytes;
334
335             case ValueTypes.YANG_IDENTIFIER_TYPE:
336                 return readYangInstanceIdentifierInternal();
337
338             case ValueTypes.EMPTY_TYPE:
339             // Leaf nodes no longer allow null values and thus we no longer emit null values. Previously, the "empty"
340             // yang type was represented as null so we translate an incoming null value to Empty. It was possible for
341             // a BI user to set a string leaf to null and we're rolling the dice here but the chances for that are
342             // very low. We'd have to know the yang type but, even if we did, we can't let a null value pass upstream
343             // so we'd have to drop the leaf which might cause other issues.
344             case ValueTypes.NULL_TYPE:
345                 return Empty.getInstance();
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 SchemaPath readSchemaPath() throws IOException {
360         readSignatureMarkerAndVersionIfNeeded();
361
362         final boolean absolute = input.readBoolean();
363         final int size = input.readInt();
364
365         final Builder<QName> qnames = ImmutableList.builderWithExpectedSize(size);
366         for (int i = 0; i < size; ++i) {
367             qnames.add(readQName());
368         }
369         return SchemaPath.create(qnames.build(), absolute);
370     }
371
372     @Override
373     public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
374         readSignatureMarkerAndVersionIfNeeded();
375         return readYangInstanceIdentifierInternal();
376     }
377
378     private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
379         int size = input.readInt();
380         final Builder<PathArgument> pathArguments = ImmutableList.builderWithExpectedSize(size);
381         for (int i = 0; i < size; i++) {
382             pathArguments.add(readPathArgument());
383         }
384         return YangInstanceIdentifier.create(pathArguments.build());
385     }
386
387     private Set<String> readObjSet() throws IOException {
388         int count = input.readInt();
389         Set<String> children = new HashSet<>(count);
390         for (int i = 0; i < count; i++) {
391             children.add(readCodedString());
392         }
393         return children;
394     }
395
396     @Override
397     public PathArgument readPathArgument() throws IOException {
398         // read Type
399         int type = input.readByte();
400
401         switch (type) {
402             case PathArgumentTypes.AUGMENTATION_IDENTIFIER:
403                 return readAugmentationIdentifier();
404             case PathArgumentTypes.NODE_IDENTIFIER:
405                 return readNodeIdentifier();
406             case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES:
407                 return readNormalizedNodeWithPredicates();
408             case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE:
409                 return new NodeWithValue<>(readQName(), readObject());
410             default:
411                 // FIXME: throw hard error
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 }