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");
115 case NodeTypes.AUGMENTATION_NODE :
116 YangInstanceIdentifier.AugmentationIdentifier augIdentifier =
117 new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
119 LOG.trace("Reading augmentation node {} ", augIdentifier);
121 return addDataContainerChildren(Builders.augmentationBuilder()
122 .withNodeIdentifier(augIdentifier)).build();
124 case NodeTypes.LEAF_SET_ENTRY_NODE :
125 QName name = lastLeafSetQName;
130 Object value = readObject();
131 NodeWithValue<Object> leafIdentifier = new NodeWithValue<>(name, value);
133 LOG.trace("Reading leaf set entry node {}, value {}", leafIdentifier, value);
135 return leafSetEntryBuilder().withNodeIdentifier(leafIdentifier).withValue(value).build();
137 case NodeTypes.MAP_ENTRY_NODE :
138 NodeIdentifierWithPredicates entryIdentifier = new NodeIdentifierWithPredicates(
139 readQName(), readKeyValueMap());
141 LOG.trace("Reading map entry node {} ", entryIdentifier);
143 return addDataContainerChildren(Builders.mapEntryBuilder()
144 .withNodeIdentifier(entryIdentifier)).build();
147 return readNodeIdentifierDependentNode(nodeType, new NodeIdentifier(readQName()));
151 private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
152 Object, LeafNode<Object>> leafBuilder() {
153 if (leafBuilder == null) {
154 leafBuilder = Builders.leafBuilder();
160 @SuppressWarnings("rawtypes")
161 private NormalizedNodeAttrBuilder<NodeWithValue, Object,
162 LeafSetEntryNode<Object>> leafSetEntryBuilder() {
163 if (leafSetEntryBuilder == null) {
164 leafSetEntryBuilder = Builders.leafSetEntryBuilder();
167 return leafSetEntryBuilder;
170 private NormalizedNode<?, ?> readNodeIdentifierDependentNode(final byte nodeType, final NodeIdentifier identifier)
174 case NodeTypes.LEAF_NODE :
175 LOG.trace("Read leaf node {}", identifier);
176 // Read the object value
177 return leafBuilder().withNodeIdentifier(identifier).withValue(readObject()).build();
179 case NodeTypes.ANY_XML_NODE :
180 LOG.trace("Read xml node");
181 return Builders.anyXmlBuilder().withNodeIdentifier(identifier).withValue(readDOMSource()).build();
183 case NodeTypes.MAP_NODE :
184 LOG.trace("Read map node {}", identifier);
185 return addDataContainerChildren(Builders.mapBuilder().withNodeIdentifier(identifier)).build();
187 case NodeTypes.CHOICE_NODE:
188 LOG.trace("Read choice node {}", identifier);
189 return addDataContainerChildren(Builders.choiceBuilder().withNodeIdentifier(identifier)).build();
191 case NodeTypes.ORDERED_MAP_NODE:
192 LOG.trace("Reading ordered map node {}", identifier);
193 return addDataContainerChildren(Builders.orderedMapBuilder().withNodeIdentifier(identifier)).build();
195 case NodeTypes.UNKEYED_LIST:
196 LOG.trace("Read unkeyed list node {}", identifier);
197 return addDataContainerChildren(Builders.unkeyedListBuilder().withNodeIdentifier(identifier)).build();
199 case NodeTypes.UNKEYED_LIST_ITEM:
200 LOG.trace("Read unkeyed list item node {}", identifier);
201 return addDataContainerChildren(Builders.unkeyedListEntryBuilder()
202 .withNodeIdentifier(identifier)).build();
204 case NodeTypes.CONTAINER_NODE:
205 LOG.trace("Read container node {}", identifier);
206 return addDataContainerChildren(Builders.containerBuilder().withNodeIdentifier(identifier)).build();
208 case NodeTypes.LEAF_SET :
209 LOG.trace("Read leaf set node {}", identifier);
210 return addLeafSetChildren(identifier.getNodeType(),
211 Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
213 case NodeTypes.ORDERED_LEAF_SET:
214 LOG.trace("Read ordered leaf set node {}", identifier);
215 ListNodeBuilder<Object, LeafSetEntryNode<Object>> orderedLeafSetBuilder =
216 Builders.orderedLeafSetBuilder().withNodeIdentifier(identifier);
217 orderedLeafSetBuilder = addLeafSetChildren(identifier.getNodeType(), orderedLeafSetBuilder);
218 return orderedLeafSetBuilder.build();
225 private DOMSource readDOMSource() throws IOException {
226 String xml = readObject().toString();
228 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
229 factory.setNamespaceAware(true);
230 Element node = factory.newDocumentBuilder().parse(
231 new InputSource(new StringReader(xml))).getDocumentElement();
232 return new DOMSource(node);
233 } catch (SAXException | ParserConfigurationException e) {
234 throw new IOException("Error parsing XML: " + xml, e);
238 private QName readQName() throws IOException {
239 // Read in the same sequence of writing
240 String localName = readCodedString();
241 String namespace = readCodedString();
242 String revision = readCodedString();
245 if (!Strings.isNullOrEmpty(revision)) {
246 qname = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG).append(revision)
247 .append(')').append(localName).toString();
249 qname = reusableStringBuilder.append('(').append(namespace).append(')').append(localName).toString();
252 reusableStringBuilder.delete(0, reusableStringBuilder.length());
253 return QNameFactory.create(qname);
257 private String readCodedString() throws IOException {
258 byte valueType = input.readByte();
259 if (valueType == TokenTypes.IS_CODE_VALUE) {
260 return codedStringMap.get(input.readInt());
261 } else if (valueType == TokenTypes.IS_STRING_VALUE) {
262 String value = input.readUTF().intern();
263 codedStringMap.put(Integer.valueOf(codedStringMap.size()), value);
270 private Set<QName> readQNameSet() throws IOException {
271 // Read the children count
272 int count = input.readInt();
273 Set<QName> children = new HashSet<>(count);
274 for (int i = 0; i < count; i++) {
275 children.add(readQName());
280 private Map<QName, Object> readKeyValueMap() throws IOException {
281 int count = input.readInt();
282 Map<QName, Object> keyValueMap = new HashMap<>(count);
284 for (int i = 0; i < count; i++) {
285 keyValueMap.put(readQName(), readObject());
291 private Object readObject() throws IOException {
292 byte objectType = input.readByte();
293 switch (objectType) {
294 case ValueTypes.BITS_TYPE:
297 case ValueTypes.BOOL_TYPE :
298 return Boolean.valueOf(input.readBoolean());
300 case ValueTypes.BYTE_TYPE :
301 return Byte.valueOf(input.readByte());
303 case ValueTypes.INT_TYPE :
304 return Integer.valueOf(input.readInt());
306 case ValueTypes.LONG_TYPE :
307 return Long.valueOf(input.readLong());
309 case ValueTypes.QNAME_TYPE :
312 case ValueTypes.SHORT_TYPE :
313 return Short.valueOf(input.readShort());
315 case ValueTypes.STRING_TYPE :
316 return input.readUTF();
318 case ValueTypes.STRING_BYTES_TYPE:
319 return readStringBytes();
321 case ValueTypes.BIG_DECIMAL_TYPE :
322 return new BigDecimal(input.readUTF());
324 case ValueTypes.BIG_INTEGER_TYPE :
325 return new BigInteger(input.readUTF());
327 case ValueTypes.BINARY_TYPE :
328 byte[] bytes = new byte[input.readInt()];
329 input.readFully(bytes);
332 case ValueTypes.YANG_IDENTIFIER_TYPE :
333 return readYangInstanceIdentifierInternal();
340 private String readStringBytes() throws IOException {
341 byte[] bytes = new byte[input.readInt()];
342 input.readFully(bytes);
343 return new String(bytes, StandardCharsets.UTF_8);
347 public SchemaPath readSchemaPath() throws IOException {
348 readSignatureMarkerAndVersionIfNeeded();
350 final boolean absolute = input.readBoolean();
351 final int size = input.readInt();
352 final Collection<QName> qnames = new ArrayList<>(size);
353 for (int i = 0; i < size; ++i) {
354 qnames.add(readQName());
357 return SchemaPath.create(qnames, absolute);
361 public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
362 readSignatureMarkerAndVersionIfNeeded();
363 return readYangInstanceIdentifierInternal();
366 private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
367 int size = input.readInt();
369 List<PathArgument> pathArguments = new ArrayList<>(size);
371 for (int i = 0; i < size; i++) {
372 pathArguments.add(readPathArgument());
374 return YangInstanceIdentifier.create(pathArguments);
377 private Set<String> readObjSet() throws IOException {
378 int count = input.readInt();
379 Set<String> children = new HashSet<>(count);
380 for (int i = 0; i < count; i++) {
381 children.add(readCodedString());
387 public PathArgument readPathArgument() throws IOException {
389 int type = input.readByte();
393 case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
394 return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
396 case PathArgumentTypes.NODE_IDENTIFIER :
397 return new NodeIdentifier(readQName());
399 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES :
400 return new NodeIdentifierWithPredicates(readQName(), readKeyValueMap());
402 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
403 return new NodeWithValue<>(readQName(), readObject());
410 @SuppressWarnings("unchecked")
411 private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(final QName nodeType,
412 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
414 LOG.trace("Reading children of leaf set");
416 lastLeafSetQName = nodeType;
418 LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
420 while (child != null) {
421 builder.withChild(child);
422 child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
427 @SuppressWarnings({ "unchecked", "rawtypes" })
428 private NormalizedNodeContainerBuilder addDataContainerChildren(
429 final NormalizedNodeContainerBuilder builder) throws IOException {
430 LOG.trace("Reading data container (leaf nodes) nodes");
432 NormalizedNode<?, ?> child = readNormalizedNodeInternal();
434 while (child != null) {
435 builder.addChild(child);
436 child = readNormalizedNodeInternal();
442 public void readFully(final byte[] value) throws IOException {
443 readSignatureMarkerAndVersionIfNeeded();
444 input.readFully(value);
448 public void readFully(final byte[] str, final int off, final int len) throws IOException {
449 readSignatureMarkerAndVersionIfNeeded();
450 input.readFully(str, off, len);
454 public int skipBytes(final int num) throws IOException {
455 readSignatureMarkerAndVersionIfNeeded();
456 return input.skipBytes(num);
460 public boolean readBoolean() throws IOException {
461 readSignatureMarkerAndVersionIfNeeded();
462 return input.readBoolean();
466 public byte readByte() throws IOException {
467 readSignatureMarkerAndVersionIfNeeded();
468 return input.readByte();
472 public int readUnsignedByte() throws IOException {
473 readSignatureMarkerAndVersionIfNeeded();
474 return input.readUnsignedByte();
478 public short readShort() throws IOException {
479 readSignatureMarkerAndVersionIfNeeded();
480 return input.readShort();
484 public int readUnsignedShort() throws IOException {
485 readSignatureMarkerAndVersionIfNeeded();
486 return input.readUnsignedShort();
490 public char readChar() throws IOException {
491 readSignatureMarkerAndVersionIfNeeded();
492 return input.readChar();
496 public int readInt() throws IOException {
497 readSignatureMarkerAndVersionIfNeeded();
498 return input.readInt();
502 public long readLong() throws IOException {
503 readSignatureMarkerAndVersionIfNeeded();
504 return input.readLong();
508 public float readFloat() throws IOException {
509 readSignatureMarkerAndVersionIfNeeded();
510 return input.readFloat();
514 public double readDouble() throws IOException {
515 readSignatureMarkerAndVersionIfNeeded();
516 return input.readDouble();
520 public String readLine() throws IOException {
521 readSignatureMarkerAndVersionIfNeeded();
522 return input.readLine();
526 public String readUTF() throws IOException {
527 readSignatureMarkerAndVersionIfNeeded();
528 return input.readUTF();