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.HashMap;
21 import java.util.HashSet;
22 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.yang.common.QName;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
35 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
38 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
39 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
40 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
41 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.w3c.dom.Element;
45 import org.xml.sax.InputSource;
46 import org.xml.sax.SAXException;
49 * NormalizedNodeInputStreamReader reads the byte stream and constructs the normalized node including its children
50 * nodes. This process goes in recursive manner, where each NodeTypes object signifies the start of the object, except
51 * END_NODE. If a node can have children, then that node's end is calculated based on appearance of END_NODE.
53 public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput {
55 private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeInputStreamReader.class);
57 private static final String REVISION_ARG = "?revision=";
59 private final DataInput input;
61 private final Map<Integer, String> codedStringMap = new HashMap<>();
63 private QName lastLeafSetQName;
65 private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
66 Object, LeafNode<Object>> leafBuilder;
68 @SuppressWarnings("rawtypes")
69 private NormalizedNodeAttrBuilder<NodeWithValue, Object, LeafSetEntryNode<Object>> leafSetEntryBuilder;
71 private final StringBuilder reusableStringBuilder = new StringBuilder(50);
73 private boolean readSignatureMarker = true;
76 * Constructs an instance.
78 * @deprecated Use {@link NormalizedNodeInputOutput#newDataInput(DataInput)} instead.
81 public NormalizedNodeInputStreamReader(final DataInput input) {
85 NormalizedNodeInputStreamReader(final DataInput input, final boolean versionChecked) {
86 this.input = Preconditions.checkNotNull(input);
87 readSignatureMarker = !versionChecked;
91 public NormalizedNode<?, ?> readNormalizedNode() throws IOException {
92 readSignatureMarkerAndVersionIfNeeded();
93 return readNormalizedNodeInternal();
96 private void readSignatureMarkerAndVersionIfNeeded() throws IOException {
97 if (readSignatureMarker) {
98 readSignatureMarker = false;
100 final byte marker = input.readByte();
101 if (marker != TokenTypes.SIGNATURE_MARKER) {
102 throw new InvalidNormalizedNodeStreamException(String.format(
103 "Invalid signature marker: %d", marker));
106 final short version = input.readShort();
107 if (version != TokenTypes.LITHIUM_VERSION) {
108 throw new InvalidNormalizedNodeStreamException(String.format("Unhandled stream version %s", version));
113 private NormalizedNode<?, ?> readNormalizedNodeInternal() throws IOException {
114 // each node should start with a byte
115 byte nodeType = input.readByte();
117 if (nodeType == NodeTypes.END_NODE) {
118 LOG.debug("End node reached. return");
123 case NodeTypes.AUGMENTATION_NODE :
124 YangInstanceIdentifier.AugmentationIdentifier augIdentifier =
125 new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
127 LOG.debug("Reading augmentation node {} ", augIdentifier);
129 return addDataContainerChildren(Builders.augmentationBuilder()
130 .withNodeIdentifier(augIdentifier)).build();
132 case NodeTypes.LEAF_SET_ENTRY_NODE :
133 QName name = lastLeafSetQName;
138 Object value = readObject();
139 NodeWithValue<Object> leafIdentifier = new NodeWithValue<>(name, value);
141 LOG.debug("Reading leaf set entry node {}, value {}", leafIdentifier, value);
143 return leafSetEntryBuilder().withNodeIdentifier(leafIdentifier).withValue(value).build();
145 case NodeTypes.MAP_ENTRY_NODE :
146 NodeIdentifierWithPredicates entryIdentifier = new NodeIdentifierWithPredicates(
147 readQName(), readKeyValueMap());
149 LOG.debug("Reading map entry node {} ", entryIdentifier);
151 return addDataContainerChildren(Builders.mapEntryBuilder()
152 .withNodeIdentifier(entryIdentifier)).build();
155 return readNodeIdentifierDependentNode(nodeType, new NodeIdentifier(readQName()));
159 private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
160 Object, LeafNode<Object>> leafBuilder() {
161 if (leafBuilder == null) {
162 leafBuilder = Builders.leafBuilder();
168 @SuppressWarnings("rawtypes")
169 private NormalizedNodeAttrBuilder<NodeWithValue, Object,
170 LeafSetEntryNode<Object>> leafSetEntryBuilder() {
171 if (leafSetEntryBuilder == null) {
172 leafSetEntryBuilder = Builders.leafSetEntryBuilder();
175 return leafSetEntryBuilder;
178 private NormalizedNode<?, ?> readNodeIdentifierDependentNode(final byte nodeType, final NodeIdentifier identifier)
182 case NodeTypes.LEAF_NODE :
183 LOG.debug("Read leaf node {}", identifier);
184 // Read the object value
185 return leafBuilder().withNodeIdentifier(identifier).withValue(readObject()).build();
187 case NodeTypes.ANY_XML_NODE :
188 LOG.debug("Read xml node");
189 return Builders.anyXmlBuilder().withNodeIdentifier(identifier).withValue(readDOMSource()).build();
191 case NodeTypes.MAP_NODE :
192 LOG.debug("Read map node {}", identifier);
193 return addDataContainerChildren(Builders.mapBuilder().withNodeIdentifier(identifier)).build();
195 case NodeTypes.CHOICE_NODE:
196 LOG.debug("Read choice node {}", identifier);
197 return addDataContainerChildren(Builders.choiceBuilder().withNodeIdentifier(identifier)).build();
199 case NodeTypes.ORDERED_MAP_NODE:
200 LOG.debug("Reading ordered map node {}", identifier);
201 return addDataContainerChildren(Builders.orderedMapBuilder().withNodeIdentifier(identifier)).build();
203 case NodeTypes.UNKEYED_LIST:
204 LOG.debug("Read unkeyed list node {}", identifier);
205 return addDataContainerChildren(Builders.unkeyedListBuilder().withNodeIdentifier(identifier)).build();
207 case NodeTypes.UNKEYED_LIST_ITEM:
208 LOG.debug("Read unkeyed list item node {}", identifier);
209 return addDataContainerChildren(Builders.unkeyedListEntryBuilder()
210 .withNodeIdentifier(identifier)).build();
212 case NodeTypes.CONTAINER_NODE:
213 LOG.debug("Read container node {}", identifier);
214 return addDataContainerChildren(Builders.containerBuilder().withNodeIdentifier(identifier)).build();
216 case NodeTypes.LEAF_SET :
217 LOG.debug("Read leaf set node {}", identifier);
218 return addLeafSetChildren(identifier.getNodeType(),
219 Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
221 case NodeTypes.ORDERED_LEAF_SET:
222 LOG.debug("Read ordered leaf set node {}", identifier);
223 ListNodeBuilder<Object, LeafSetEntryNode<Object>> orderedLeafSetBuilder =
224 Builders.orderedLeafSetBuilder().withNodeIdentifier(identifier);
225 orderedLeafSetBuilder = addLeafSetChildren(identifier.getNodeType(), orderedLeafSetBuilder);
226 return orderedLeafSetBuilder.build();
233 private DOMSource readDOMSource() throws IOException {
234 String xml = readObject().toString();
236 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
237 factory.setNamespaceAware(true);
238 Element node = factory.newDocumentBuilder().parse(
239 new InputSource(new StringReader(xml))).getDocumentElement();
240 return new DOMSource(node);
241 } catch (SAXException | ParserConfigurationException e) {
242 throw new IOException("Error parsing XML: " + xml, e);
246 private QName readQName() throws IOException {
247 // Read in the same sequence of writing
248 String localName = readCodedString();
249 String namespace = readCodedString();
250 String revision = readCodedString();
253 if (!Strings.isNullOrEmpty(revision)) {
254 qname = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG).append(revision)
255 .append(')').append(localName).toString();
257 qname = reusableStringBuilder.append('(').append(namespace).append(')').append(localName).toString();
260 reusableStringBuilder.delete(0, reusableStringBuilder.length());
261 return QNameFactory.create(qname);
265 private String readCodedString() throws IOException {
266 byte valueType = input.readByte();
267 if (valueType == TokenTypes.IS_CODE_VALUE) {
268 return codedStringMap.get(input.readInt());
269 } else if (valueType == TokenTypes.IS_STRING_VALUE) {
270 String value = input.readUTF().intern();
271 codedStringMap.put(Integer.valueOf(codedStringMap.size()), value);
278 private Set<QName> readQNameSet() throws IOException {
279 // Read the children count
280 int count = input.readInt();
281 Set<QName> children = new HashSet<>(count);
282 for (int i = 0; i < count; i++) {
283 children.add(readQName());
288 private Map<QName, Object> readKeyValueMap() throws IOException {
289 int count = input.readInt();
290 Map<QName, Object> keyValueMap = new HashMap<>(count);
292 for (int i = 0; i < count; i++) {
293 keyValueMap.put(readQName(), readObject());
299 private Object readObject() throws IOException {
300 byte objectType = input.readByte();
301 switch (objectType) {
302 case ValueTypes.BITS_TYPE:
305 case ValueTypes.BOOL_TYPE :
306 return Boolean.valueOf(input.readBoolean());
308 case ValueTypes.BYTE_TYPE :
309 return Byte.valueOf(input.readByte());
311 case ValueTypes.INT_TYPE :
312 return Integer.valueOf(input.readInt());
314 case ValueTypes.LONG_TYPE :
315 return Long.valueOf(input.readLong());
317 case ValueTypes.QNAME_TYPE :
320 case ValueTypes.SHORT_TYPE :
321 return Short.valueOf(input.readShort());
323 case ValueTypes.STRING_TYPE :
324 return input.readUTF();
326 case ValueTypes.STRING_BYTES_TYPE:
327 return readStringBytes();
329 case ValueTypes.BIG_DECIMAL_TYPE :
330 return new BigDecimal(input.readUTF());
332 case ValueTypes.BIG_INTEGER_TYPE :
333 return new BigInteger(input.readUTF());
335 case ValueTypes.BINARY_TYPE :
336 byte[] bytes = new byte[input.readInt()];
337 input.readFully(bytes);
340 case ValueTypes.YANG_IDENTIFIER_TYPE :
341 return readYangInstanceIdentifierInternal();
348 private String readStringBytes() throws IOException {
349 byte[] bytes = new byte[input.readInt()];
350 input.readFully(bytes);
351 return new String(bytes, StandardCharsets.UTF_8);
355 public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
356 readSignatureMarkerAndVersionIfNeeded();
357 return readYangInstanceIdentifierInternal();
360 private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
361 int size = input.readInt();
363 List<PathArgument> pathArguments = new ArrayList<>(size);
365 for (int i = 0; i < size; i++) {
366 pathArguments.add(readPathArgument());
368 return YangInstanceIdentifier.create(pathArguments);
371 private Set<String> readObjSet() throws IOException {
372 int count = input.readInt();
373 Set<String> children = new HashSet<>(count);
374 for (int i = 0; i < count; i++) {
375 children.add(readCodedString());
381 public PathArgument readPathArgument() throws IOException {
383 int type = input.readByte();
387 case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
388 return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
390 case PathArgumentTypes.NODE_IDENTIFIER :
391 return new NodeIdentifier(readQName());
393 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES :
394 return new NodeIdentifierWithPredicates(readQName(), readKeyValueMap());
396 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
397 return new NodeWithValue<>(readQName(), readObject());
404 @SuppressWarnings("unchecked")
405 private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(final QName nodeType,
406 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
408 LOG.debug("Reading children of leaf set");
410 lastLeafSetQName = nodeType;
412 LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
414 while (child != null) {
415 builder.withChild(child);
416 child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
421 @SuppressWarnings({ "unchecked", "rawtypes" })
422 private NormalizedNodeContainerBuilder addDataContainerChildren(
423 final NormalizedNodeContainerBuilder builder) throws IOException {
424 LOG.debug("Reading data container (leaf nodes) nodes");
426 NormalizedNode<?, ?> child = readNormalizedNodeInternal();
428 while (child != null) {
429 builder.addChild(child);
430 child = readNormalizedNodeInternal();
436 public void readFully(final byte[] value) throws IOException {
437 readSignatureMarkerAndVersionIfNeeded();
438 input.readFully(value);
442 public void readFully(final byte[] str, final int off, final int len) throws IOException {
443 readSignatureMarkerAndVersionIfNeeded();
444 input.readFully(str, off, len);
448 public int skipBytes(final int num) throws IOException {
449 readSignatureMarkerAndVersionIfNeeded();
450 return input.skipBytes(num);
454 public boolean readBoolean() throws IOException {
455 readSignatureMarkerAndVersionIfNeeded();
456 return input.readBoolean();
460 public byte readByte() throws IOException {
461 readSignatureMarkerAndVersionIfNeeded();
462 return input.readByte();
466 public int readUnsignedByte() throws IOException {
467 readSignatureMarkerAndVersionIfNeeded();
468 return input.readUnsignedByte();
472 public short readShort() throws IOException {
473 readSignatureMarkerAndVersionIfNeeded();
474 return input.readShort();
478 public int readUnsignedShort() throws IOException {
479 readSignatureMarkerAndVersionIfNeeded();
480 return input.readUnsignedShort();
484 public char readChar() throws IOException {
485 readSignatureMarkerAndVersionIfNeeded();
486 return input.readChar();
490 public int readInt() throws IOException {
491 readSignatureMarkerAndVersionIfNeeded();
492 return input.readInt();
496 public long readLong() throws IOException {
497 readSignatureMarkerAndVersionIfNeeded();
498 return input.readLong();
502 public float readFloat() throws IOException {
503 readSignatureMarkerAndVersionIfNeeded();
504 return input.readFloat();
508 public double readDouble() throws IOException {
509 readSignatureMarkerAndVersionIfNeeded();
510 return input.readDouble();
514 public String readLine() throws IOException {
515 readSignatureMarkerAndVersionIfNeeded();
516 return input.readLine();
520 public String readUTF() throws IOException {
521 readSignatureMarkerAndVersionIfNeeded();
522 return input.readUTF();