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.NormalizedNodeAttrBuilder;
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 NormalizedNodeAttrBuilder<NodeIdentifier, 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 = 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 NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder() {
138 if (leafBuilder == null) {
139 leafBuilder = Builders.leafBuilder();
145 @SuppressWarnings("rawtypes")
146 private NormalizedNodeAttrBuilder<NodeWithValue, Object,
147 LeafSetEntryNode<Object>> leafSetEntryBuilder() {
148 if (leafSetEntryBuilder == null) {
149 leafSetEntryBuilder = Builders.leafSetEntryBuilder();
152 return leafSetEntryBuilder;
155 private NormalizedNode<?, ?> readNodeIdentifierDependentNode(final byte nodeType, final NodeIdentifier identifier)
159 case NodeTypes.LEAF_NODE:
160 LOG.trace("Read leaf node {}", identifier);
161 // Read the object value
162 return leafBuilder().withNodeIdentifier(identifier).withValue(readObject()).build();
164 case NodeTypes.ANY_XML_NODE:
165 LOG.trace("Read xml node");
166 return Builders.anyXmlBuilder().withNodeIdentifier(identifier).withValue(readDOMSource()).build();
168 case NodeTypes.MAP_NODE:
169 LOG.trace("Read map node {}", identifier);
170 return addDataContainerChildren(Builders.mapBuilder().withNodeIdentifier(identifier)).build();
172 case NodeTypes.CHOICE_NODE:
173 LOG.trace("Read choice node {}", identifier);
174 return addDataContainerChildren(Builders.choiceBuilder().withNodeIdentifier(identifier)).build();
176 case NodeTypes.ORDERED_MAP_NODE:
177 LOG.trace("Reading ordered map node {}", identifier);
178 return addDataContainerChildren(Builders.orderedMapBuilder().withNodeIdentifier(identifier)).build();
180 case NodeTypes.UNKEYED_LIST:
181 LOG.trace("Read unkeyed list node {}", identifier);
182 return addDataContainerChildren(Builders.unkeyedListBuilder().withNodeIdentifier(identifier)).build();
184 case NodeTypes.UNKEYED_LIST_ITEM:
185 LOG.trace("Read unkeyed list item node {}", identifier);
186 return addDataContainerChildren(Builders.unkeyedListEntryBuilder()
187 .withNodeIdentifier(identifier)).build();
189 case NodeTypes.CONTAINER_NODE:
190 LOG.trace("Read container node {}", identifier);
191 return addDataContainerChildren(Builders.containerBuilder().withNodeIdentifier(identifier)).build();
193 case NodeTypes.LEAF_SET:
194 LOG.trace("Read leaf set node {}", identifier);
195 return addLeafSetChildren(identifier.getNodeType(),
196 Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
198 case NodeTypes.ORDERED_LEAF_SET:
199 LOG.trace("Read ordered leaf set node {}", identifier);
200 return addLeafSetChildren(identifier.getNodeType(),
201 Builders.orderedLeafSetBuilder().withNodeIdentifier(identifier)).build();
208 private DOMSource readDOMSource() throws IOException {
209 String xml = readObject().toString();
211 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
212 factory.setNamespaceAware(true);
213 Element node = factory.newDocumentBuilder().parse(
214 new InputSource(new StringReader(xml))).getDocumentElement();
215 return new DOMSource(node);
216 } catch (SAXException | ParserConfigurationException e) {
217 throw new IOException("Error parsing XML: " + xml, e);
221 private QName readQName() throws IOException {
222 // Read in the same sequence of writing
223 String localName = readCodedString();
224 String namespace = readCodedString();
225 String revision = Strings.emptyToNull(readCodedString());
227 return QNameFactory.create(new QNameFactory.Key(localName, namespace, revision));
231 private String readCodedString() throws IOException {
232 final byte valueType = input.readByte();
234 case TokenTypes.IS_NULL_VALUE:
236 case TokenTypes.IS_CODE_VALUE:
237 final int code = input.readInt();
239 return codedStringMap.get(code);
240 } catch (IndexOutOfBoundsException e) {
241 throw new IOException("String code " + code + " was not found", e);
243 case TokenTypes.IS_STRING_VALUE:
244 final String value = input.readUTF().intern();
245 codedStringMap.add(value);
248 throw new IOException("Unhandled string value type " + valueType);
252 private Set<QName> readQNameSet() throws IOException {
253 // Read the children count
254 int count = input.readInt();
255 Set<QName> children = new HashSet<>(count);
256 for (int i = 0; i < count; i++) {
257 children.add(readQName());
262 private AugmentationIdentifier readAugmentationIdentifier() throws IOException {
263 // FIXME: we should have a cache for these, too
264 return new AugmentationIdentifier(readQNameSet());
267 private NodeIdentifier readNodeIdentifier() throws IOException {
268 // FIXME: we should have a cache for these, too
269 return new NodeIdentifier(readQName());
272 private NodeIdentifierWithPredicates readNormalizedNodeWithPredicates() throws IOException {
273 final QName qname = readQName();
274 final int count = input.readInt();
277 return new NodeIdentifierWithPredicates(qname);
279 return new NodeIdentifierWithPredicates(qname, readQName(), readObject());
281 // ImmutableList is used by ImmutableOffsetMapTemplate for lookups, hence we use that.
282 final Builder<QName> keys = ImmutableList.builderWithExpectedSize(count);
283 final Object[] values = new Object[count];
284 for (int i = 0; i < count; i++) {
285 keys.add(readQName());
286 values[i] = readObject();
289 return new NodeIdentifierWithPredicates(qname, ImmutableOffsetMapTemplate.ordered(keys.build())
290 .instantiateWithValues(values));
294 private Object readObject() throws IOException {
295 byte objectType = input.readByte();
296 switch (objectType) {
297 case ValueTypes.BITS_TYPE:
300 case ValueTypes.BOOL_TYPE:
301 return input.readBoolean();
303 case ValueTypes.BYTE_TYPE:
304 return input.readByte();
306 case ValueTypes.INT_TYPE:
307 return input.readInt();
309 case ValueTypes.LONG_TYPE:
310 return input.readLong();
312 case ValueTypes.QNAME_TYPE:
315 case ValueTypes.SHORT_TYPE:
316 return input.readShort();
318 case ValueTypes.STRING_TYPE:
319 return input.readUTF();
321 case ValueTypes.STRING_BYTES_TYPE:
322 return readStringBytes();
324 case ValueTypes.BIG_DECIMAL_TYPE:
325 return new BigDecimal(input.readUTF());
327 case ValueTypes.BIG_INTEGER_TYPE:
328 return new BigInteger(input.readUTF());
330 case ValueTypes.BINARY_TYPE:
331 byte[] bytes = new byte[input.readInt()];
332 input.readFully(bytes);
335 case ValueTypes.YANG_IDENTIFIER_TYPE:
336 return readYangInstanceIdentifierInternal();
338 case ValueTypes.EMPTY_TYPE:
339 // Leaf nodes no longer allow null values and thus we no longer emit null values. Previously, the "empty"
340 // yang type was represented as null so we translate an incoming null value to Empty. It was possible for
341 // a BI user to set a string leaf to null and we're rolling the dice here but the chances for that are
342 // very low. We'd have to know the yang type but, even if we did, we can't let a null value pass upstream
343 // so we'd have to drop the leaf which might cause other issues.
344 case ValueTypes.NULL_TYPE:
345 return Empty.getInstance();
352 private String readStringBytes() throws IOException {
353 byte[] bytes = new byte[input.readInt()];
354 input.readFully(bytes);
355 return new String(bytes, StandardCharsets.UTF_8);
359 public SchemaPath readSchemaPath() throws IOException {
360 readSignatureMarkerAndVersionIfNeeded();
362 final boolean absolute = input.readBoolean();
363 final int size = input.readInt();
365 final Builder<QName> qnames = ImmutableList.builderWithExpectedSize(size);
366 for (int i = 0; i < size; ++i) {
367 qnames.add(readQName());
369 return SchemaPath.create(qnames.build(), absolute);
373 public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
374 readSignatureMarkerAndVersionIfNeeded();
375 return readYangInstanceIdentifierInternal();
378 private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
379 int size = input.readInt();
380 final Builder<PathArgument> pathArguments = ImmutableList.builderWithExpectedSize(size);
381 for (int i = 0; i < size; i++) {
382 pathArguments.add(readPathArgument());
384 return YangInstanceIdentifier.create(pathArguments.build());
387 private Set<String> readObjSet() throws IOException {
388 int count = input.readInt();
389 Set<String> children = new HashSet<>(count);
390 for (int i = 0; i < count; i++) {
391 children.add(readCodedString());
397 public PathArgument readPathArgument() throws IOException {
399 int type = input.readByte();
402 case PathArgumentTypes.AUGMENTATION_IDENTIFIER:
403 return readAugmentationIdentifier();
404 case PathArgumentTypes.NODE_IDENTIFIER:
405 return readNodeIdentifier();
406 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES:
407 return readNormalizedNodeWithPredicates();
408 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE:
409 return new NodeWithValue<>(readQName(), readObject());
411 // FIXME: throw hard error
416 @SuppressWarnings("unchecked")
417 private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(final QName nodeType,
418 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
420 LOG.trace("Reading children of leaf set");
422 lastLeafSetQName = nodeType;
424 LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
426 while (child != null) {
427 builder.withChild(child);
428 child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
433 @SuppressWarnings({ "unchecked", "rawtypes" })
434 private NormalizedNodeContainerBuilder addDataContainerChildren(
435 final NormalizedNodeContainerBuilder builder) throws IOException {
436 LOG.trace("Reading data container (leaf nodes) nodes");
438 NormalizedNode<?, ?> child = readNormalizedNodeInternal();
440 while (child != null) {
441 builder.addChild(child);
442 child = readNormalizedNodeInternal();
448 public void readFully(final byte[] value) throws IOException {
449 readSignatureMarkerAndVersionIfNeeded();
450 input.readFully(value);
454 public void readFully(final byte[] str, final int off, final int len) throws IOException {
455 readSignatureMarkerAndVersionIfNeeded();
456 input.readFully(str, off, len);
460 public int skipBytes(final int num) throws IOException {
461 readSignatureMarkerAndVersionIfNeeded();
462 return input.skipBytes(num);
466 public boolean readBoolean() throws IOException {
467 readSignatureMarkerAndVersionIfNeeded();
468 return input.readBoolean();
472 public byte readByte() throws IOException {
473 readSignatureMarkerAndVersionIfNeeded();
474 return input.readByte();
478 public int readUnsignedByte() throws IOException {
479 readSignatureMarkerAndVersionIfNeeded();
480 return input.readUnsignedByte();
484 public short readShort() throws IOException {
485 readSignatureMarkerAndVersionIfNeeded();
486 return input.readShort();
490 public int readUnsignedShort() throws IOException {
491 readSignatureMarkerAndVersionIfNeeded();
492 return input.readUnsignedShort();
496 public char readChar() throws IOException {
497 readSignatureMarkerAndVersionIfNeeded();
498 return input.readChar();
502 public int readInt() throws IOException {
503 readSignatureMarkerAndVersionIfNeeded();
504 return input.readInt();
508 public long readLong() throws IOException {
509 readSignatureMarkerAndVersionIfNeeded();
510 return input.readLong();
514 public float readFloat() throws IOException {
515 readSignatureMarkerAndVersionIfNeeded();
516 return input.readFloat();
520 public double readDouble() throws IOException {
521 readSignatureMarkerAndVersionIfNeeded();
522 return input.readDouble();
526 public String readLine() throws IOException {
527 readSignatureMarkerAndVersionIfNeeded();
528 return input.readLine();
532 public String readUTF() throws IOException {
533 readSignatureMarkerAndVersionIfNeeded();
534 return input.readUTF();