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 this((DataInput) new DataInputStream(Preconditions.checkNotNull(stream)));
82 * @deprecated Use {@link NormalizedNodeInputOutput#newDataInput(DataInput)} instead.
85 public NormalizedNodeInputStreamReader(final DataInput input) {
89 NormalizedNodeInputStreamReader(final DataInput input, final boolean versionChecked) {
90 this.input = Preconditions.checkNotNull(input);
91 readSignatureMarker = !versionChecked;
95 public NormalizedNode<?, ?> readNormalizedNode() throws IOException {
96 readSignatureMarkerAndVersionIfNeeded();
97 return readNormalizedNodeInternal();
100 private void readSignatureMarkerAndVersionIfNeeded() throws IOException {
101 if(readSignatureMarker) {
102 readSignatureMarker = false;
104 final byte marker = input.readByte();
105 if (marker != TokenTypes.SIGNATURE_MARKER) {
106 throw new InvalidNormalizedNodeStreamException(String.format(
107 "Invalid signature marker: %d", marker));
110 final short version = input.readShort();
111 if (version != TokenTypes.LITHIUM_VERSION) {
112 throw new InvalidNormalizedNodeStreamException(String.format("Unhandled stream version %s", version));
117 private NormalizedNode<?, ?> readNormalizedNodeInternal() throws IOException {
118 // each node should start with a byte
119 byte nodeType = input.readByte();
121 if(nodeType == NodeTypes.END_NODE) {
122 LOG.debug("End node reached. return");
127 case NodeTypes.AUGMENTATION_NODE :
128 YangInstanceIdentifier.AugmentationIdentifier augIdentifier =
129 new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
131 LOG.debug("Reading augmentation node {} ", augIdentifier);
133 return addDataContainerChildren(Builders.augmentationBuilder().
134 withNodeIdentifier(augIdentifier)).build();
136 case NodeTypes.LEAF_SET_ENTRY_NODE :
137 Object value = readObject();
138 NodeWithValue leafIdentifier = new NodeWithValue(lastLeafSetQName, 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().withValue((DOMSource) readObject()).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 leaf set node");
226 ListNodeBuilder<Object, LeafSetEntryNode<Object>> orderedLeafSetBuilder =
227 Builders.orderedLeafSetBuilder().withNodeIdentifier(identifier);
228 orderedLeafSetBuilder = addLeafSetChildren(identifier.getNodeType(), orderedLeafSetBuilder);
229 return orderedLeafSetBuilder.build();
236 private QName readQName() throws IOException {
237 // Read in the same sequence of writing
238 String localName = readCodedString();
239 String namespace = readCodedString();
240 String revision = readCodedString();
243 if(!Strings.isNullOrEmpty(revision)) {
244 qName = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG).
245 append(revision).append(')').append(localName).toString();
247 qName = reusableStringBuilder.append('(').append(namespace).append(')').
248 append(localName).toString();
251 reusableStringBuilder.delete(0, reusableStringBuilder.length());
252 return QNameFactory.create(qName);
256 private String readCodedString() throws IOException {
257 byte valueType = input.readByte();
258 if(valueType == TokenTypes.IS_CODE_VALUE) {
259 return codedStringMap.get(input.readInt());
260 } else if(valueType == TokenTypes.IS_STRING_VALUE) {
261 String value = input.readUTF().intern();
262 codedStringMap.put(Integer.valueOf(codedStringMap.size()), value);
269 private Set<QName> readQNameSet() throws IOException{
270 // Read the children count
271 int count = input.readInt();
272 Set<QName> children = new HashSet<>(count);
273 for(int i = 0; i < count; i++) {
274 children.add(readQName());
279 private Map<QName, Object> readKeyValueMap() throws IOException {
280 int count = input.readInt();
281 Map<QName, Object> keyValueMap = new HashMap<>(count);
283 for(int i = 0; i < count; i++) {
284 keyValueMap.put(readQName(), readObject());
290 private Object readObject() throws IOException {
291 byte objectType = input.readByte();
293 case ValueTypes.BITS_TYPE:
296 case ValueTypes.BOOL_TYPE :
297 return Boolean.valueOf(input.readBoolean());
299 case ValueTypes.BYTE_TYPE :
300 return Byte.valueOf(input.readByte());
302 case ValueTypes.INT_TYPE :
303 return Integer.valueOf(input.readInt());
305 case ValueTypes.LONG_TYPE :
306 return Long.valueOf(input.readLong());
308 case ValueTypes.QNAME_TYPE :
311 case ValueTypes.SHORT_TYPE :
312 return Short.valueOf(input.readShort());
314 case ValueTypes.STRING_TYPE :
315 return input.readUTF();
317 case ValueTypes.STRING_BYTES_TYPE:
318 return readStringBytes();
320 case ValueTypes.BIG_DECIMAL_TYPE :
321 return new BigDecimal(input.readUTF());
323 case ValueTypes.BIG_INTEGER_TYPE :
324 return new BigInteger(input.readUTF());
326 case ValueTypes.BINARY_TYPE :
327 byte[] bytes = new byte[input.readInt()];
328 input.readFully(bytes);
331 case ValueTypes.YANG_IDENTIFIER_TYPE :
332 return readYangInstanceIdentifierInternal();
339 private String readStringBytes() throws IOException {
340 byte[] bytes = new byte[input.readInt()];
341 input.readFully(bytes);
342 return new String(bytes, StandardCharsets.UTF_8);
346 public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
347 readSignatureMarkerAndVersionIfNeeded();
348 return readYangInstanceIdentifierInternal();
351 private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
352 int size = input.readInt();
354 List<PathArgument> pathArguments = new ArrayList<>(size);
356 for(int i = 0; i < size; i++) {
357 pathArguments.add(readPathArgument());
359 return YangInstanceIdentifier.create(pathArguments);
362 private Set<String> readObjSet() throws IOException {
363 int count = input.readInt();
364 Set<String> children = new HashSet<>(count);
365 for(int i = 0; i < count; i++) {
366 children.add(readCodedString());
372 public PathArgument readPathArgument() throws IOException {
374 int type = input.readByte();
378 case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
379 return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
381 case PathArgumentTypes.NODE_IDENTIFIER :
382 return new NodeIdentifier(readQName());
384 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES :
385 return new NodeIdentifierWithPredicates(readQName(), readKeyValueMap());
387 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
388 return new NodeWithValue(readQName(), readObject());
395 @SuppressWarnings("unchecked")
396 private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(final QName nodeType,
397 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
399 LOG.debug("Reading children of leaf set");
401 lastLeafSetQName = nodeType;
403 LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
405 while(child != null) {
406 builder.withChild(child);
407 child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
412 @SuppressWarnings({ "unchecked", "rawtypes" })
413 private NormalizedNodeContainerBuilder addDataContainerChildren(
414 final NormalizedNodeContainerBuilder builder) throws IOException {
415 LOG.debug("Reading data container (leaf nodes) nodes");
417 NormalizedNode<?, ?> child = readNormalizedNodeInternal();
419 while(child != null) {
420 builder.addChild(child);
421 child = readNormalizedNodeInternal();
427 public void readFully(final byte[] b) throws IOException {
428 readSignatureMarkerAndVersionIfNeeded();
433 public void readFully(final byte[] b, final int off, final int len) throws IOException {
434 readSignatureMarkerAndVersionIfNeeded();
435 input.readFully(b, off, len);
439 public int skipBytes(final int n) throws IOException {
440 readSignatureMarkerAndVersionIfNeeded();
441 return input.skipBytes(n);
445 public boolean readBoolean() throws IOException {
446 readSignatureMarkerAndVersionIfNeeded();
447 return input.readBoolean();
451 public byte readByte() throws IOException {
452 readSignatureMarkerAndVersionIfNeeded();
453 return input.readByte();
457 public int readUnsignedByte() throws IOException {
458 readSignatureMarkerAndVersionIfNeeded();
459 return input.readUnsignedByte();
463 public short readShort() throws IOException {
464 readSignatureMarkerAndVersionIfNeeded();
465 return input.readShort();
469 public int readUnsignedShort() throws IOException {
470 readSignatureMarkerAndVersionIfNeeded();
471 return input.readUnsignedShort();
475 public char readChar() throws IOException {
476 readSignatureMarkerAndVersionIfNeeded();
477 return input.readChar();
481 public int readInt() throws IOException {
482 readSignatureMarkerAndVersionIfNeeded();
483 return input.readInt();
487 public long readLong() throws IOException {
488 readSignatureMarkerAndVersionIfNeeded();
489 return input.readLong();
493 public float readFloat() throws IOException {
494 readSignatureMarkerAndVersionIfNeeded();
495 return input.readFloat();
499 public double readDouble() throws IOException {
500 readSignatureMarkerAndVersionIfNeeded();
501 return input.readDouble();
505 public String readLine() throws IOException {
506 readSignatureMarkerAndVersionIfNeeded();
507 return input.readLine();
511 public String readUTF() throws IOException {
512 readSignatureMarkerAndVersionIfNeeded();
513 return input.readUTF();