3b912e6cb9064e2bd7ff50a5bbaa72e629eea131
[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 java.io.DataInput;
14 import java.io.IOException;
15 import java.io.StringReader;
16 import java.math.BigDecimal;
17 import java.math.BigInteger;
18 import java.nio.charset.StandardCharsets;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.HashMap;
22 import java.util.HashSet;
23 import java.util.List;
24 import java.util.Map;
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.opendaylight.controller.cluster.datastore.node.utils.QNameFactory;
30 import org.opendaylight.yangtools.yang.common.QName;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
36 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
39 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
40 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
41 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
42 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
43 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.w3c.dom.Element;
47 import org.xml.sax.InputSource;
48 import org.xml.sax.SAXException;
49
50 /**
51  * NormalizedNodeInputStreamReader reads the byte stream and constructs the normalized node including its children
52  * nodes. This process goes in recursive manner, where each NodeTypes object signifies the start of the object, except
53  * END_NODE. If a node can have children, then that node's end is calculated based on appearance of END_NODE.
54  */
55 public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput {
56
57     private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeInputStreamReader.class);
58
59     private static final String REVISION_ARG = "?revision=";
60
61     private final DataInput input;
62
63     private final Map<Integer, String> codedStringMap = new HashMap<>();
64
65     private QName lastLeafSetQName;
66
67     private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
68                                       Object, LeafNode<Object>> leafBuilder;
69
70     @SuppressWarnings("rawtypes")
71     private NormalizedNodeAttrBuilder<NodeWithValue, Object, LeafSetEntryNode<Object>> leafSetEntryBuilder;
72
73     private final StringBuilder reusableStringBuilder = new StringBuilder(50);
74
75     private boolean readSignatureMarker = true;
76
77     NormalizedNodeInputStreamReader(final DataInput input, final boolean versionChecked) {
78         this.input = Preconditions.checkNotNull(input);
79         readSignatureMarker = !versionChecked;
80     }
81
82     @Override
83     public NormalizedNode<?, ?> readNormalizedNode() throws IOException {
84         readSignatureMarkerAndVersionIfNeeded();
85         return readNormalizedNodeInternal();
86     }
87
88     private void readSignatureMarkerAndVersionIfNeeded() throws IOException {
89         if (readSignatureMarker) {
90             readSignatureMarker = false;
91
92             final byte marker = input.readByte();
93             if (marker != TokenTypes.SIGNATURE_MARKER) {
94                 throw new InvalidNormalizedNodeStreamException(String.format(
95                         "Invalid signature marker: %d", marker));
96             }
97
98             final short version = input.readShort();
99             if (version != TokenTypes.LITHIUM_VERSION) {
100                 throw new InvalidNormalizedNodeStreamException(String.format("Unhandled stream version %s", version));
101             }
102         }
103     }
104
105     private NormalizedNode<?, ?> readNormalizedNodeInternal() throws IOException {
106         // each node should start with a byte
107         byte nodeType = input.readByte();
108
109         if (nodeType == NodeTypes.END_NODE) {
110             LOG.trace("End node reached. return");
111             lastLeafSetQName = null;
112             return null;
113         }
114
115         switch (nodeType) {
116             case NodeTypes.AUGMENTATION_NODE :
117                 YangInstanceIdentifier.AugmentationIdentifier augIdentifier =
118                     new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
119
120                 LOG.trace("Reading augmentation node {} ", augIdentifier);
121
122                 return addDataContainerChildren(Builders.augmentationBuilder()
123                         .withNodeIdentifier(augIdentifier)).build();
124
125             case NodeTypes.LEAF_SET_ENTRY_NODE :
126                 QName name = lastLeafSetQName;
127                 if (name == null) {
128                     name = readQName();
129                 }
130
131                 Object value = readObject();
132                 NodeWithValue<Object> leafIdentifier = new NodeWithValue<>(name, value);
133
134                 LOG.trace("Reading leaf set entry node {}, value {}", leafIdentifier, value);
135
136                 return leafSetEntryBuilder().withNodeIdentifier(leafIdentifier).withValue(value).build();
137
138             case NodeTypes.MAP_ENTRY_NODE :
139                 NodeIdentifierWithPredicates entryIdentifier = new NodeIdentifierWithPredicates(
140                         readQName(), readKeyValueMap());
141
142                 LOG.trace("Reading map entry node {} ", entryIdentifier);
143
144                 return addDataContainerChildren(Builders.mapEntryBuilder()
145                         .withNodeIdentifier(entryIdentifier)).build();
146
147             default :
148                 return readNodeIdentifierDependentNode(nodeType, new NodeIdentifier(readQName()));
149         }
150     }
151
152     private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
153                                       Object, LeafNode<Object>> leafBuilder() {
154         if (leafBuilder == null) {
155             leafBuilder = Builders.leafBuilder();
156         }
157
158         return leafBuilder;
159     }
160
161     @SuppressWarnings("rawtypes")
162     private NormalizedNodeAttrBuilder<NodeWithValue, Object,
163                                       LeafSetEntryNode<Object>> leafSetEntryBuilder() {
164         if (leafSetEntryBuilder == null) {
165             leafSetEntryBuilder = Builders.leafSetEntryBuilder();
166         }
167
168         return leafSetEntryBuilder;
169     }
170
171     private NormalizedNode<?, ?> readNodeIdentifierDependentNode(final byte nodeType, final NodeIdentifier identifier)
172         throws IOException {
173
174         switch (nodeType) {
175             case NodeTypes.LEAF_NODE :
176                 LOG.trace("Read leaf node {}", identifier);
177                 // Read the object value
178                 return leafBuilder().withNodeIdentifier(identifier).withValue(readObject()).build();
179
180             case NodeTypes.ANY_XML_NODE :
181                 LOG.trace("Read xml node");
182                 return Builders.anyXmlBuilder().withNodeIdentifier(identifier).withValue(readDOMSource()).build();
183
184             case NodeTypes.MAP_NODE :
185                 LOG.trace("Read map node {}", identifier);
186                 return addDataContainerChildren(Builders.mapBuilder().withNodeIdentifier(identifier)).build();
187
188             case NodeTypes.CHOICE_NODE:
189                 LOG.trace("Read choice node {}", identifier);
190                 return addDataContainerChildren(Builders.choiceBuilder().withNodeIdentifier(identifier)).build();
191
192             case NodeTypes.ORDERED_MAP_NODE:
193                 LOG.trace("Reading ordered map node {}", identifier);
194                 return addDataContainerChildren(Builders.orderedMapBuilder().withNodeIdentifier(identifier)).build();
195
196             case NodeTypes.UNKEYED_LIST:
197                 LOG.trace("Read unkeyed list node {}", identifier);
198                 return addDataContainerChildren(Builders.unkeyedListBuilder().withNodeIdentifier(identifier)).build();
199
200             case NodeTypes.UNKEYED_LIST_ITEM:
201                 LOG.trace("Read unkeyed list item node {}", identifier);
202                 return addDataContainerChildren(Builders.unkeyedListEntryBuilder()
203                         .withNodeIdentifier(identifier)).build();
204
205             case NodeTypes.CONTAINER_NODE:
206                 LOG.trace("Read container node {}", identifier);
207                 return addDataContainerChildren(Builders.containerBuilder().withNodeIdentifier(identifier)).build();
208
209             case NodeTypes.LEAF_SET :
210                 LOG.trace("Read leaf set node {}", identifier);
211                 return addLeafSetChildren(identifier.getNodeType(),
212                         Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
213
214             case NodeTypes.ORDERED_LEAF_SET:
215                 LOG.trace("Read ordered leaf set node {}", identifier);
216                 ListNodeBuilder<Object, LeafSetEntryNode<Object>> orderedLeafSetBuilder =
217                         Builders.orderedLeafSetBuilder().withNodeIdentifier(identifier);
218                 orderedLeafSetBuilder = addLeafSetChildren(identifier.getNodeType(), orderedLeafSetBuilder);
219                 return orderedLeafSetBuilder.build();
220
221             default :
222                 return null;
223         }
224     }
225
226     private DOMSource readDOMSource() throws IOException {
227         String xml = readObject().toString();
228         try {
229             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
230             factory.setNamespaceAware(true);
231             Element node = factory.newDocumentBuilder().parse(
232                     new InputSource(new StringReader(xml))).getDocumentElement();
233             return new DOMSource(node);
234         } catch (SAXException | ParserConfigurationException e) {
235             throw new IOException("Error parsing XML: " + xml, e);
236         }
237     }
238
239     private QName readQName() throws IOException {
240         // Read in the same sequence of writing
241         String localName = readCodedString();
242         String namespace = readCodedString();
243         String revision = readCodedString();
244
245         String qname;
246         if (!Strings.isNullOrEmpty(revision)) {
247             qname = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG).append(revision)
248                     .append(')').append(localName).toString();
249         } else {
250             qname = reusableStringBuilder.append('(').append(namespace).append(')').append(localName).toString();
251         }
252
253         reusableStringBuilder.delete(0, reusableStringBuilder.length());
254         return QNameFactory.create(qname);
255     }
256
257
258     private String readCodedString() throws IOException {
259         byte valueType = input.readByte();
260         if (valueType == TokenTypes.IS_CODE_VALUE) {
261             return codedStringMap.get(input.readInt());
262         } else if (valueType == TokenTypes.IS_STRING_VALUE) {
263             String value = input.readUTF().intern();
264             codedStringMap.put(codedStringMap.size(), value);
265             return value;
266         }
267
268         return null;
269     }
270
271     private Set<QName> readQNameSet() throws IOException {
272         // Read the children count
273         int count = input.readInt();
274         Set<QName> children = new HashSet<>(count);
275         for (int i = 0; i < count; i++) {
276             children.add(readQName());
277         }
278         return children;
279     }
280
281     private Map<QName, Object> readKeyValueMap() throws IOException {
282         int count = input.readInt();
283         Map<QName, Object> keyValueMap = new HashMap<>(count);
284
285         for (int i = 0; i < count; i++) {
286             keyValueMap.put(readQName(), readObject());
287         }
288
289         return keyValueMap;
290     }
291
292     private Object readObject() throws IOException {
293         byte objectType = input.readByte();
294         switch (objectType) {
295             case ValueTypes.BITS_TYPE:
296                 return readObjSet();
297
298             case ValueTypes.BOOL_TYPE :
299                 return input.readBoolean();
300
301             case ValueTypes.BYTE_TYPE :
302                 return input.readByte();
303
304             case ValueTypes.INT_TYPE :
305                 return input.readInt();
306
307             case ValueTypes.LONG_TYPE :
308                 return input.readLong();
309
310             case ValueTypes.QNAME_TYPE :
311                 return readQName();
312
313             case ValueTypes.SHORT_TYPE :
314                 return input.readShort();
315
316             case ValueTypes.STRING_TYPE :
317                 return input.readUTF();
318
319             case ValueTypes.STRING_BYTES_TYPE:
320                 return readStringBytes();
321
322             case ValueTypes.BIG_DECIMAL_TYPE :
323                 return new BigDecimal(input.readUTF());
324
325             case ValueTypes.BIG_INTEGER_TYPE :
326                 return new BigInteger(input.readUTF());
327
328             case ValueTypes.BINARY_TYPE :
329                 byte[] bytes = new byte[input.readInt()];
330                 input.readFully(bytes);
331                 return bytes;
332
333             case ValueTypes.YANG_IDENTIFIER_TYPE :
334                 return readYangInstanceIdentifierInternal();
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         readSignatureMarkerAndVersionIfNeeded();
350
351         final boolean absolute = input.readBoolean();
352         final int size = input.readInt();
353         final Collection<QName> qnames = new ArrayList<>(size);
354         for (int i = 0; i < size; ++i) {
355             qnames.add(readQName());
356         }
357
358         return SchemaPath.create(qnames, absolute);
359     }
360
361     @Override
362     public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
363         readSignatureMarkerAndVersionIfNeeded();
364         return readYangInstanceIdentifierInternal();
365     }
366
367     private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
368         int size = input.readInt();
369
370         List<PathArgument> pathArguments = new ArrayList<>(size);
371
372         for (int i = 0; i < size; i++) {
373             pathArguments.add(readPathArgument());
374         }
375         return YangInstanceIdentifier.create(pathArguments);
376     }
377
378     private Set<String> readObjSet() throws IOException {
379         int count = input.readInt();
380         Set<String> children = new HashSet<>(count);
381         for (int i = 0; i < count; i++) {
382             children.add(readCodedString());
383         }
384         return children;
385     }
386
387     @Override
388     public PathArgument readPathArgument() throws IOException {
389         // read Type
390         int type = input.readByte();
391
392         switch (type) {
393
394             case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
395                 return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
396
397             case PathArgumentTypes.NODE_IDENTIFIER :
398                 return new NodeIdentifier(readQName());
399
400             case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES :
401                 return new NodeIdentifierWithPredicates(readQName(), readKeyValueMap());
402
403             case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
404                 return new NodeWithValue<>(readQName(), readObject());
405
406             default :
407                 return null;
408         }
409     }
410
411     @SuppressWarnings("unchecked")
412     private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(final QName nodeType,
413             final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
414
415         LOG.trace("Reading children of leaf set");
416
417         lastLeafSetQName = nodeType;
418
419         LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
420
421         while (child != null) {
422             builder.withChild(child);
423             child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
424         }
425         return builder;
426     }
427
428     @SuppressWarnings({ "unchecked", "rawtypes" })
429     private NormalizedNodeContainerBuilder addDataContainerChildren(
430             final NormalizedNodeContainerBuilder builder) throws IOException {
431         LOG.trace("Reading data container (leaf nodes) nodes");
432
433         NormalizedNode<?, ?> child = readNormalizedNodeInternal();
434
435         while (child != null) {
436             builder.addChild(child);
437             child = readNormalizedNodeInternal();
438         }
439         return builder;
440     }
441
442     @Override
443     public void readFully(final byte[] value) throws IOException {
444         readSignatureMarkerAndVersionIfNeeded();
445         input.readFully(value);
446     }
447
448     @Override
449     public void readFully(final byte[] str, final int off, final int len) throws IOException {
450         readSignatureMarkerAndVersionIfNeeded();
451         input.readFully(str, off, len);
452     }
453
454     @Override
455     public int skipBytes(final int num) throws IOException {
456         readSignatureMarkerAndVersionIfNeeded();
457         return input.skipBytes(num);
458     }
459
460     @Override
461     public boolean readBoolean() throws IOException {
462         readSignatureMarkerAndVersionIfNeeded();
463         return input.readBoolean();
464     }
465
466     @Override
467     public byte readByte() throws IOException {
468         readSignatureMarkerAndVersionIfNeeded();
469         return input.readByte();
470     }
471
472     @Override
473     public int readUnsignedByte() throws IOException {
474         readSignatureMarkerAndVersionIfNeeded();
475         return input.readUnsignedByte();
476     }
477
478     @Override
479     public short readShort() throws IOException {
480         readSignatureMarkerAndVersionIfNeeded();
481         return input.readShort();
482     }
483
484     @Override
485     public int readUnsignedShort() throws IOException {
486         readSignatureMarkerAndVersionIfNeeded();
487         return input.readUnsignedShort();
488     }
489
490     @Override
491     public char readChar() throws IOException {
492         readSignatureMarkerAndVersionIfNeeded();
493         return input.readChar();
494     }
495
496     @Override
497     public int readInt() throws IOException {
498         readSignatureMarkerAndVersionIfNeeded();
499         return input.readInt();
500     }
501
502     @Override
503     public long readLong() throws IOException {
504         readSignatureMarkerAndVersionIfNeeded();
505         return input.readLong();
506     }
507
508     @Override
509     public float readFloat() throws IOException {
510         readSignatureMarkerAndVersionIfNeeded();
511         return input.readFloat();
512     }
513
514     @Override
515     public double readDouble() throws IOException {
516         readSignatureMarkerAndVersionIfNeeded();
517         return input.readDouble();
518     }
519
520     @Override
521     public String readLine() throws IOException {
522         readSignatureMarkerAndVersionIfNeeded();
523         return input.readLine();
524     }
525
526     @Override
527     public String readUTF() throws IOException {
528         readSignatureMarkerAndVersionIfNeeded();
529         return input.readUTF();
530     }
531 }