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
8 package org.opendaylight.controller.cluster.datastore.node.utils.stream;
10 import static java.util.Objects.requireNonNull;
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.AugmentationIdentifier;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
38 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
41 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
42 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
43 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
44 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
45 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48 import org.w3c.dom.Element;
49 import org.xml.sax.InputSource;
50 import org.xml.sax.SAXException;
53 * NormalizedNodeInputStreamReader reads the byte stream and constructs the normalized node including its children
54 * nodes. This process goes in recursive manner, where each NodeTypes object signifies the start of the object, except
55 * END_NODE. If a node can have children, then that node's end is calculated based on appearance of END_NODE.
57 public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput {
59 private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeInputStreamReader.class);
61 private final DataInput input;
63 private final List<String> codedStringMap = new ArrayList<>();
65 private QName lastLeafSetQName;
67 private NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder;
69 @SuppressWarnings("rawtypes")
70 private NormalizedNodeBuilder<NodeWithValue, Object, LeafSetEntryNode<Object>> leafSetEntryBuilder;
72 private boolean readSignatureMarker = true;
74 NormalizedNodeInputStreamReader(final DataInput input, final boolean versionChecked) {
75 this.input = requireNonNull(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 AugmentationIdentifier augIdentifier = readAugmentationIdentifier();
115 LOG.trace("Reading augmentation node {} ", augIdentifier);
116 return addDataContainerChildren(Builders.augmentationBuilder().withNodeIdentifier(augIdentifier))
119 case NodeTypes.LEAF_SET_ENTRY_NODE:
120 final QName name = lastLeafSetQName != null ? lastLeafSetQName : readQName();
121 final Object value = readObject();
122 final NodeWithValue<Object> leafIdentifier = new NodeWithValue<>(name, value);
123 LOG.trace("Reading leaf set entry node {}, value {}", leafIdentifier, value);
124 return leafSetEntryBuilder().withNodeIdentifier(leafIdentifier).withValue(value).build();
126 case NodeTypes.MAP_ENTRY_NODE:
127 final NodeIdentifierWithPredicates entryIdentifier = readNormalizedNodeWithPredicates();
128 LOG.trace("Reading map entry node {} ", entryIdentifier);
129 return addDataContainerChildren(Builders.mapEntryBuilder().withNodeIdentifier(entryIdentifier))
133 return readNodeIdentifierDependentNode(nodeType, readNodeIdentifier());
137 private NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder() {
138 if (leafBuilder == null) {
139 leafBuilder = Builders.leafBuilder();
145 @SuppressWarnings("rawtypes")
146 private NormalizedNodeBuilder<NodeWithValue, Object, LeafSetEntryNode<Object>> leafSetEntryBuilder() {
147 if (leafSetEntryBuilder == null) {
148 leafSetEntryBuilder = Builders.leafSetEntryBuilder();
151 return leafSetEntryBuilder;
154 private NormalizedNode<?, ?> readNodeIdentifierDependentNode(final byte nodeType, final NodeIdentifier identifier)
158 case NodeTypes.LEAF_NODE:
159 LOG.trace("Read leaf node {}", identifier);
160 // Read the object value
161 return leafBuilder().withNodeIdentifier(identifier).withValue(readObject()).build();
163 case NodeTypes.ANY_XML_NODE:
164 LOG.trace("Read xml node");
165 return Builders.anyXmlBuilder().withNodeIdentifier(identifier).withValue(readDOMSource()).build();
167 case NodeTypes.MAP_NODE:
168 LOG.trace("Read map node {}", identifier);
169 return addDataContainerChildren(Builders.mapBuilder().withNodeIdentifier(identifier)).build();
171 case NodeTypes.CHOICE_NODE:
172 LOG.trace("Read choice node {}", identifier);
173 return addDataContainerChildren(Builders.choiceBuilder().withNodeIdentifier(identifier)).build();
175 case NodeTypes.ORDERED_MAP_NODE:
176 LOG.trace("Reading ordered map node {}", identifier);
177 return addDataContainerChildren(Builders.orderedMapBuilder().withNodeIdentifier(identifier)).build();
179 case NodeTypes.UNKEYED_LIST:
180 LOG.trace("Read unkeyed list node {}", identifier);
181 return addDataContainerChildren(Builders.unkeyedListBuilder().withNodeIdentifier(identifier)).build();
183 case NodeTypes.UNKEYED_LIST_ITEM:
184 LOG.trace("Read unkeyed list item node {}", identifier);
185 return addDataContainerChildren(Builders.unkeyedListEntryBuilder()
186 .withNodeIdentifier(identifier)).build();
188 case NodeTypes.CONTAINER_NODE:
189 LOG.trace("Read container node {}", identifier);
190 return addDataContainerChildren(Builders.containerBuilder().withNodeIdentifier(identifier)).build();
192 case NodeTypes.LEAF_SET:
193 LOG.trace("Read leaf set node {}", identifier);
194 return addLeafSetChildren(identifier.getNodeType(),
195 Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
197 case NodeTypes.ORDERED_LEAF_SET:
198 LOG.trace("Read ordered leaf set node {}", identifier);
199 return addLeafSetChildren(identifier.getNodeType(),
200 Builders.orderedLeafSetBuilder().withNodeIdentifier(identifier)).build();
207 private DOMSource readDOMSource() throws IOException {
208 String xml = readObject().toString();
210 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
211 factory.setNamespaceAware(true);
212 Element node = factory.newDocumentBuilder().parse(
213 new InputSource(new StringReader(xml))).getDocumentElement();
214 return new DOMSource(node);
215 } catch (SAXException | ParserConfigurationException e) {
216 throw new IOException("Error parsing XML: " + xml, e);
220 private QName readQName() throws IOException {
221 // Read in the same sequence of writing
222 String localName = readCodedString();
223 String namespace = readCodedString();
224 String revision = Strings.emptyToNull(readCodedString());
226 return QNameFactory.create(new QNameFactory.Key(localName, namespace, revision));
230 private String readCodedString() throws IOException {
231 final byte valueType = input.readByte();
233 case TokenTypes.IS_NULL_VALUE:
235 case TokenTypes.IS_CODE_VALUE:
236 final int code = input.readInt();
238 return codedStringMap.get(code);
239 } catch (IndexOutOfBoundsException e) {
240 throw new IOException("String code " + code + " was not found", e);
242 case TokenTypes.IS_STRING_VALUE:
243 final String value = input.readUTF().intern();
244 codedStringMap.add(value);
247 throw new IOException("Unhandled string value type " + valueType);
251 private Set<QName> readQNameSet() throws IOException {
252 // Read the children count
253 int count = input.readInt();
254 Set<QName> children = new HashSet<>(count);
255 for (int i = 0; i < count; i++) {
256 children.add(readQName());
261 private AugmentationIdentifier readAugmentationIdentifier() throws IOException {
262 // FIXME: we should have a cache for these, too
263 return new AugmentationIdentifier(readQNameSet());
266 private NodeIdentifier readNodeIdentifier() throws IOException {
267 // FIXME: we should have a cache for these, too
268 return new NodeIdentifier(readQName());
271 private NodeIdentifierWithPredicates readNormalizedNodeWithPredicates() throws IOException {
272 final QName qname = readQName();
273 final int count = input.readInt();
276 return new NodeIdentifierWithPredicates(qname);
278 return new NodeIdentifierWithPredicates(qname, readQName(), readObject());
280 // ImmutableList is used by ImmutableOffsetMapTemplate for lookups, hence we use that.
281 final Builder<QName> keys = ImmutableList.builderWithExpectedSize(count);
282 final Object[] values = new Object[count];
283 for (int i = 0; i < count; i++) {
284 keys.add(readQName());
285 values[i] = readObject();
288 return new NodeIdentifierWithPredicates(qname, ImmutableOffsetMapTemplate.ordered(keys.build())
289 .instantiateWithValues(values));
293 private Object readObject() throws IOException {
294 byte objectType = input.readByte();
295 switch (objectType) {
296 case ValueTypes.BITS_TYPE:
299 case ValueTypes.BOOL_TYPE:
300 return input.readBoolean();
302 case ValueTypes.BYTE_TYPE:
303 return input.readByte();
305 case ValueTypes.INT_TYPE:
306 return input.readInt();
308 case ValueTypes.LONG_TYPE:
309 return input.readLong();
311 case ValueTypes.QNAME_TYPE:
314 case ValueTypes.SHORT_TYPE:
315 return input.readShort();
317 case ValueTypes.STRING_TYPE:
318 return input.readUTF();
320 case ValueTypes.STRING_BYTES_TYPE:
321 return readStringBytes();
323 case ValueTypes.BIG_DECIMAL_TYPE:
324 return new BigDecimal(input.readUTF());
326 case ValueTypes.BIG_INTEGER_TYPE:
327 return new BigInteger(input.readUTF());
329 case ValueTypes.BINARY_TYPE:
330 byte[] bytes = new byte[input.readInt()];
331 input.readFully(bytes);
334 case ValueTypes.YANG_IDENTIFIER_TYPE:
335 return readYangInstanceIdentifierInternal();
337 case ValueTypes.EMPTY_TYPE:
338 // Leaf nodes no longer allow null values and thus we no longer emit null values. Previously, the "empty"
339 // yang type was represented as null so we translate an incoming null value to Empty. It was possible for
340 // a BI user to set a string leaf to null and we're rolling the dice here but the chances for that are
341 // very low. We'd have to know the yang type but, even if we did, we can't let a null value pass upstream
342 // so we'd have to drop the leaf which might cause other issues.
343 case ValueTypes.NULL_TYPE:
344 return Empty.getInstance();
351 private String readStringBytes() throws IOException {
352 byte[] bytes = new byte[input.readInt()];
353 input.readFully(bytes);
354 return new String(bytes, StandardCharsets.UTF_8);
358 public SchemaPath readSchemaPath() throws IOException {
359 readSignatureMarkerAndVersionIfNeeded();
361 final boolean absolute = input.readBoolean();
362 final int size = input.readInt();
364 final Builder<QName> qnames = ImmutableList.builderWithExpectedSize(size);
365 for (int i = 0; i < size; ++i) {
366 qnames.add(readQName());
368 return SchemaPath.create(qnames.build(), absolute);
372 public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
373 readSignatureMarkerAndVersionIfNeeded();
374 return readYangInstanceIdentifierInternal();
377 private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
378 int size = input.readInt();
379 final Builder<PathArgument> pathArguments = ImmutableList.builderWithExpectedSize(size);
380 for (int i = 0; i < size; i++) {
381 pathArguments.add(readPathArgument());
383 return YangInstanceIdentifier.create(pathArguments.build());
386 private Set<String> readObjSet() throws IOException {
387 int count = input.readInt();
388 Set<String> children = new HashSet<>(count);
389 for (int i = 0; i < count; i++) {
390 children.add(readCodedString());
396 public PathArgument readPathArgument() throws IOException {
398 int type = input.readByte();
401 case PathArgumentTypes.AUGMENTATION_IDENTIFIER:
402 return readAugmentationIdentifier();
403 case PathArgumentTypes.NODE_IDENTIFIER:
404 return readNodeIdentifier();
405 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES:
406 return readNormalizedNodeWithPredicates();
407 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE:
408 return new NodeWithValue<>(readQName(), readObject());
410 // FIXME: throw hard error
415 @SuppressWarnings("unchecked")
416 private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(final QName nodeType,
417 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
419 LOG.trace("Reading children of leaf set");
421 lastLeafSetQName = nodeType;
423 LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
425 while (child != null) {
426 builder.withChild(child);
427 child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
432 @SuppressWarnings({ "unchecked", "rawtypes" })
433 private NormalizedNodeContainerBuilder addDataContainerChildren(
434 final NormalizedNodeContainerBuilder builder) throws IOException {
435 LOG.trace("Reading data container (leaf nodes) nodes");
437 NormalizedNode<?, ?> child = readNormalizedNodeInternal();
439 while (child != null) {
440 builder.addChild(child);
441 child = readNormalizedNodeInternal();
447 public void readFully(final byte[] value) throws IOException {
448 readSignatureMarkerAndVersionIfNeeded();
449 input.readFully(value);
453 public void readFully(final byte[] str, final int off, final int len) throws IOException {
454 readSignatureMarkerAndVersionIfNeeded();
455 input.readFully(str, off, len);
459 public int skipBytes(final int num) throws IOException {
460 readSignatureMarkerAndVersionIfNeeded();
461 return input.skipBytes(num);
465 public boolean readBoolean() throws IOException {
466 readSignatureMarkerAndVersionIfNeeded();
467 return input.readBoolean();
471 public byte readByte() throws IOException {
472 readSignatureMarkerAndVersionIfNeeded();
473 return input.readByte();
477 public int readUnsignedByte() throws IOException {
478 readSignatureMarkerAndVersionIfNeeded();
479 return input.readUnsignedByte();
483 public short readShort() throws IOException {
484 readSignatureMarkerAndVersionIfNeeded();
485 return input.readShort();
489 public int readUnsignedShort() throws IOException {
490 readSignatureMarkerAndVersionIfNeeded();
491 return input.readUnsignedShort();
495 public char readChar() throws IOException {
496 readSignatureMarkerAndVersionIfNeeded();
497 return input.readChar();
501 public int readInt() throws IOException {
502 readSignatureMarkerAndVersionIfNeeded();
503 return input.readInt();
507 public long readLong() throws IOException {
508 readSignatureMarkerAndVersionIfNeeded();
509 return input.readLong();
513 public float readFloat() throws IOException {
514 readSignatureMarkerAndVersionIfNeeded();
515 return input.readFloat();
519 public double readDouble() throws IOException {
520 readSignatureMarkerAndVersionIfNeeded();
521 return input.readDouble();
525 public String readLine() throws IOException {
526 readSignatureMarkerAndVersionIfNeeded();
527 return input.readLine();
531 public String readUTF() throws IOException {
532 readSignatureMarkerAndVersionIfNeeded();
533 return input.readUTF();