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.DataInputStream;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.math.BigDecimal;
18 import java.math.BigInteger;
19 import java.nio.charset.StandardCharsets;
20 import java.util.ArrayList;
21 import java.util.HashMap;
22 import java.util.HashSet;
23 import java.util.List;
26 import javax.xml.transform.dom.DOMSource;
27 import org.opendaylight.controller.cluster.datastore.node.utils.QNameFactory;
28 import org.opendaylight.yangtools.yang.common.QName;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
34 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
37 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
38 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
39 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
40 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
45 * NormalizedNodeInputStreamReader reads the byte stream and constructs the normalized node including its children nodes.
46 * This process goes in recursive manner, where each NodeTypes object signifies the start of the object, except END_NODE.
47 * If a node can have children, then that node's end is calculated based on appearance of END_NODE.
51 public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput, NormalizedNodeStreamReader {
53 private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeInputStreamReader.class);
55 private static final String REVISION_ARG = "?revision=";
57 private final DataInput input;
59 private final Map<Integer, String> codedStringMap = new HashMap<>();
61 private QName lastLeafSetQName;
63 private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
64 Object, LeafNode<Object>> leafBuilder;
66 private NormalizedNodeAttrBuilder<NodeWithValue, Object,
67 LeafSetEntryNode<Object>> leafSetEntryBuilder;
69 private final StringBuilder reusableStringBuilder = new StringBuilder(50);
71 private boolean readSignatureMarker = true;
74 * @deprecated Use {@link #NormalizedNodeInputStreamReader(DataInput)} instead.
77 public NormalizedNodeInputStreamReader(final InputStream stream) throws IOException {
78 Preconditions.checkNotNull(stream);
79 input = new DataInputStream(stream);
83 * @deprecated Use {@link NormalizedNodeInputOutput#newDataInput(DataInput)} instead.
86 public NormalizedNodeInputStreamReader(final DataInput input) {
87 this.input = Preconditions.checkNotNull(input);
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 Object value = readObject();
134 NodeWithValue leafIdentifier = new NodeWithValue(lastLeafSetQName, value);
136 LOG.debug("Reading leaf set entry node {}, value {}", leafIdentifier, value);
138 return leafSetEntryBuilder().withNodeIdentifier(leafIdentifier).withValue(value).build();
140 case NodeTypes.MAP_ENTRY_NODE :
141 NodeIdentifierWithPredicates entryIdentifier = new NodeIdentifierWithPredicates(
142 readQName(), readKeyValueMap());
144 LOG.debug("Reading map entry node {} ", entryIdentifier);
146 return addDataContainerChildren(Builders.mapEntryBuilder().
147 withNodeIdentifier(entryIdentifier)).build();
150 return readNodeIdentifierDependentNode(nodeType, new NodeIdentifier(readQName()));
154 private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
155 Object, LeafNode<Object>> leafBuilder() {
156 if(leafBuilder == null) {
157 leafBuilder = Builders.leafBuilder();
163 private NormalizedNodeAttrBuilder<NodeWithValue, Object,
164 LeafSetEntryNode<Object>> leafSetEntryBuilder() {
165 if(leafSetEntryBuilder == null) {
166 leafSetEntryBuilder = Builders.leafSetEntryBuilder();
169 return leafSetEntryBuilder;
172 private NormalizedNode<?, ?> readNodeIdentifierDependentNode(final byte nodeType, final NodeIdentifier identifier)
176 case NodeTypes.LEAF_NODE :
177 LOG.debug("Read leaf node {}", identifier);
178 // Read the object value
179 return leafBuilder().withNodeIdentifier(identifier).withValue(readObject()).build();
181 case NodeTypes.ANY_XML_NODE :
182 LOG.debug("Read xml node");
183 return Builders.anyXmlBuilder().withValue((DOMSource) readObject()).build();
185 case NodeTypes.MAP_NODE :
186 LOG.debug("Read map node {}", identifier);
187 return addDataContainerChildren(Builders.mapBuilder().
188 withNodeIdentifier(identifier)).build();
190 case NodeTypes.CHOICE_NODE :
191 LOG.debug("Read choice node {}", identifier);
192 return addDataContainerChildren(Builders.choiceBuilder().
193 withNodeIdentifier(identifier)).build();
195 case NodeTypes.ORDERED_MAP_NODE :
196 LOG.debug("Reading ordered map node {}", identifier);
197 return addDataContainerChildren(Builders.orderedMapBuilder().
198 withNodeIdentifier(identifier)).build();
200 case NodeTypes.UNKEYED_LIST :
201 LOG.debug("Read unkeyed list node {}", identifier);
202 return addDataContainerChildren(Builders.unkeyedListBuilder().
203 withNodeIdentifier(identifier)).build();
205 case NodeTypes.UNKEYED_LIST_ITEM :
206 LOG.debug("Read unkeyed list item node {}", identifier);
207 return addDataContainerChildren(Builders.unkeyedListEntryBuilder().
208 withNodeIdentifier(identifier)).build();
210 case NodeTypes.CONTAINER_NODE :
211 LOG.debug("Read container node {}", identifier);
212 return addDataContainerChildren(Builders.containerBuilder().
213 withNodeIdentifier(identifier)).build();
215 case NodeTypes.LEAF_SET :
216 LOG.debug("Read leaf set node {}", identifier);
217 return addLeafSetChildren(identifier.getNodeType(),
218 Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
225 private QName readQName() throws IOException {
226 // Read in the same sequence of writing
227 String localName = readCodedString();
228 String namespace = readCodedString();
229 String revision = readCodedString();
232 if(!Strings.isNullOrEmpty(revision)) {
233 qName = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG).
234 append(revision).append(')').append(localName).toString();
236 qName = reusableStringBuilder.append('(').append(namespace).append(')').
237 append(localName).toString();
240 reusableStringBuilder.delete(0, reusableStringBuilder.length());
241 return QNameFactory.create(qName);
245 private String readCodedString() throws IOException {
246 byte valueType = input.readByte();
247 if(valueType == TokenTypes.IS_CODE_VALUE) {
248 return codedStringMap.get(input.readInt());
249 } else if(valueType == TokenTypes.IS_STRING_VALUE) {
250 String value = input.readUTF().intern();
251 codedStringMap.put(Integer.valueOf(codedStringMap.size()), value);
258 private Set<QName> readQNameSet() throws IOException{
259 // Read the children count
260 int count = input.readInt();
261 Set<QName> children = new HashSet<>(count);
262 for(int i = 0; i < count; i++) {
263 children.add(readQName());
268 private Map<QName, Object> readKeyValueMap() throws IOException {
269 int count = input.readInt();
270 Map<QName, Object> keyValueMap = new HashMap<>(count);
272 for(int i = 0; i < count; i++) {
273 keyValueMap.put(readQName(), readObject());
279 private Object readObject() throws IOException {
280 byte objectType = input.readByte();
282 case ValueTypes.BITS_TYPE:
285 case ValueTypes.BOOL_TYPE :
286 return Boolean.valueOf(input.readBoolean());
288 case ValueTypes.BYTE_TYPE :
289 return Byte.valueOf(input.readByte());
291 case ValueTypes.INT_TYPE :
292 return Integer.valueOf(input.readInt());
294 case ValueTypes.LONG_TYPE :
295 return Long.valueOf(input.readLong());
297 case ValueTypes.QNAME_TYPE :
300 case ValueTypes.SHORT_TYPE :
301 return Short.valueOf(input.readShort());
303 case ValueTypes.STRING_TYPE :
304 return input.readUTF();
306 case ValueTypes.STRING_BYTES_TYPE:
307 return readStringBytes();
309 case ValueTypes.BIG_DECIMAL_TYPE :
310 return new BigDecimal(input.readUTF());
312 case ValueTypes.BIG_INTEGER_TYPE :
313 return new BigInteger(input.readUTF());
315 case ValueTypes.BINARY_TYPE :
316 byte[] bytes = new byte[input.readInt()];
317 input.readFully(bytes);
320 case ValueTypes.YANG_IDENTIFIER_TYPE :
321 return readYangInstanceIdentifierInternal();
328 private String readStringBytes() throws IOException {
329 byte[] bytes = new byte[input.readInt()];
330 input.readFully(bytes);
331 return new String(bytes, StandardCharsets.UTF_8);
335 public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
336 readSignatureMarkerAndVersionIfNeeded();
337 return readYangInstanceIdentifierInternal();
340 private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
341 int size = input.readInt();
343 List<PathArgument> pathArguments = new ArrayList<>(size);
345 for(int i = 0; i < size; i++) {
346 pathArguments.add(readPathArgument());
348 return YangInstanceIdentifier.create(pathArguments);
351 private Set<String> readObjSet() throws IOException {
352 int count = input.readInt();
353 Set<String> children = new HashSet<>(count);
354 for(int i = 0; i < count; i++) {
355 children.add(readCodedString());
361 public PathArgument readPathArgument() throws IOException {
363 int type = input.readByte();
367 case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
368 return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
370 case PathArgumentTypes.NODE_IDENTIFIER :
371 return new NodeIdentifier(readQName());
373 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES :
374 return new NodeIdentifierWithPredicates(readQName(), readKeyValueMap());
376 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
377 return new NodeWithValue(readQName(), readObject());
384 @SuppressWarnings("unchecked")
385 private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(final QName nodeType,
386 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
388 LOG.debug("Reading children of leaf set");
390 lastLeafSetQName = nodeType;
392 LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
394 while(child != null) {
395 builder.withChild(child);
396 child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
401 @SuppressWarnings({ "unchecked", "rawtypes" })
402 private NormalizedNodeContainerBuilder addDataContainerChildren(
403 final NormalizedNodeContainerBuilder builder) throws IOException {
404 LOG.debug("Reading data container (leaf nodes) nodes");
406 NormalizedNode<?, ?> child = readNormalizedNodeInternal();
408 while(child != null) {
409 builder.addChild(child);
410 child = readNormalizedNodeInternal();
416 public void readFully(byte[] b) throws IOException {
417 readSignatureMarkerAndVersionIfNeeded();
422 public void readFully(byte[] b, int off, int len) throws IOException {
423 readSignatureMarkerAndVersionIfNeeded();
424 input.readFully(b, off, len);
428 public int skipBytes(int n) throws IOException {
429 readSignatureMarkerAndVersionIfNeeded();
430 return input.skipBytes(n);
434 public boolean readBoolean() throws IOException {
435 readSignatureMarkerAndVersionIfNeeded();
436 return input.readBoolean();
440 public byte readByte() throws IOException {
441 readSignatureMarkerAndVersionIfNeeded();
442 return input.readByte();
446 public int readUnsignedByte() throws IOException {
447 readSignatureMarkerAndVersionIfNeeded();
448 return input.readUnsignedByte();
452 public short readShort() throws IOException {
453 readSignatureMarkerAndVersionIfNeeded();
454 return input.readShort();
458 public int readUnsignedShort() throws IOException {
459 readSignatureMarkerAndVersionIfNeeded();
460 return input.readUnsignedShort();
464 public char readChar() throws IOException {
465 readSignatureMarkerAndVersionIfNeeded();
466 return input.readChar();
470 public int readInt() throws IOException {
471 readSignatureMarkerAndVersionIfNeeded();
472 return input.readInt();
476 public long readLong() throws IOException {
477 readSignatureMarkerAndVersionIfNeeded();
478 return input.readLong();
482 public float readFloat() throws IOException {
483 readSignatureMarkerAndVersionIfNeeded();
484 return input.readFloat();
488 public double readDouble() throws IOException {
489 readSignatureMarkerAndVersionIfNeeded();
490 return input.readDouble();
494 public String readLine() throws IOException {
495 readSignatureMarkerAndVersionIfNeeded();
496 return input.readLine();
500 public String readUTF() throws IOException {
501 readSignatureMarkerAndVersionIfNeeded();
502 return input.readUTF();