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