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 nodes.
50 * This process goes in recursive manner, where each NodeTypes object signifies the start of the object, except END_NODE.
51 * 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 private NormalizedNodeAttrBuilder<NodeWithValue, Object, LeafSetEntryNode<Object>> leafSetEntryBuilder;
72 private final StringBuilder reusableStringBuilder = new StringBuilder(50);
74 private boolean readSignatureMarker = true;
77 * @deprecated Use {@link NormalizedNodeInputOutput#newDataInput(DataInput)} instead.
80 public NormalizedNodeInputStreamReader(final DataInput input) {
84 NormalizedNodeInputStreamReader(final DataInput input, final boolean versionChecked) {
85 this.input = Preconditions.checkNotNull(input);
86 readSignatureMarker = !versionChecked;
90 public NormalizedNode<?, ?> readNormalizedNode() throws IOException {
91 readSignatureMarkerAndVersionIfNeeded();
92 return readNormalizedNodeInternal();
95 private void readSignatureMarkerAndVersionIfNeeded() throws IOException {
96 if(readSignatureMarker) {
97 readSignatureMarker = false;
99 final byte marker = input.readByte();
100 if (marker != TokenTypes.SIGNATURE_MARKER) {
101 throw new InvalidNormalizedNodeStreamException(String.format(
102 "Invalid signature marker: %d", marker));
105 final short version = input.readShort();
106 if (version != TokenTypes.LITHIUM_VERSION) {
107 throw new InvalidNormalizedNodeStreamException(String.format("Unhandled stream version %s", version));
112 private NormalizedNode<?, ?> readNormalizedNodeInternal() throws IOException {
113 // each node should start with a byte
114 byte nodeType = input.readByte();
116 if(nodeType == NodeTypes.END_NODE) {
117 LOG.debug("End node reached. return");
122 case NodeTypes.AUGMENTATION_NODE :
123 YangInstanceIdentifier.AugmentationIdentifier augIdentifier =
124 new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
126 LOG.debug("Reading augmentation node {} ", augIdentifier);
128 return addDataContainerChildren(Builders.augmentationBuilder().
129 withNodeIdentifier(augIdentifier)).build();
131 case NodeTypes.LEAF_SET_ENTRY_NODE :
132 QName name = lastLeafSetQName;
137 Object value = readObject();
138 NodeWithValue<Object> leafIdentifier = new NodeWithValue<>(name, value);
140 LOG.debug("Reading leaf set entry node {}, value {}", leafIdentifier, value);
142 return leafSetEntryBuilder().withNodeIdentifier(leafIdentifier).withValue(value).build();
144 case NodeTypes.MAP_ENTRY_NODE :
145 NodeIdentifierWithPredicates entryIdentifier = new NodeIdentifierWithPredicates(
146 readQName(), readKeyValueMap());
148 LOG.debug("Reading map entry node {} ", entryIdentifier);
150 return addDataContainerChildren(Builders.mapEntryBuilder().
151 withNodeIdentifier(entryIdentifier)).build();
154 return readNodeIdentifierDependentNode(nodeType, new NodeIdentifier(readQName()));
158 private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
159 Object, LeafNode<Object>> leafBuilder() {
160 if(leafBuilder == null) {
161 leafBuilder = Builders.leafBuilder();
167 private NormalizedNodeAttrBuilder<NodeWithValue, Object,
168 LeafSetEntryNode<Object>> leafSetEntryBuilder() {
169 if(leafSetEntryBuilder == null) {
170 leafSetEntryBuilder = Builders.leafSetEntryBuilder();
173 return leafSetEntryBuilder;
176 private NormalizedNode<?, ?> readNodeIdentifierDependentNode(final byte nodeType, final NodeIdentifier identifier)
180 case NodeTypes.LEAF_NODE :
181 LOG.debug("Read leaf node {}", identifier);
182 // Read the object value
183 return leafBuilder().withNodeIdentifier(identifier).withValue(readObject()).build();
185 case NodeTypes.ANY_XML_NODE :
186 LOG.debug("Read xml node");
187 return Builders.anyXmlBuilder().withNodeIdentifier(identifier).withValue(readDOMSource()).build();
189 case NodeTypes.MAP_NODE :
190 LOG.debug("Read map node {}", identifier);
191 return addDataContainerChildren(Builders.mapBuilder().
192 withNodeIdentifier(identifier)).build();
194 case NodeTypes.CHOICE_NODE :
195 LOG.debug("Read choice node {}", identifier);
196 return addDataContainerChildren(Builders.choiceBuilder().
197 withNodeIdentifier(identifier)).build();
199 case NodeTypes.ORDERED_MAP_NODE :
200 LOG.debug("Reading ordered map node {}", identifier);
201 return addDataContainerChildren(Builders.orderedMapBuilder().
202 withNodeIdentifier(identifier)).build();
204 case NodeTypes.UNKEYED_LIST :
205 LOG.debug("Read unkeyed list node {}", identifier);
206 return addDataContainerChildren(Builders.unkeyedListBuilder().
207 withNodeIdentifier(identifier)).build();
209 case NodeTypes.UNKEYED_LIST_ITEM :
210 LOG.debug("Read unkeyed list item node {}", identifier);
211 return addDataContainerChildren(Builders.unkeyedListEntryBuilder().
212 withNodeIdentifier(identifier)).build();
214 case NodeTypes.CONTAINER_NODE :
215 LOG.debug("Read container node {}", identifier);
216 return addDataContainerChildren(Builders.containerBuilder().
217 withNodeIdentifier(identifier)).build();
219 case NodeTypes.LEAF_SET :
220 LOG.debug("Read leaf set node {}", identifier);
221 return addLeafSetChildren(identifier.getNodeType(),
222 Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
224 case NodeTypes.ORDERED_LEAF_SET:
225 LOG.debug("Read ordered leaf set node {}", identifier);
226 ListNodeBuilder<Object, LeafSetEntryNode<Object>> orderedLeafSetBuilder =
227 Builders.orderedLeafSetBuilder().withNodeIdentifier(identifier);
228 orderedLeafSetBuilder = addLeafSetChildren(identifier.getNodeType(), orderedLeafSetBuilder);
229 return orderedLeafSetBuilder.build();
236 private DOMSource readDOMSource() throws IOException {
237 String xml = readObject().toString();
239 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
240 factory.setNamespaceAware(true);
241 Element node = factory.newDocumentBuilder().parse(
242 new InputSource(new StringReader(xml))).getDocumentElement();
243 return new DOMSource(node);
244 } catch (SAXException | ParserConfigurationException e) {
245 throw new IOException("Error parsing XML: " + xml, e);
249 private QName readQName() throws IOException {
250 // Read in the same sequence of writing
251 String localName = readCodedString();
252 String namespace = readCodedString();
253 String revision = readCodedString();
256 if(!Strings.isNullOrEmpty(revision)) {
257 qName = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG).
258 append(revision).append(')').append(localName).toString();
260 qName = reusableStringBuilder.append('(').append(namespace).append(')').
261 append(localName).toString();
264 reusableStringBuilder.delete(0, reusableStringBuilder.length());
265 return QNameFactory.create(qName);
269 private String readCodedString() throws IOException {
270 byte valueType = input.readByte();
271 if(valueType == TokenTypes.IS_CODE_VALUE) {
272 return codedStringMap.get(input.readInt());
273 } else if(valueType == TokenTypes.IS_STRING_VALUE) {
274 String value = input.readUTF().intern();
275 codedStringMap.put(Integer.valueOf(codedStringMap.size()), value);
282 private Set<QName> readQNameSet() throws IOException{
283 // Read the children count
284 int count = input.readInt();
285 Set<QName> children = new HashSet<>(count);
286 for(int i = 0; i < count; i++) {
287 children.add(readQName());
292 private Map<QName, Object> readKeyValueMap() throws IOException {
293 int count = input.readInt();
294 Map<QName, Object> keyValueMap = new HashMap<>(count);
296 for(int i = 0; i < count; i++) {
297 keyValueMap.put(readQName(), readObject());
303 private Object readObject() throws IOException {
304 byte objectType = input.readByte();
306 case ValueTypes.BITS_TYPE:
309 case ValueTypes.BOOL_TYPE :
310 return Boolean.valueOf(input.readBoolean());
312 case ValueTypes.BYTE_TYPE :
313 return Byte.valueOf(input.readByte());
315 case ValueTypes.INT_TYPE :
316 return Integer.valueOf(input.readInt());
318 case ValueTypes.LONG_TYPE :
319 return Long.valueOf(input.readLong());
321 case ValueTypes.QNAME_TYPE :
324 case ValueTypes.SHORT_TYPE :
325 return Short.valueOf(input.readShort());
327 case ValueTypes.STRING_TYPE :
328 return input.readUTF();
330 case ValueTypes.STRING_BYTES_TYPE:
331 return readStringBytes();
333 case ValueTypes.BIG_DECIMAL_TYPE :
334 return new BigDecimal(input.readUTF());
336 case ValueTypes.BIG_INTEGER_TYPE :
337 return new BigInteger(input.readUTF());
339 case ValueTypes.BINARY_TYPE :
340 byte[] bytes = new byte[input.readInt()];
341 input.readFully(bytes);
344 case ValueTypes.YANG_IDENTIFIER_TYPE :
345 return readYangInstanceIdentifierInternal();
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 YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
360 readSignatureMarkerAndVersionIfNeeded();
361 return readYangInstanceIdentifierInternal();
364 private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
365 int size = input.readInt();
367 List<PathArgument> pathArguments = new ArrayList<>(size);
369 for(int i = 0; i < size; i++) {
370 pathArguments.add(readPathArgument());
372 return YangInstanceIdentifier.create(pathArguments);
375 private Set<String> readObjSet() throws IOException {
376 int count = input.readInt();
377 Set<String> children = new HashSet<>(count);
378 for(int i = 0; i < count; i++) {
379 children.add(readCodedString());
385 public PathArgument readPathArgument() throws IOException {
387 int type = input.readByte();
391 case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
392 return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
394 case PathArgumentTypes.NODE_IDENTIFIER :
395 return new NodeIdentifier(readQName());
397 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES :
398 return new NodeIdentifierWithPredicates(readQName(), readKeyValueMap());
400 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
401 return new NodeWithValue<>(readQName(), readObject());
408 @SuppressWarnings("unchecked")
409 private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(final QName nodeType,
410 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
412 LOG.debug("Reading children of leaf set");
414 lastLeafSetQName = nodeType;
416 LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
418 while(child != null) {
419 builder.withChild(child);
420 child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
425 @SuppressWarnings({ "unchecked", "rawtypes" })
426 private NormalizedNodeContainerBuilder addDataContainerChildren(
427 final NormalizedNodeContainerBuilder builder) throws IOException {
428 LOG.debug("Reading data container (leaf nodes) nodes");
430 NormalizedNode<?, ?> child = readNormalizedNodeInternal();
432 while(child != null) {
433 builder.addChild(child);
434 child = readNormalizedNodeInternal();
440 public void readFully(final byte[] b) throws IOException {
441 readSignatureMarkerAndVersionIfNeeded();
446 public void readFully(final byte[] b, final int off, final int len) throws IOException {
447 readSignatureMarkerAndVersionIfNeeded();
448 input.readFully(b, off, len);
452 public int skipBytes(final int n) throws IOException {
453 readSignatureMarkerAndVersionIfNeeded();
454 return input.skipBytes(n);
458 public boolean readBoolean() throws IOException {
459 readSignatureMarkerAndVersionIfNeeded();
460 return input.readBoolean();
464 public byte readByte() throws IOException {
465 readSignatureMarkerAndVersionIfNeeded();
466 return input.readByte();
470 public int readUnsignedByte() throws IOException {
471 readSignatureMarkerAndVersionIfNeeded();
472 return input.readUnsignedByte();
476 public short readShort() throws IOException {
477 readSignatureMarkerAndVersionIfNeeded();
478 return input.readShort();
482 public int readUnsignedShort() throws IOException {
483 readSignatureMarkerAndVersionIfNeeded();
484 return input.readUnsignedShort();
488 public char readChar() throws IOException {
489 readSignatureMarkerAndVersionIfNeeded();
490 return input.readChar();
494 public int readInt() throws IOException {
495 readSignatureMarkerAndVersionIfNeeded();
496 return input.readInt();
500 public long readLong() throws IOException {
501 readSignatureMarkerAndVersionIfNeeded();
502 return input.readLong();
506 public float readFloat() throws IOException {
507 readSignatureMarkerAndVersionIfNeeded();
508 return input.readFloat();
512 public double readDouble() throws IOException {
513 readSignatureMarkerAndVersionIfNeeded();
514 return input.readDouble();
518 public String readLine() throws IOException {
519 readSignatureMarkerAndVersionIfNeeded();
520 return input.readLine();
524 public String readUTF() throws IOException {
525 readSignatureMarkerAndVersionIfNeeded();
526 return input.readUTF();