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 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;
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;
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.
55 public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput {
57 private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeInputStreamReader.class);
59 private static final String REVISION_ARG = "?revision=";
61 private final DataInput input;
63 private final Map<Integer, String> codedStringMap = new HashMap<>();
65 private QName lastLeafSetQName;
67 private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
68 Object, LeafNode<Object>> leafBuilder;
70 @SuppressWarnings("rawtypes")
71 private NormalizedNodeAttrBuilder<NodeWithValue, Object, LeafSetEntryNode<Object>> leafSetEntryBuilder;
73 private final StringBuilder reusableStringBuilder = new StringBuilder(50);
75 private boolean readSignatureMarker = true;
77 NormalizedNodeInputStreamReader(final DataInput input, final boolean versionChecked) {
78 this.input = Preconditions.checkNotNull(input);
79 readSignatureMarker = !versionChecked;
83 public NormalizedNode<?, ?> readNormalizedNode() throws IOException {
84 readSignatureMarkerAndVersionIfNeeded();
85 return readNormalizedNodeInternal();
88 private void readSignatureMarkerAndVersionIfNeeded() throws IOException {
89 if (readSignatureMarker) {
90 readSignatureMarker = false;
92 final byte marker = input.readByte();
93 if (marker != TokenTypes.SIGNATURE_MARKER) {
94 throw new InvalidNormalizedNodeStreamException(String.format(
95 "Invalid signature marker: %d", marker));
98 final short version = input.readShort();
99 if (version != TokenTypes.LITHIUM_VERSION) {
100 throw new InvalidNormalizedNodeStreamException(String.format("Unhandled stream version %s", version));
105 private NormalizedNode<?, ?> readNormalizedNodeInternal() throws IOException {
106 // each node should start with a byte
107 byte nodeType = input.readByte();
109 if (nodeType == NodeTypes.END_NODE) {
110 LOG.trace("End node reached. return");
111 lastLeafSetQName = null;
116 case NodeTypes.AUGMENTATION_NODE :
117 YangInstanceIdentifier.AugmentationIdentifier augIdentifier =
118 new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
120 LOG.trace("Reading augmentation node {} ", augIdentifier);
122 return addDataContainerChildren(Builders.augmentationBuilder()
123 .withNodeIdentifier(augIdentifier)).build();
125 case NodeTypes.LEAF_SET_ENTRY_NODE :
126 QName name = lastLeafSetQName;
131 Object value = readObject();
132 NodeWithValue<Object> leafIdentifier = new NodeWithValue<>(name, value);
134 LOG.trace("Reading leaf set entry node {}, value {}", leafIdentifier, value);
136 return leafSetEntryBuilder().withNodeIdentifier(leafIdentifier).withValue(value).build();
138 case NodeTypes.MAP_ENTRY_NODE :
139 NodeIdentifierWithPredicates entryIdentifier = new NodeIdentifierWithPredicates(
140 readQName(), readKeyValueMap());
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 ListNodeBuilder<Object, LeafSetEntryNode<Object>> orderedLeafSetBuilder =
217 Builders.orderedLeafSetBuilder().withNodeIdentifier(identifier);
218 orderedLeafSetBuilder = addLeafSetChildren(identifier.getNodeType(), orderedLeafSetBuilder);
219 return orderedLeafSetBuilder.build();
226 private DOMSource readDOMSource() throws IOException {
227 String xml = readObject().toString();
229 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
230 factory.setNamespaceAware(true);
231 Element node = factory.newDocumentBuilder().parse(
232 new InputSource(new StringReader(xml))).getDocumentElement();
233 return new DOMSource(node);
234 } catch (SAXException | ParserConfigurationException e) {
235 throw new IOException("Error parsing XML: " + xml, e);
239 private QName readQName() throws IOException {
240 // Read in the same sequence of writing
241 String localName = readCodedString();
242 String namespace = readCodedString();
243 String revision = readCodedString();
246 if (!Strings.isNullOrEmpty(revision)) {
247 qname = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG).append(revision)
248 .append(')').append(localName).toString();
250 qname = reusableStringBuilder.append('(').append(namespace).append(')').append(localName).toString();
253 reusableStringBuilder.delete(0, reusableStringBuilder.length());
254 return QNameFactory.create(qname);
258 private String readCodedString() throws IOException {
259 byte valueType = input.readByte();
260 if (valueType == TokenTypes.IS_CODE_VALUE) {
261 return codedStringMap.get(input.readInt());
262 } else if (valueType == TokenTypes.IS_STRING_VALUE) {
263 String value = input.readUTF().intern();
264 codedStringMap.put(Integer.valueOf(codedStringMap.size()), value);
271 private Set<QName> readQNameSet() throws IOException {
272 // Read the children count
273 int count = input.readInt();
274 Set<QName> children = new HashSet<>(count);
275 for (int i = 0; i < count; i++) {
276 children.add(readQName());
281 private Map<QName, Object> readKeyValueMap() throws IOException {
282 int count = input.readInt();
283 Map<QName, Object> keyValueMap = new HashMap<>(count);
285 for (int i = 0; i < count; i++) {
286 keyValueMap.put(readQName(), readObject());
292 private Object readObject() throws IOException {
293 byte objectType = input.readByte();
294 switch (objectType) {
295 case ValueTypes.BITS_TYPE:
298 case ValueTypes.BOOL_TYPE :
299 return Boolean.valueOf(input.readBoolean());
301 case ValueTypes.BYTE_TYPE :
302 return Byte.valueOf(input.readByte());
304 case ValueTypes.INT_TYPE :
305 return Integer.valueOf(input.readInt());
307 case ValueTypes.LONG_TYPE :
308 return Long.valueOf(input.readLong());
310 case ValueTypes.QNAME_TYPE :
313 case ValueTypes.SHORT_TYPE :
314 return Short.valueOf(input.readShort());
316 case ValueTypes.STRING_TYPE :
317 return input.readUTF();
319 case ValueTypes.STRING_BYTES_TYPE:
320 return readStringBytes();
322 case ValueTypes.BIG_DECIMAL_TYPE :
323 return new BigDecimal(input.readUTF());
325 case ValueTypes.BIG_INTEGER_TYPE :
326 return new BigInteger(input.readUTF());
328 case ValueTypes.BINARY_TYPE :
329 byte[] bytes = new byte[input.readInt()];
330 input.readFully(bytes);
333 case ValueTypes.YANG_IDENTIFIER_TYPE :
334 return readYangInstanceIdentifierInternal();
341 private String readStringBytes() throws IOException {
342 byte[] bytes = new byte[input.readInt()];
343 input.readFully(bytes);
344 return new String(bytes, StandardCharsets.UTF_8);
348 public SchemaPath readSchemaPath() throws IOException {
349 readSignatureMarkerAndVersionIfNeeded();
351 final boolean absolute = input.readBoolean();
352 final int size = input.readInt();
353 final Collection<QName> qnames = new ArrayList<>(size);
354 for (int i = 0; i < size; ++i) {
355 qnames.add(readQName());
358 return SchemaPath.create(qnames, absolute);
362 public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
363 readSignatureMarkerAndVersionIfNeeded();
364 return readYangInstanceIdentifierInternal();
367 private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
368 int size = input.readInt();
370 List<PathArgument> pathArguments = new ArrayList<>(size);
372 for (int i = 0; i < size; i++) {
373 pathArguments.add(readPathArgument());
375 return YangInstanceIdentifier.create(pathArguments);
378 private Set<String> readObjSet() throws IOException {
379 int count = input.readInt();
380 Set<String> children = new HashSet<>(count);
381 for (int i = 0; i < count; i++) {
382 children.add(readCodedString());
388 public PathArgument readPathArgument() throws IOException {
390 int type = input.readByte();
394 case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
395 return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
397 case PathArgumentTypes.NODE_IDENTIFIER :
398 return new NodeIdentifier(readQName());
400 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES :
401 return new NodeIdentifierWithPredicates(readQName(), readKeyValueMap());
403 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
404 return new NodeWithValue<>(readQName(), readObject());
411 @SuppressWarnings("unchecked")
412 private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(final QName nodeType,
413 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
415 LOG.trace("Reading children of leaf set");
417 lastLeafSetQName = nodeType;
419 LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
421 while (child != null) {
422 builder.withChild(child);
423 child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
428 @SuppressWarnings({ "unchecked", "rawtypes" })
429 private NormalizedNodeContainerBuilder addDataContainerChildren(
430 final NormalizedNodeContainerBuilder builder) throws IOException {
431 LOG.trace("Reading data container (leaf nodes) nodes");
433 NormalizedNode<?, ?> child = readNormalizedNodeInternal();
435 while (child != null) {
436 builder.addChild(child);
437 child = readNormalizedNodeInternal();
443 public void readFully(final byte[] value) throws IOException {
444 readSignatureMarkerAndVersionIfNeeded();
445 input.readFully(value);
449 public void readFully(final byte[] str, final int off, final int len) throws IOException {
450 readSignatureMarkerAndVersionIfNeeded();
451 input.readFully(str, off, len);
455 public int skipBytes(final int num) throws IOException {
456 readSignatureMarkerAndVersionIfNeeded();
457 return input.skipBytes(num);
461 public boolean readBoolean() throws IOException {
462 readSignatureMarkerAndVersionIfNeeded();
463 return input.readBoolean();
467 public byte readByte() throws IOException {
468 readSignatureMarkerAndVersionIfNeeded();
469 return input.readByte();
473 public int readUnsignedByte() throws IOException {
474 readSignatureMarkerAndVersionIfNeeded();
475 return input.readUnsignedByte();
479 public short readShort() throws IOException {
480 readSignatureMarkerAndVersionIfNeeded();
481 return input.readShort();
485 public int readUnsignedShort() throws IOException {
486 readSignatureMarkerAndVersionIfNeeded();
487 return input.readUnsignedShort();
491 public char readChar() throws IOException {
492 readSignatureMarkerAndVersionIfNeeded();
493 return input.readChar();
497 public int readInt() throws IOException {
498 readSignatureMarkerAndVersionIfNeeded();
499 return input.readInt();
503 public long readLong() throws IOException {
504 readSignatureMarkerAndVersionIfNeeded();
505 return input.readLong();
509 public float readFloat() throws IOException {
510 readSignatureMarkerAndVersionIfNeeded();
511 return input.readFloat();
515 public double readDouble() throws IOException {
516 readSignatureMarkerAndVersionIfNeeded();
517 return input.readDouble();
521 public String readLine() throws IOException {
522 readSignatureMarkerAndVersionIfNeeded();
523 return input.readLine();
527 public String readUTF() throws IOException {
528 readSignatureMarkerAndVersionIfNeeded();
529 return input.readUTF();