2 * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.cluster.datastore.node.utils.stream;
11 import com.google.common.base.Preconditions;
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;
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.NodeIdentifier;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
37 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
40 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
41 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
42 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
43 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
44 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.w3c.dom.Element;
48 import org.xml.sax.InputSource;
49 import org.xml.sax.SAXException;
52 * NormalizedNodeInputStreamReader reads the byte stream and constructs the normalized node including its children
53 * nodes. This process goes in recursive manner, where each NodeTypes object signifies the start of the object, except
54 * END_NODE. If a node can have children, then that node's end is calculated based on appearance of END_NODE.
56 public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput {
58 private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeInputStreamReader.class);
60 private final DataInput input;
62 private final List<String> codedStringMap = new ArrayList<>();
64 private QName lastLeafSetQName;
66 private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
67 Object, LeafNode<Object>> leafBuilder;
69 @SuppressWarnings("rawtypes")
70 private NormalizedNodeAttrBuilder<NodeWithValue, Object, LeafSetEntryNode<Object>> leafSetEntryBuilder;
72 private boolean readSignatureMarker = true;
74 NormalizedNodeInputStreamReader(final DataInput input, final boolean versionChecked) {
75 this.input = Preconditions.checkNotNull(input);
76 readSignatureMarker = !versionChecked;
80 public NormalizedNode<?, ?> readNormalizedNode() throws IOException {
81 readSignatureMarkerAndVersionIfNeeded();
82 return readNormalizedNodeInternal();
85 private void readSignatureMarkerAndVersionIfNeeded() throws IOException {
86 if (readSignatureMarker) {
87 readSignatureMarker = false;
89 final byte marker = input.readByte();
90 if (marker != TokenTypes.SIGNATURE_MARKER) {
91 throw new InvalidNormalizedNodeStreamException(String.format(
92 "Invalid signature marker: %d", marker));
95 final short version = input.readShort();
96 if (version != TokenTypes.LITHIUM_VERSION) {
97 throw new InvalidNormalizedNodeStreamException(String.format("Unhandled stream version %s", version));
102 private NormalizedNode<?, ?> readNormalizedNodeInternal() throws IOException {
103 // each node should start with a byte
104 byte nodeType = input.readByte();
106 if (nodeType == NodeTypes.END_NODE) {
107 LOG.trace("End node reached. return");
108 lastLeafSetQName = null;
113 case NodeTypes.AUGMENTATION_NODE :
114 YangInstanceIdentifier.AugmentationIdentifier augIdentifier =
115 new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
117 LOG.trace("Reading augmentation node {} ", augIdentifier);
119 return addDataContainerChildren(Builders.augmentationBuilder()
120 .withNodeIdentifier(augIdentifier)).build();
122 case NodeTypes.LEAF_SET_ENTRY_NODE :
123 QName name = lastLeafSetQName;
128 Object value = readObject();
129 NodeWithValue<Object> leafIdentifier = new NodeWithValue<>(name, value);
131 LOG.trace("Reading leaf set entry node {}, value {}", leafIdentifier, value);
133 return leafSetEntryBuilder().withNodeIdentifier(leafIdentifier).withValue(value).build();
135 case NodeTypes.MAP_ENTRY_NODE :
136 NodeIdentifierWithPredicates entryIdentifier = readNormalizedNodeWithPredicates();
138 LOG.trace("Reading map entry node {} ", entryIdentifier);
140 return addDataContainerChildren(Builders.mapEntryBuilder()
141 .withNodeIdentifier(entryIdentifier)).build();
144 return readNodeIdentifierDependentNode(nodeType, new NodeIdentifier(readQName()));
148 private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
149 Object, LeafNode<Object>> leafBuilder() {
150 if (leafBuilder == null) {
151 leafBuilder = Builders.leafBuilder();
157 @SuppressWarnings("rawtypes")
158 private NormalizedNodeAttrBuilder<NodeWithValue, Object,
159 LeafSetEntryNode<Object>> leafSetEntryBuilder() {
160 if (leafSetEntryBuilder == null) {
161 leafSetEntryBuilder = Builders.leafSetEntryBuilder();
164 return leafSetEntryBuilder;
167 private NormalizedNode<?, ?> readNodeIdentifierDependentNode(final byte nodeType, final NodeIdentifier identifier)
171 case NodeTypes.LEAF_NODE :
172 LOG.trace("Read leaf node {}", identifier);
173 // Read the object value
174 return leafBuilder().withNodeIdentifier(identifier).withValue(readObject()).build();
176 case NodeTypes.ANY_XML_NODE :
177 LOG.trace("Read xml node");
178 return Builders.anyXmlBuilder().withNodeIdentifier(identifier).withValue(readDOMSource()).build();
180 case NodeTypes.MAP_NODE :
181 LOG.trace("Read map node {}", identifier);
182 return addDataContainerChildren(Builders.mapBuilder().withNodeIdentifier(identifier)).build();
184 case NodeTypes.CHOICE_NODE:
185 LOG.trace("Read choice node {}", identifier);
186 return addDataContainerChildren(Builders.choiceBuilder().withNodeIdentifier(identifier)).build();
188 case NodeTypes.ORDERED_MAP_NODE:
189 LOG.trace("Reading ordered map node {}", identifier);
190 return addDataContainerChildren(Builders.orderedMapBuilder().withNodeIdentifier(identifier)).build();
192 case NodeTypes.UNKEYED_LIST:
193 LOG.trace("Read unkeyed list node {}", identifier);
194 return addDataContainerChildren(Builders.unkeyedListBuilder().withNodeIdentifier(identifier)).build();
196 case NodeTypes.UNKEYED_LIST_ITEM:
197 LOG.trace("Read unkeyed list item node {}", identifier);
198 return addDataContainerChildren(Builders.unkeyedListEntryBuilder()
199 .withNodeIdentifier(identifier)).build();
201 case NodeTypes.CONTAINER_NODE:
202 LOG.trace("Read container node {}", identifier);
203 return addDataContainerChildren(Builders.containerBuilder().withNodeIdentifier(identifier)).build();
205 case NodeTypes.LEAF_SET :
206 LOG.trace("Read leaf set node {}", identifier);
207 return addLeafSetChildren(identifier.getNodeType(),
208 Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
210 case NodeTypes.ORDERED_LEAF_SET:
211 LOG.trace("Read ordered leaf set node {}", identifier);
212 return addLeafSetChildren(identifier.getNodeType(),
213 Builders.orderedLeafSetBuilder().withNodeIdentifier(identifier)).build();
220 private DOMSource readDOMSource() throws IOException {
221 String xml = readObject().toString();
223 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
224 factory.setNamespaceAware(true);
225 Element node = factory.newDocumentBuilder().parse(
226 new InputSource(new StringReader(xml))).getDocumentElement();
227 return new DOMSource(node);
228 } catch (SAXException | ParserConfigurationException e) {
229 throw new IOException("Error parsing XML: " + xml, e);
233 private QName readQName() throws IOException {
234 // Read in the same sequence of writing
235 String localName = readCodedString();
236 String namespace = readCodedString();
237 String revision = Strings.emptyToNull(readCodedString());
239 return QNameFactory.create(new QNameFactory.Key(localName, namespace, revision));
243 private String readCodedString() throws IOException {
244 final byte valueType = input.readByte();
246 case TokenTypes.IS_NULL_VALUE:
248 case TokenTypes.IS_CODE_VALUE:
249 final int code = input.readInt();
251 return codedStringMap.get(code);
252 } catch (IndexOutOfBoundsException e) {
253 throw new IOException("String code " + code + " was not found", e);
255 case TokenTypes.IS_STRING_VALUE:
256 final String value = input.readUTF().intern();
257 codedStringMap.add(value);
260 throw new IOException("Unhandled string value type " + valueType);
264 private Set<QName> readQNameSet() throws IOException {
265 // Read the children count
266 int count = input.readInt();
267 Set<QName> children = new HashSet<>(count);
268 for (int i = 0; i < count; i++) {
269 children.add(readQName());
274 private NodeIdentifierWithPredicates readNormalizedNodeWithPredicates() throws IOException {
275 final QName qname = readQName();
276 final int count = input.readInt();
279 return new NodeIdentifierWithPredicates(qname);
281 return new NodeIdentifierWithPredicates(qname, readQName(), readObject());
283 // ImmutableList is used by ImmutableOffsetMapTemplate for lookups, hence we use that.
284 final Builder<QName> keys = ImmutableList.builderWithExpectedSize(count);
285 final Object[] values = new Object[count];
286 for (int i = 0; i < count; i++) {
287 keys.add(readQName());
288 values[i] = readObject();
291 return new NodeIdentifierWithPredicates(qname, ImmutableOffsetMapTemplate.ordered(keys.build())
292 .instantiateWithValues(values));
296 private Object readObject() throws IOException {
297 byte objectType = input.readByte();
298 switch (objectType) {
299 case ValueTypes.BITS_TYPE:
302 case ValueTypes.BOOL_TYPE :
303 return input.readBoolean();
305 case ValueTypes.BYTE_TYPE :
306 return input.readByte();
308 case ValueTypes.INT_TYPE :
309 return input.readInt();
311 case ValueTypes.LONG_TYPE :
312 return input.readLong();
314 case ValueTypes.QNAME_TYPE :
317 case ValueTypes.SHORT_TYPE :
318 return input.readShort();
320 case ValueTypes.STRING_TYPE :
321 return input.readUTF();
323 case ValueTypes.STRING_BYTES_TYPE:
324 return readStringBytes();
326 case ValueTypes.BIG_DECIMAL_TYPE :
327 return new BigDecimal(input.readUTF());
329 case ValueTypes.BIG_INTEGER_TYPE :
330 return new BigInteger(input.readUTF());
332 case ValueTypes.BINARY_TYPE :
333 byte[] bytes = new byte[input.readInt()];
334 input.readFully(bytes);
337 case ValueTypes.YANG_IDENTIFIER_TYPE :
338 return readYangInstanceIdentifierInternal();
340 case ValueTypes.EMPTY_TYPE:
341 // Leaf nodes no longer allow null values and thus we no longer emit null values. Previously, the "empty"
342 // yang type was represented as null so we translate an incoming null value to Empty. It was possible for
343 // a BI user to set a string leaf to null and we're rolling the dice here but the chances for that are
344 // very low. We'd have to know the yang type but, even if we did, we can't let a null value pass upstream
345 // so we'd have to drop the leaf which might cause other issues.
346 case ValueTypes.NULL_TYPE:
347 return Empty.getInstance();
354 private String readStringBytes() throws IOException {
355 byte[] bytes = new byte[input.readInt()];
356 input.readFully(bytes);
357 return new String(bytes, StandardCharsets.UTF_8);
361 public SchemaPath readSchemaPath() throws IOException {
362 readSignatureMarkerAndVersionIfNeeded();
364 final boolean absolute = input.readBoolean();
365 final int size = input.readInt();
367 final Builder<QName> qnames = ImmutableList.builderWithExpectedSize(size);
368 for (int i = 0; i < size; ++i) {
369 qnames.add(readQName());
371 return SchemaPath.create(qnames.build(), absolute);
375 public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
376 readSignatureMarkerAndVersionIfNeeded();
377 return readYangInstanceIdentifierInternal();
380 private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
381 int size = input.readInt();
382 final Builder<PathArgument> pathArguments = ImmutableList.builderWithExpectedSize(size);
383 for (int i = 0; i < size; i++) {
384 pathArguments.add(readPathArgument());
386 return YangInstanceIdentifier.create(pathArguments.build());
389 private Set<String> readObjSet() throws IOException {
390 int count = input.readInt();
391 Set<String> children = new HashSet<>(count);
392 for (int i = 0; i < count; i++) {
393 children.add(readCodedString());
399 public PathArgument readPathArgument() throws IOException {
401 int type = input.readByte();
405 case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
406 return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
408 case PathArgumentTypes.NODE_IDENTIFIER :
409 return new NodeIdentifier(readQName());
411 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES :
412 return readNormalizedNodeWithPredicates();
414 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
415 return new NodeWithValue<>(readQName(), readObject());
422 @SuppressWarnings("unchecked")
423 private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(final QName nodeType,
424 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
426 LOG.trace("Reading children of leaf set");
428 lastLeafSetQName = nodeType;
430 LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
432 while (child != null) {
433 builder.withChild(child);
434 child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
439 @SuppressWarnings({ "unchecked", "rawtypes" })
440 private NormalizedNodeContainerBuilder addDataContainerChildren(
441 final NormalizedNodeContainerBuilder builder) throws IOException {
442 LOG.trace("Reading data container (leaf nodes) nodes");
444 NormalizedNode<?, ?> child = readNormalizedNodeInternal();
446 while (child != null) {
447 builder.addChild(child);
448 child = readNormalizedNodeInternal();
454 public void readFully(final byte[] value) throws IOException {
455 readSignatureMarkerAndVersionIfNeeded();
456 input.readFully(value);
460 public void readFully(final byte[] str, final int off, final int len) throws IOException {
461 readSignatureMarkerAndVersionIfNeeded();
462 input.readFully(str, off, len);
466 public int skipBytes(final int num) throws IOException {
467 readSignatureMarkerAndVersionIfNeeded();
468 return input.skipBytes(num);
472 public boolean readBoolean() throws IOException {
473 readSignatureMarkerAndVersionIfNeeded();
474 return input.readBoolean();
478 public byte readByte() throws IOException {
479 readSignatureMarkerAndVersionIfNeeded();
480 return input.readByte();
484 public int readUnsignedByte() throws IOException {
485 readSignatureMarkerAndVersionIfNeeded();
486 return input.readUnsignedByte();
490 public short readShort() throws IOException {
491 readSignatureMarkerAndVersionIfNeeded();
492 return input.readShort();
496 public int readUnsignedShort() throws IOException {
497 readSignatureMarkerAndVersionIfNeeded();
498 return input.readUnsignedShort();
502 public char readChar() throws IOException {
503 readSignatureMarkerAndVersionIfNeeded();
504 return input.readChar();
508 public int readInt() throws IOException {
509 readSignatureMarkerAndVersionIfNeeded();
510 return input.readInt();
514 public long readLong() throws IOException {
515 readSignatureMarkerAndVersionIfNeeded();
516 return input.readLong();
520 public float readFloat() throws IOException {
521 readSignatureMarkerAndVersionIfNeeded();
522 return input.readFloat();
526 public double readDouble() throws IOException {
527 readSignatureMarkerAndVersionIfNeeded();
528 return input.readDouble();
532 public String readLine() throws IOException {
533 readSignatureMarkerAndVersionIfNeeded();
534 return input.readLine();
538 public String readUTF() throws IOException {
539 readSignatureMarkerAndVersionIfNeeded();
540 return input.readUTF();