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.HashMap;
22 import java.util.HashSet;
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 static final String REVISION_ARG = "?revision=";
62 private final DataInput input;
64 private final Map<Integer, String> codedStringMap = new HashMap<>();
66 private QName lastLeafSetQName;
68 private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
69 Object, LeafNode<Object>> leafBuilder;
71 @SuppressWarnings("rawtypes")
72 private NormalizedNodeAttrBuilder<NodeWithValue, Object, LeafSetEntryNode<Object>> leafSetEntryBuilder;
74 private final StringBuilder reusableStringBuilder = new StringBuilder(50);
76 private boolean readSignatureMarker = true;
78 NormalizedNodeInputStreamReader(final DataInput input, final boolean versionChecked) {
79 this.input = Preconditions.checkNotNull(input);
80 readSignatureMarker = !versionChecked;
84 public NormalizedNode<?, ?> readNormalizedNode() throws IOException {
85 readSignatureMarkerAndVersionIfNeeded();
86 return readNormalizedNodeInternal();
89 private void readSignatureMarkerAndVersionIfNeeded() throws IOException {
90 if (readSignatureMarker) {
91 readSignatureMarker = false;
93 final byte marker = input.readByte();
94 if (marker != TokenTypes.SIGNATURE_MARKER) {
95 throw new InvalidNormalizedNodeStreamException(String.format(
96 "Invalid signature marker: %d", marker));
99 final short version = input.readShort();
100 if (version != TokenTypes.LITHIUM_VERSION) {
101 throw new InvalidNormalizedNodeStreamException(String.format("Unhandled stream version %s", version));
106 private NormalizedNode<?, ?> readNormalizedNodeInternal() throws IOException {
107 // each node should start with a byte
108 byte nodeType = input.readByte();
110 if (nodeType == NodeTypes.END_NODE) {
111 LOG.trace("End node reached. return");
112 lastLeafSetQName = null;
117 case NodeTypes.AUGMENTATION_NODE :
118 YangInstanceIdentifier.AugmentationIdentifier augIdentifier =
119 new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
121 LOG.trace("Reading augmentation node {} ", augIdentifier);
123 return addDataContainerChildren(Builders.augmentationBuilder()
124 .withNodeIdentifier(augIdentifier)).build();
126 case NodeTypes.LEAF_SET_ENTRY_NODE :
127 QName name = lastLeafSetQName;
132 Object value = readObject();
133 NodeWithValue<Object> leafIdentifier = new NodeWithValue<>(name, value);
135 LOG.trace("Reading leaf set entry node {}, value {}", leafIdentifier, value);
137 return leafSetEntryBuilder().withNodeIdentifier(leafIdentifier).withValue(value).build();
139 case NodeTypes.MAP_ENTRY_NODE :
140 NodeIdentifierWithPredicates entryIdentifier = readNormalizedNodeWithPredicates();
142 LOG.trace("Reading map entry node {} ", entryIdentifier);
144 return addDataContainerChildren(Builders.mapEntryBuilder()
145 .withNodeIdentifier(entryIdentifier)).build();
148 return readNodeIdentifierDependentNode(nodeType, new NodeIdentifier(readQName()));
152 private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
153 Object, LeafNode<Object>> leafBuilder() {
154 if (leafBuilder == null) {
155 leafBuilder = Builders.leafBuilder();
161 @SuppressWarnings("rawtypes")
162 private NormalizedNodeAttrBuilder<NodeWithValue, Object,
163 LeafSetEntryNode<Object>> leafSetEntryBuilder() {
164 if (leafSetEntryBuilder == null) {
165 leafSetEntryBuilder = Builders.leafSetEntryBuilder();
168 return leafSetEntryBuilder;
171 private NormalizedNode<?, ?> readNodeIdentifierDependentNode(final byte nodeType, final NodeIdentifier identifier)
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();
180 case NodeTypes.ANY_XML_NODE :
181 LOG.trace("Read xml node");
182 return Builders.anyXmlBuilder().withNodeIdentifier(identifier).withValue(readDOMSource()).build();
184 case NodeTypes.MAP_NODE :
185 LOG.trace("Read map node {}", identifier);
186 return addDataContainerChildren(Builders.mapBuilder().withNodeIdentifier(identifier)).build();
188 case NodeTypes.CHOICE_NODE:
189 LOG.trace("Read choice node {}", identifier);
190 return addDataContainerChildren(Builders.choiceBuilder().withNodeIdentifier(identifier)).build();
192 case NodeTypes.ORDERED_MAP_NODE:
193 LOG.trace("Reading ordered map node {}", identifier);
194 return addDataContainerChildren(Builders.orderedMapBuilder().withNodeIdentifier(identifier)).build();
196 case NodeTypes.UNKEYED_LIST:
197 LOG.trace("Read unkeyed list node {}", identifier);
198 return addDataContainerChildren(Builders.unkeyedListBuilder().withNodeIdentifier(identifier)).build();
200 case NodeTypes.UNKEYED_LIST_ITEM:
201 LOG.trace("Read unkeyed list item node {}", identifier);
202 return addDataContainerChildren(Builders.unkeyedListEntryBuilder()
203 .withNodeIdentifier(identifier)).build();
205 case NodeTypes.CONTAINER_NODE:
206 LOG.trace("Read container node {}", identifier);
207 return addDataContainerChildren(Builders.containerBuilder().withNodeIdentifier(identifier)).build();
209 case NodeTypes.LEAF_SET :
210 LOG.trace("Read leaf set node {}", identifier);
211 return addLeafSetChildren(identifier.getNodeType(),
212 Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
214 case NodeTypes.ORDERED_LEAF_SET:
215 LOG.trace("Read ordered leaf set node {}", identifier);
216 return addLeafSetChildren(identifier.getNodeType(),
217 Builders.orderedLeafSetBuilder().withNodeIdentifier(identifier)).build();
224 private DOMSource readDOMSource() throws IOException {
225 String xml = readObject().toString();
227 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
228 factory.setNamespaceAware(true);
229 Element node = factory.newDocumentBuilder().parse(
230 new InputSource(new StringReader(xml))).getDocumentElement();
231 return new DOMSource(node);
232 } catch (SAXException | ParserConfigurationException e) {
233 throw new IOException("Error parsing XML: " + xml, e);
237 private QName readQName() throws IOException {
238 // Read in the same sequence of writing
239 String localName = readCodedString();
240 String namespace = readCodedString();
241 String revision = readCodedString();
244 if (!Strings.isNullOrEmpty(revision)) {
245 qname = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG).append(revision)
246 .append(')').append(localName).toString();
248 qname = reusableStringBuilder.append('(').append(namespace).append(')').append(localName).toString();
251 reusableStringBuilder.delete(0, reusableStringBuilder.length());
252 return QNameFactory.create(qname);
256 private String readCodedString() throws IOException {
257 byte valueType = input.readByte();
258 if (valueType == TokenTypes.IS_CODE_VALUE) {
259 return codedStringMap.get(input.readInt());
260 } else if (valueType == TokenTypes.IS_STRING_VALUE) {
261 String value = input.readUTF().intern();
262 codedStringMap.put(codedStringMap.size(), value);
269 private Set<QName> readQNameSet() throws IOException {
270 // Read the children count
271 int count = input.readInt();
272 Set<QName> children = new HashSet<>(count);
273 for (int i = 0; i < count; i++) {
274 children.add(readQName());
279 private NodeIdentifierWithPredicates readNormalizedNodeWithPredicates() throws IOException {
280 final QName qname = readQName();
281 final int count = input.readInt();
284 return new NodeIdentifierWithPredicates(qname);
286 return new NodeIdentifierWithPredicates(qname, readQName(), readObject());
288 // ImmutableList is used by ImmutableOffsetMapTemplate for lookups, hence we use that.
289 final Builder<QName> keys = ImmutableList.builderWithExpectedSize(count);
290 final Object[] values = new Object[count];
291 for (int i = 0; i < count; i++) {
292 keys.add(readQName());
293 values[i] = readObject();
296 return new NodeIdentifierWithPredicates(qname, ImmutableOffsetMapTemplate.ordered(keys.build())
297 .instantiateWithValues(values));
301 private Object readObject() throws IOException {
302 byte objectType = input.readByte();
303 switch (objectType) {
304 case ValueTypes.BITS_TYPE:
307 case ValueTypes.BOOL_TYPE :
308 return input.readBoolean();
310 case ValueTypes.BYTE_TYPE :
311 return input.readByte();
313 case ValueTypes.INT_TYPE :
314 return input.readInt();
316 case ValueTypes.LONG_TYPE :
317 return input.readLong();
319 case ValueTypes.QNAME_TYPE :
322 case ValueTypes.SHORT_TYPE :
323 return input.readShort();
325 case ValueTypes.STRING_TYPE :
326 return input.readUTF();
328 case ValueTypes.STRING_BYTES_TYPE:
329 return readStringBytes();
331 case ValueTypes.BIG_DECIMAL_TYPE :
332 return new BigDecimal(input.readUTF());
334 case ValueTypes.BIG_INTEGER_TYPE :
335 return new BigInteger(input.readUTF());
337 case ValueTypes.BINARY_TYPE :
338 byte[] bytes = new byte[input.readInt()];
339 input.readFully(bytes);
342 case ValueTypes.YANG_IDENTIFIER_TYPE :
343 return readYangInstanceIdentifierInternal();
345 case ValueTypes.EMPTY_TYPE:
346 // Leaf nodes no longer allow null values and thus we no longer emit null values. Previously, the "empty"
347 // yang type was represented as null so we translate an incoming null value to Empty. It was possible for
348 // a BI user to set a string leaf to null and we're rolling the dice here but the chances for that are
349 // very low. We'd have to know the yang type but, even if we did, we can't let a null value pass upstream
350 // so we'd have to drop the leaf which might cause other issues.
351 case ValueTypes.NULL_TYPE:
352 return Empty.getInstance();
359 private String readStringBytes() throws IOException {
360 byte[] bytes = new byte[input.readInt()];
361 input.readFully(bytes);
362 return new String(bytes, StandardCharsets.UTF_8);
366 public SchemaPath readSchemaPath() throws IOException {
367 readSignatureMarkerAndVersionIfNeeded();
369 final boolean absolute = input.readBoolean();
370 final int size = input.readInt();
372 final Builder<QName> qnames = ImmutableList.builderWithExpectedSize(size);
373 for (int i = 0; i < size; ++i) {
374 qnames.add(readQName());
376 return SchemaPath.create(qnames.build(), absolute);
380 public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
381 readSignatureMarkerAndVersionIfNeeded();
382 return readYangInstanceIdentifierInternal();
385 private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
386 int size = input.readInt();
387 final Builder<PathArgument> pathArguments = ImmutableList.builderWithExpectedSize(size);
388 for (int i = 0; i < size; i++) {
389 pathArguments.add(readPathArgument());
391 return YangInstanceIdentifier.create(pathArguments.build());
394 private Set<String> readObjSet() throws IOException {
395 int count = input.readInt();
396 Set<String> children = new HashSet<>(count);
397 for (int i = 0; i < count; i++) {
398 children.add(readCodedString());
404 public PathArgument readPathArgument() throws IOException {
406 int type = input.readByte();
410 case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
411 return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
413 case PathArgumentTypes.NODE_IDENTIFIER :
414 return new NodeIdentifier(readQName());
416 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES :
417 return readNormalizedNodeWithPredicates();
419 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
420 return new NodeWithValue<>(readQName(), readObject());
427 @SuppressWarnings("unchecked")
428 private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(final QName nodeType,
429 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
431 LOG.trace("Reading children of leaf set");
433 lastLeafSetQName = nodeType;
435 LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
437 while (child != null) {
438 builder.withChild(child);
439 child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
444 @SuppressWarnings({ "unchecked", "rawtypes" })
445 private NormalizedNodeContainerBuilder addDataContainerChildren(
446 final NormalizedNodeContainerBuilder builder) throws IOException {
447 LOG.trace("Reading data container (leaf nodes) nodes");
449 NormalizedNode<?, ?> child = readNormalizedNodeInternal();
451 while (child != null) {
452 builder.addChild(child);
453 child = readNormalizedNodeInternal();
459 public void readFully(final byte[] value) throws IOException {
460 readSignatureMarkerAndVersionIfNeeded();
461 input.readFully(value);
465 public void readFully(final byte[] str, final int off, final int len) throws IOException {
466 readSignatureMarkerAndVersionIfNeeded();
467 input.readFully(str, off, len);
471 public int skipBytes(final int num) throws IOException {
472 readSignatureMarkerAndVersionIfNeeded();
473 return input.skipBytes(num);
477 public boolean readBoolean() throws IOException {
478 readSignatureMarkerAndVersionIfNeeded();
479 return input.readBoolean();
483 public byte readByte() throws IOException {
484 readSignatureMarkerAndVersionIfNeeded();
485 return input.readByte();
489 public int readUnsignedByte() throws IOException {
490 readSignatureMarkerAndVersionIfNeeded();
491 return input.readUnsignedByte();
495 public short readShort() throws IOException {
496 readSignatureMarkerAndVersionIfNeeded();
497 return input.readShort();
501 public int readUnsignedShort() throws IOException {
502 readSignatureMarkerAndVersionIfNeeded();
503 return input.readUnsignedShort();
507 public char readChar() throws IOException {
508 readSignatureMarkerAndVersionIfNeeded();
509 return input.readChar();
513 public int readInt() throws IOException {
514 readSignatureMarkerAndVersionIfNeeded();
515 return input.readInt();
519 public long readLong() throws IOException {
520 readSignatureMarkerAndVersionIfNeeded();
521 return input.readLong();
525 public float readFloat() throws IOException {
526 readSignatureMarkerAndVersionIfNeeded();
527 return input.readFloat();
531 public double readDouble() throws IOException {
532 readSignatureMarkerAndVersionIfNeeded();
533 return input.readDouble();
537 public String readLine() throws IOException {
538 readSignatureMarkerAndVersionIfNeeded();
539 return input.readLine();
543 public String readUTF() throws IOException {
544 readSignatureMarkerAndVersionIfNeeded();
545 return input.readUTF();