Add QNameModule coding
[controller.git] / opendaylight / md-sal / sal-clustering-commons / src / main / java / org / opendaylight / controller / cluster / datastore / node / utils / stream / LithiumNormalizedNodeInputStreamReader.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 com.google.common.collect.Sets;
16 import java.io.DataInput;
17 import java.io.IOException;
18 import java.io.StringReader;
19 import java.math.BigDecimal;
20 import java.math.BigInteger;
21 import java.nio.charset.StandardCharsets;
22 import java.util.ArrayList;
23 import java.util.HashSet;
24 import java.util.List;
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.eclipse.jdt.annotation.NonNull;
30 import org.opendaylight.controller.cluster.datastore.node.utils.QNameFactory;
31 import org.opendaylight.yangtools.util.ImmutableOffsetMapTemplate;
32 import org.opendaylight.yangtools.yang.common.Empty;
33 import org.opendaylight.yangtools.yang.common.QName;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
40 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
43 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
44 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
45 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
46 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
47 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.w3c.dom.Element;
51 import org.xml.sax.InputSource;
52 import org.xml.sax.SAXException;
53
54 /**
55  * NormalizedNodeInputStreamReader reads the byte stream and constructs the normalized node including its children
56  * nodes. This process goes in recursive manner, where each NodeTypes object signifies the start of the object, except
57  * END_NODE. If a node can have children, then that node's end is calculated based on appearance of END_NODE.
58  */
59 class LithiumNormalizedNodeInputStreamReader extends ForwardingDataInput implements NormalizedNodeDataInput {
60
61     private static final Logger LOG = LoggerFactory.getLogger(LithiumNormalizedNodeInputStreamReader.class);
62
63     private final @NonNull DataInput input;
64
65     private final List<String> codedStringMap = new ArrayList<>();
66
67     private QName lastLeafSetQName;
68
69     private NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder;
70
71     @SuppressWarnings("rawtypes")
72     private NormalizedNodeBuilder<NodeWithValue, Object, LeafSetEntryNode<Object>> leafSetEntryBuilder;
73
74     LithiumNormalizedNodeInputStreamReader(final DataInput input) {
75         this.input = requireNonNull(input);
76     }
77
78     @Override
79     final DataInput delegate() {
80         return input;
81     }
82
83     @Override
84     public NormalizedNodeStreamVersion getVersion() throws IOException {
85         return NormalizedNodeStreamVersion.LITHIUM;
86     }
87
88     @Override
89     public NormalizedNode<?, ?> readNormalizedNode() throws IOException {
90         return readNormalizedNodeInternal();
91     }
92
93     private NormalizedNode<?, ?> readNormalizedNodeInternal() throws IOException {
94         // each node should start with a byte
95         byte nodeType = input.readByte();
96
97         if (nodeType == NodeTypes.END_NODE) {
98             LOG.trace("End node reached. return");
99             lastLeafSetQName = null;
100             return null;
101         }
102
103         switch (nodeType) {
104             case NodeTypes.AUGMENTATION_NODE:
105                 AugmentationIdentifier augIdentifier = readAugmentationIdentifier();
106                 LOG.trace("Reading augmentation node {} ", augIdentifier);
107                 return addDataContainerChildren(Builders.augmentationBuilder().withNodeIdentifier(augIdentifier))
108                         .build();
109
110             case NodeTypes.LEAF_SET_ENTRY_NODE:
111                 final QName name = lastLeafSetQName != null ? lastLeafSetQName : readQName();
112                 final Object value = readObject();
113                 final NodeWithValue<Object> leafIdentifier = new NodeWithValue<>(name, value);
114                 LOG.trace("Reading leaf set entry node {}, value {}", leafIdentifier, value);
115                 return leafSetEntryBuilder().withNodeIdentifier(leafIdentifier).withValue(value).build();
116
117             case NodeTypes.MAP_ENTRY_NODE:
118                 final NodeIdentifierWithPredicates entryIdentifier = readNormalizedNodeWithPredicates();
119                 LOG.trace("Reading map entry node {} ", entryIdentifier);
120                 return addDataContainerChildren(Builders.mapEntryBuilder().withNodeIdentifier(entryIdentifier))
121                         .build();
122
123             default:
124                 return readNodeIdentifierDependentNode(nodeType, readNodeIdentifier());
125         }
126     }
127
128     private NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder() {
129         if (leafBuilder == null) {
130             leafBuilder = Builders.leafBuilder();
131         }
132
133         return leafBuilder;
134     }
135
136     @SuppressWarnings("rawtypes")
137     private NormalizedNodeBuilder<NodeWithValue, Object, LeafSetEntryNode<Object>> leafSetEntryBuilder() {
138         if (leafSetEntryBuilder == null) {
139             leafSetEntryBuilder = Builders.leafSetEntryBuilder();
140         }
141
142         return leafSetEntryBuilder;
143     }
144
145     private NormalizedNode<?, ?> readNodeIdentifierDependentNode(final byte nodeType, final NodeIdentifier identifier)
146         throws IOException {
147
148         switch (nodeType) {
149             case NodeTypes.LEAF_NODE:
150                 LOG.trace("Read leaf node {}", identifier);
151                 // Read the object value
152                 return leafBuilder().withNodeIdentifier(identifier).withValue(readObject()).build();
153
154             case NodeTypes.ANY_XML_NODE:
155                 LOG.trace("Read xml node");
156                 return Builders.anyXmlBuilder().withNodeIdentifier(identifier).withValue(readDOMSource()).build();
157
158             case NodeTypes.MAP_NODE:
159                 LOG.trace("Read map node {}", identifier);
160                 return addDataContainerChildren(Builders.mapBuilder().withNodeIdentifier(identifier)).build();
161
162             case NodeTypes.CHOICE_NODE:
163                 LOG.trace("Read choice node {}", identifier);
164                 return addDataContainerChildren(Builders.choiceBuilder().withNodeIdentifier(identifier)).build();
165
166             case NodeTypes.ORDERED_MAP_NODE:
167                 LOG.trace("Reading ordered map node {}", identifier);
168                 return addDataContainerChildren(Builders.orderedMapBuilder().withNodeIdentifier(identifier)).build();
169
170             case NodeTypes.UNKEYED_LIST:
171                 LOG.trace("Read unkeyed list node {}", identifier);
172                 return addDataContainerChildren(Builders.unkeyedListBuilder().withNodeIdentifier(identifier)).build();
173
174             case NodeTypes.UNKEYED_LIST_ITEM:
175                 LOG.trace("Read unkeyed list item node {}", identifier);
176                 return addDataContainerChildren(Builders.unkeyedListEntryBuilder()
177                         .withNodeIdentifier(identifier)).build();
178
179             case NodeTypes.CONTAINER_NODE:
180                 LOG.trace("Read container node {}", identifier);
181                 return addDataContainerChildren(Builders.containerBuilder().withNodeIdentifier(identifier)).build();
182
183             case NodeTypes.LEAF_SET:
184                 LOG.trace("Read leaf set node {}", identifier);
185                 return addLeafSetChildren(identifier.getNodeType(),
186                         Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
187
188             case NodeTypes.ORDERED_LEAF_SET:
189                 LOG.trace("Read ordered leaf set node {}", identifier);
190                 return addLeafSetChildren(identifier.getNodeType(),
191                         Builders.orderedLeafSetBuilder().withNodeIdentifier(identifier)).build();
192
193             default:
194                 return null;
195         }
196     }
197
198     private DOMSource readDOMSource() throws IOException {
199         String xml = readObject().toString();
200         try {
201             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
202             factory.setNamespaceAware(true);
203             Element node = factory.newDocumentBuilder().parse(
204                     new InputSource(new StringReader(xml))).getDocumentElement();
205             return new DOMSource(node);
206         } catch (SAXException | ParserConfigurationException e) {
207             throw new IOException("Error parsing XML: " + xml, e);
208         }
209     }
210
211     QName readQName() throws IOException {
212         // Read in the same sequence of writing
213         String localName = readCodedString();
214         String namespace = readCodedString();
215         String revision = Strings.emptyToNull(readCodedString());
216
217         return QNameFactory.create(localName, namespace, revision);
218     }
219
220     final String readCodedString() throws IOException {
221         final byte valueType = input.readByte();
222         switch (valueType) {
223             case TokenTypes.IS_NULL_VALUE:
224                 return null;
225             case TokenTypes.IS_CODE_VALUE:
226                 final int code = input.readInt();
227                 try {
228                     return codedStringMap.get(code);
229                 } catch (IndexOutOfBoundsException e) {
230                     throw new IOException("String code " + code + " was not found", e);
231                 }
232             case TokenTypes.IS_STRING_VALUE:
233                 final String value = input.readUTF().intern();
234                 codedStringMap.add(value);
235                 return value;
236             default:
237                 throw new IOException("Unhandled string value type " + valueType);
238         }
239     }
240
241     private Set<QName> readQNameSet() throws IOException {
242         // Read the children count
243         final int count = input.readInt();
244         final Set<QName> children = Sets.newHashSetWithExpectedSize(count);
245         for (int i = 0; i < count; i++) {
246             children.add(readQName());
247         }
248         return children;
249     }
250
251     AugmentationIdentifier readAugmentationIdentifier() throws IOException {
252         return AugmentationIdentifier.create(readQNameSet());
253     }
254
255     NodeIdentifier readNodeIdentifier() throws IOException {
256         return new NodeIdentifier(readQName());
257     }
258
259     private NodeIdentifierWithPredicates readNormalizedNodeWithPredicates() throws IOException {
260         final QName qname = readQName();
261         final int count = input.readInt();
262         switch (count) {
263             case 0:
264                 return NodeIdentifierWithPredicates.of(qname);
265             case 1:
266                 return NodeIdentifierWithPredicates.of(qname, readQName(), readObject());
267             default:
268                 // ImmutableList is used by ImmutableOffsetMapTemplate for lookups, hence we use that.
269                 final Builder<QName> keys = ImmutableList.builderWithExpectedSize(count);
270                 final Object[] values = new Object[count];
271                 for (int i = 0; i < count; i++) {
272                     keys.add(readQName());
273                     values[i] = readObject();
274                 }
275
276                 return NodeIdentifierWithPredicates.of(qname, ImmutableOffsetMapTemplate.ordered(keys.build())
277                     .instantiateWithValues(values));
278         }
279     }
280
281     private Object readObject() throws IOException {
282         byte objectType = input.readByte();
283         switch (objectType) {
284             case ValueTypes.BITS_TYPE:
285                 return readObjSet();
286
287             case ValueTypes.BOOL_TYPE:
288                 return input.readBoolean();
289
290             case ValueTypes.BYTE_TYPE:
291                 return input.readByte();
292
293             case ValueTypes.INT_TYPE:
294                 return input.readInt();
295
296             case ValueTypes.LONG_TYPE:
297                 return input.readLong();
298
299             case ValueTypes.QNAME_TYPE:
300                 return readQName();
301
302             case ValueTypes.SHORT_TYPE:
303                 return input.readShort();
304
305             case ValueTypes.STRING_TYPE:
306                 return input.readUTF();
307
308             case ValueTypes.STRING_BYTES_TYPE:
309                 return readStringBytes();
310
311             case ValueTypes.BIG_DECIMAL_TYPE:
312                 return new BigDecimal(input.readUTF());
313
314             case ValueTypes.BIG_INTEGER_TYPE:
315                 return new BigInteger(input.readUTF());
316
317             case ValueTypes.BINARY_TYPE:
318                 byte[] bytes = new byte[input.readInt()];
319                 input.readFully(bytes);
320                 return bytes;
321
322             case ValueTypes.YANG_IDENTIFIER_TYPE:
323                 return readYangInstanceIdentifierInternal();
324
325             case ValueTypes.EMPTY_TYPE:
326             // Leaf nodes no longer allow null values and thus we no longer emit null values. Previously, the "empty"
327             // yang type was represented as null so we translate an incoming null value to Empty. It was possible for
328             // a BI user to set a string leaf to null and we're rolling the dice here but the chances for that are
329             // very low. We'd have to know the yang type but, even if we did, we can't let a null value pass upstream
330             // so we'd have to drop the leaf which might cause other issues.
331             case ValueTypes.NULL_TYPE:
332                 return Empty.getInstance();
333
334             default:
335                 return null;
336         }
337     }
338
339     private String readStringBytes() throws IOException {
340         byte[] bytes = new byte[input.readInt()];
341         input.readFully(bytes);
342         return new String(bytes, StandardCharsets.UTF_8);
343     }
344
345     @Override
346     public SchemaPath readSchemaPath() throws IOException {
347         final boolean absolute = input.readBoolean();
348         final int size = input.readInt();
349
350         final Builder<QName> qnames = ImmutableList.builderWithExpectedSize(size);
351         for (int i = 0; i < size; ++i) {
352             qnames.add(readQName());
353         }
354         return SchemaPath.create(qnames.build(), absolute);
355     }
356
357     @Override
358     public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
359         return readYangInstanceIdentifierInternal();
360     }
361
362     private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
363         int size = input.readInt();
364         final Builder<PathArgument> pathArguments = ImmutableList.builderWithExpectedSize(size);
365         for (int i = 0; i < size; i++) {
366             pathArguments.add(readPathArgument());
367         }
368         return YangInstanceIdentifier.create(pathArguments.build());
369     }
370
371     private Set<String> readObjSet() throws IOException {
372         int count = input.readInt();
373         Set<String> children = new HashSet<>(count);
374         for (int i = 0; i < count; i++) {
375             children.add(readCodedString());
376         }
377         return children;
378     }
379
380     @Override
381     public PathArgument readPathArgument() throws IOException {
382         // read Type
383         int type = input.readByte();
384
385         switch (type) {
386             case PathArgumentTypes.AUGMENTATION_IDENTIFIER:
387                 return readAugmentationIdentifier();
388             case PathArgumentTypes.NODE_IDENTIFIER:
389                 return readNodeIdentifier();
390             case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES:
391                 return readNormalizedNodeWithPredicates();
392             case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE:
393                 return new NodeWithValue<>(readQName(), readObject());
394             default:
395                 // FIXME: throw hard error
396                 return null;
397         }
398     }
399
400     @SuppressWarnings("unchecked")
401     private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(final QName nodeType,
402             final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
403
404         LOG.trace("Reading children of leaf set");
405
406         lastLeafSetQName = nodeType;
407
408         LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
409
410         while (child != null) {
411             builder.withChild(child);
412             child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
413         }
414         return builder;
415     }
416
417     @SuppressWarnings({ "unchecked", "rawtypes" })
418     private NormalizedNodeContainerBuilder addDataContainerChildren(
419             final NormalizedNodeContainerBuilder builder) throws IOException {
420         LOG.trace("Reading data container (leaf nodes) nodes");
421
422         NormalizedNode<?, ?> child = readNormalizedNodeInternal();
423
424         while (child != null) {
425             builder.addChild(child);
426             child = readNormalizedNodeInternal();
427         }
428         return builder;
429     }
430 }