989884cebdfa3d75d159686b92ba1a3cc5927e35
[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             return null;
112         }
113
114         switch (nodeType) {
115             case NodeTypes.AUGMENTATION_NODE :
116                 YangInstanceIdentifier.AugmentationIdentifier augIdentifier =
117                     new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
118
119                 LOG.trace("Reading augmentation node {} ", augIdentifier);
120
121                 return addDataContainerChildren(Builders.augmentationBuilder()
122                         .withNodeIdentifier(augIdentifier)).build();
123
124             case NodeTypes.LEAF_SET_ENTRY_NODE :
125                 QName name = lastLeafSetQName;
126                 if (name == null) {
127                     name = readQName();
128                 }
129
130                 Object value = readObject();
131                 NodeWithValue<Object> leafIdentifier = new NodeWithValue<>(name, value);
132
133                 LOG.trace("Reading leaf set entry node {}, value {}", leafIdentifier, value);
134
135                 return leafSetEntryBuilder().withNodeIdentifier(leafIdentifier).withValue(value).build();
136
137             case NodeTypes.MAP_ENTRY_NODE :
138                 NodeIdentifierWithPredicates entryIdentifier = new NodeIdentifierWithPredicates(
139                         readQName(), readKeyValueMap());
140
141                 LOG.trace("Reading map entry node {} ", entryIdentifier);
142
143                 return addDataContainerChildren(Builders.mapEntryBuilder()
144                         .withNodeIdentifier(entryIdentifier)).build();
145
146             default :
147                 return readNodeIdentifierDependentNode(nodeType, new NodeIdentifier(readQName()));
148         }
149     }
150
151     private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
152                                       Object, LeafNode<Object>> leafBuilder() {
153         if (leafBuilder == null) {
154             leafBuilder = Builders.leafBuilder();
155         }
156
157         return leafBuilder;
158     }
159
160     @SuppressWarnings("rawtypes")
161     private NormalizedNodeAttrBuilder<NodeWithValue, Object,
162                                       LeafSetEntryNode<Object>> leafSetEntryBuilder() {
163         if (leafSetEntryBuilder == null) {
164             leafSetEntryBuilder = Builders.leafSetEntryBuilder();
165         }
166
167         return leafSetEntryBuilder;
168     }
169
170     private NormalizedNode<?, ?> readNodeIdentifierDependentNode(final byte nodeType, final NodeIdentifier identifier)
171         throws IOException {
172
173         switch (nodeType) {
174             case NodeTypes.LEAF_NODE :
175                 LOG.trace("Read leaf node {}", identifier);
176                 // Read the object value
177                 return leafBuilder().withNodeIdentifier(identifier).withValue(readObject()).build();
178
179             case NodeTypes.ANY_XML_NODE :
180                 LOG.trace("Read xml node");
181                 return Builders.anyXmlBuilder().withNodeIdentifier(identifier).withValue(readDOMSource()).build();
182
183             case NodeTypes.MAP_NODE :
184                 LOG.trace("Read map node {}", identifier);
185                 return addDataContainerChildren(Builders.mapBuilder().withNodeIdentifier(identifier)).build();
186
187             case NodeTypes.CHOICE_NODE:
188                 LOG.trace("Read choice node {}", identifier);
189                 return addDataContainerChildren(Builders.choiceBuilder().withNodeIdentifier(identifier)).build();
190
191             case NodeTypes.ORDERED_MAP_NODE:
192                 LOG.trace("Reading ordered map node {}", identifier);
193                 return addDataContainerChildren(Builders.orderedMapBuilder().withNodeIdentifier(identifier)).build();
194
195             case NodeTypes.UNKEYED_LIST:
196                 LOG.trace("Read unkeyed list node {}", identifier);
197                 return addDataContainerChildren(Builders.unkeyedListBuilder().withNodeIdentifier(identifier)).build();
198
199             case NodeTypes.UNKEYED_LIST_ITEM:
200                 LOG.trace("Read unkeyed list item node {}", identifier);
201                 return addDataContainerChildren(Builders.unkeyedListEntryBuilder()
202                         .withNodeIdentifier(identifier)).build();
203
204             case NodeTypes.CONTAINER_NODE:
205                 LOG.trace("Read container node {}", identifier);
206                 return addDataContainerChildren(Builders.containerBuilder().withNodeIdentifier(identifier)).build();
207
208             case NodeTypes.LEAF_SET :
209                 LOG.trace("Read leaf set node {}", identifier);
210                 return addLeafSetChildren(identifier.getNodeType(),
211                         Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
212
213             case NodeTypes.ORDERED_LEAF_SET:
214                 LOG.trace("Read ordered leaf set node {}", identifier);
215                 ListNodeBuilder<Object, LeafSetEntryNode<Object>> orderedLeafSetBuilder =
216                         Builders.orderedLeafSetBuilder().withNodeIdentifier(identifier);
217                 orderedLeafSetBuilder = addLeafSetChildren(identifier.getNodeType(), orderedLeafSetBuilder);
218                 return orderedLeafSetBuilder.build();
219
220             default :
221                 return null;
222         }
223     }
224
225     private DOMSource readDOMSource() throws IOException {
226         String xml = readObject().toString();
227         try {
228             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
229             factory.setNamespaceAware(true);
230             Element node = factory.newDocumentBuilder().parse(
231                     new InputSource(new StringReader(xml))).getDocumentElement();
232             return new DOMSource(node);
233         } catch (SAXException | ParserConfigurationException e) {
234             throw new IOException("Error parsing XML: " + xml, e);
235         }
236     }
237
238     private QName readQName() throws IOException {
239         // Read in the same sequence of writing
240         String localName = readCodedString();
241         String namespace = readCodedString();
242         String revision = readCodedString();
243
244         String qname;
245         if (!Strings.isNullOrEmpty(revision)) {
246             qname = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG).append(revision)
247                     .append(')').append(localName).toString();
248         } else {
249             qname = reusableStringBuilder.append('(').append(namespace).append(')').append(localName).toString();
250         }
251
252         reusableStringBuilder.delete(0, reusableStringBuilder.length());
253         return QNameFactory.create(qname);
254     }
255
256
257     private String readCodedString() throws IOException {
258         byte valueType = input.readByte();
259         if (valueType == TokenTypes.IS_CODE_VALUE) {
260             return codedStringMap.get(input.readInt());
261         } else if (valueType == TokenTypes.IS_STRING_VALUE) {
262             String value = input.readUTF().intern();
263             codedStringMap.put(Integer.valueOf(codedStringMap.size()), value);
264             return value;
265         }
266
267         return null;
268     }
269
270     private Set<QName> readQNameSet() throws IOException {
271         // Read the children count
272         int count = input.readInt();
273         Set<QName> children = new HashSet<>(count);
274         for (int i = 0; i < count; i++) {
275             children.add(readQName());
276         }
277         return children;
278     }
279
280     private Map<QName, Object> readKeyValueMap() throws IOException {
281         int count = input.readInt();
282         Map<QName, Object> keyValueMap = new HashMap<>(count);
283
284         for (int i = 0; i < count; i++) {
285             keyValueMap.put(readQName(), readObject());
286         }
287
288         return keyValueMap;
289     }
290
291     private Object readObject() throws IOException {
292         byte objectType = input.readByte();
293         switch (objectType) {
294             case ValueTypes.BITS_TYPE:
295                 return readObjSet();
296
297             case ValueTypes.BOOL_TYPE :
298                 return Boolean.valueOf(input.readBoolean());
299
300             case ValueTypes.BYTE_TYPE :
301                 return Byte.valueOf(input.readByte());
302
303             case ValueTypes.INT_TYPE :
304                 return Integer.valueOf(input.readInt());
305
306             case ValueTypes.LONG_TYPE :
307                 return Long.valueOf(input.readLong());
308
309             case ValueTypes.QNAME_TYPE :
310                 return readQName();
311
312             case ValueTypes.SHORT_TYPE :
313                 return Short.valueOf(input.readShort());
314
315             case ValueTypes.STRING_TYPE :
316                 return input.readUTF();
317
318             case ValueTypes.STRING_BYTES_TYPE:
319                 return readStringBytes();
320
321             case ValueTypes.BIG_DECIMAL_TYPE :
322                 return new BigDecimal(input.readUTF());
323
324             case ValueTypes.BIG_INTEGER_TYPE :
325                 return new BigInteger(input.readUTF());
326
327             case ValueTypes.BINARY_TYPE :
328                 byte[] bytes = new byte[input.readInt()];
329                 input.readFully(bytes);
330                 return bytes;
331
332             case ValueTypes.YANG_IDENTIFIER_TYPE :
333                 return readYangInstanceIdentifierInternal();
334
335             default :
336                 return null;
337         }
338     }
339
340     private String readStringBytes() throws IOException {
341         byte[] bytes = new byte[input.readInt()];
342         input.readFully(bytes);
343         return new String(bytes, StandardCharsets.UTF_8);
344     }
345
346     @Override
347     public SchemaPath readSchemaPath() throws IOException {
348         readSignatureMarkerAndVersionIfNeeded();
349
350         final boolean absolute = input.readBoolean();
351         final int size = input.readInt();
352         final Collection<QName> qnames = new ArrayList<>(size);
353         for (int i = 0; i < size; ++i) {
354             qnames.add(readQName());
355         }
356
357         return SchemaPath.create(qnames, absolute);
358     }
359
360     @Override
361     public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
362         readSignatureMarkerAndVersionIfNeeded();
363         return readYangInstanceIdentifierInternal();
364     }
365
366     private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
367         int size = input.readInt();
368
369         List<PathArgument> pathArguments = new ArrayList<>(size);
370
371         for (int i = 0; i < size; i++) {
372             pathArguments.add(readPathArgument());
373         }
374         return YangInstanceIdentifier.create(pathArguments);
375     }
376
377     private Set<String> readObjSet() throws IOException {
378         int count = input.readInt();
379         Set<String> children = new HashSet<>(count);
380         for (int i = 0; i < count; i++) {
381             children.add(readCodedString());
382         }
383         return children;
384     }
385
386     @Override
387     public PathArgument readPathArgument() throws IOException {
388         // read Type
389         int type = input.readByte();
390
391         switch (type) {
392
393             case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
394                 return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
395
396             case PathArgumentTypes.NODE_IDENTIFIER :
397                 return new NodeIdentifier(readQName());
398
399             case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES :
400                 return new NodeIdentifierWithPredicates(readQName(), readKeyValueMap());
401
402             case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
403                 return new NodeWithValue<>(readQName(), readObject());
404
405             default :
406                 return null;
407         }
408     }
409
410     @SuppressWarnings("unchecked")
411     private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(final QName nodeType,
412             final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
413
414         LOG.trace("Reading children of leaf set");
415
416         lastLeafSetQName = nodeType;
417
418         LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
419
420         while (child != null) {
421             builder.withChild(child);
422             child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
423         }
424         return builder;
425     }
426
427     @SuppressWarnings({ "unchecked", "rawtypes" })
428     private NormalizedNodeContainerBuilder addDataContainerChildren(
429             final NormalizedNodeContainerBuilder builder) throws IOException {
430         LOG.trace("Reading data container (leaf nodes) nodes");
431
432         NormalizedNode<?, ?> child = readNormalizedNodeInternal();
433
434         while (child != null) {
435             builder.addChild(child);
436             child = readNormalizedNodeInternal();
437         }
438         return builder;
439     }
440
441     @Override
442     public void readFully(final byte[] value) throws IOException {
443         readSignatureMarkerAndVersionIfNeeded();
444         input.readFully(value);
445     }
446
447     @Override
448     public void readFully(final byte[] str, final int off, final int len) throws IOException {
449         readSignatureMarkerAndVersionIfNeeded();
450         input.readFully(str, off, len);
451     }
452
453     @Override
454     public int skipBytes(final int num) throws IOException {
455         readSignatureMarkerAndVersionIfNeeded();
456         return input.skipBytes(num);
457     }
458
459     @Override
460     public boolean readBoolean() throws IOException {
461         readSignatureMarkerAndVersionIfNeeded();
462         return input.readBoolean();
463     }
464
465     @Override
466     public byte readByte() throws IOException {
467         readSignatureMarkerAndVersionIfNeeded();
468         return input.readByte();
469     }
470
471     @Override
472     public int readUnsignedByte() throws IOException {
473         readSignatureMarkerAndVersionIfNeeded();
474         return input.readUnsignedByte();
475     }
476
477     @Override
478     public short readShort() throws IOException {
479         readSignatureMarkerAndVersionIfNeeded();
480         return input.readShort();
481     }
482
483     @Override
484     public int readUnsignedShort() throws IOException {
485         readSignatureMarkerAndVersionIfNeeded();
486         return input.readUnsignedShort();
487     }
488
489     @Override
490     public char readChar() throws IOException {
491         readSignatureMarkerAndVersionIfNeeded();
492         return input.readChar();
493     }
494
495     @Override
496     public int readInt() throws IOException {
497         readSignatureMarkerAndVersionIfNeeded();
498         return input.readInt();
499     }
500
501     @Override
502     public long readLong() throws IOException {
503         readSignatureMarkerAndVersionIfNeeded();
504         return input.readLong();
505     }
506
507     @Override
508     public float readFloat() throws IOException {
509         readSignatureMarkerAndVersionIfNeeded();
510         return input.readFloat();
511     }
512
513     @Override
514     public double readDouble() throws IOException {
515         readSignatureMarkerAndVersionIfNeeded();
516         return input.readDouble();
517     }
518
519     @Override
520     public String readLine() throws IOException {
521         readSignatureMarkerAndVersionIfNeeded();
522         return input.readLine();
523     }
524
525     @Override
526     public String readUTF() throws IOException {
527         readSignatureMarkerAndVersionIfNeeded();
528         return input.readUTF();
529     }
530 }