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.math.BigDecimal;
16 import java.math.BigInteger;
17 import java.nio.charset.StandardCharsets;
18 import java.util.ArrayList;
19 import java.util.HashMap;
20 import java.util.HashSet;
21 import java.util.List;
24 import javax.xml.transform.dom.DOMSource;
25 import org.opendaylight.controller.cluster.datastore.node.utils.QNameFactory;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
32 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
35 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
36 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
37 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
38 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
43 * NormalizedNodeInputStreamReader reads the byte stream and constructs the normalized node including its children nodes.
44 * This process goes in recursive manner, where each NodeTypes object signifies the start of the object, except END_NODE.
45 * If a node can have children, then that node's end is calculated based on appearance of END_NODE.
49 public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput {
51 private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeInputStreamReader.class);
53 private static final String REVISION_ARG = "?revision=";
55 private final DataInput input;
57 private final Map<Integer, String> codedStringMap = new HashMap<>();
59 private QName lastLeafSetQName;
61 private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
62 Object, LeafNode<Object>> leafBuilder;
64 private NormalizedNodeAttrBuilder<NodeWithValue, Object, LeafSetEntryNode<Object>> leafSetEntryBuilder;
66 private final StringBuilder reusableStringBuilder = new StringBuilder(50);
68 private boolean readSignatureMarker = true;
71 * @deprecated Use {@link NormalizedNodeInputOutput#newDataInput(DataInput)} instead.
74 public NormalizedNodeInputStreamReader(final DataInput input) {
78 NormalizedNodeInputStreamReader(final DataInput input, final boolean versionChecked) {
79 this.input = Preconditions.checkNotNull(input);
80 readSignatureMarker = !versionChecked;
84 public NormalizedNode<?, ?> readNormalizedNode() throws IOException {
85 readSignatureMarkerAndVersionIfNeeded();
86 return readNormalizedNodeInternal();
89 private void readSignatureMarkerAndVersionIfNeeded() throws IOException {
90 if(readSignatureMarker) {
91 readSignatureMarker = false;
93 final byte marker = input.readByte();
94 if (marker != TokenTypes.SIGNATURE_MARKER) {
95 throw new InvalidNormalizedNodeStreamException(String.format(
96 "Invalid signature marker: %d", marker));
99 final short version = input.readShort();
100 if (version != TokenTypes.LITHIUM_VERSION) {
101 throw new InvalidNormalizedNodeStreamException(String.format("Unhandled stream version %s", version));
106 private NormalizedNode<?, ?> readNormalizedNodeInternal() throws IOException {
107 // each node should start with a byte
108 byte nodeType = input.readByte();
110 if(nodeType == NodeTypes.END_NODE) {
111 LOG.debug("End node reached. return");
116 case NodeTypes.AUGMENTATION_NODE :
117 YangInstanceIdentifier.AugmentationIdentifier augIdentifier =
118 new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
120 LOG.debug("Reading augmentation node {} ", augIdentifier);
122 return addDataContainerChildren(Builders.augmentationBuilder().
123 withNodeIdentifier(augIdentifier)).build();
125 case NodeTypes.LEAF_SET_ENTRY_NODE :
126 QName name = lastLeafSetQName;
131 Object value = readObject();
132 NodeWithValue<Object> leafIdentifier = new NodeWithValue<>(name, value);
134 LOG.debug("Reading leaf set entry node {}, value {}", leafIdentifier, value);
136 return leafSetEntryBuilder().withNodeIdentifier(leafIdentifier).withValue(value).build();
138 case NodeTypes.MAP_ENTRY_NODE :
139 NodeIdentifierWithPredicates entryIdentifier = new NodeIdentifierWithPredicates(
140 readQName(), readKeyValueMap());
142 LOG.debug("Reading map entry node {} ", entryIdentifier);
144 return addDataContainerChildren(Builders.mapEntryBuilder().
145 withNodeIdentifier(entryIdentifier)).build();
148 return readNodeIdentifierDependentNode(nodeType, new NodeIdentifier(readQName()));
152 private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
153 Object, LeafNode<Object>> leafBuilder() {
154 if(leafBuilder == null) {
155 leafBuilder = Builders.leafBuilder();
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.debug("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.debug("Read xml node");
181 return Builders.anyXmlBuilder().withValue((DOMSource) readObject()).build();
183 case NodeTypes.MAP_NODE :
184 LOG.debug("Read map node {}", identifier);
185 return addDataContainerChildren(Builders.mapBuilder().
186 withNodeIdentifier(identifier)).build();
188 case NodeTypes.CHOICE_NODE :
189 LOG.debug("Read choice node {}", identifier);
190 return addDataContainerChildren(Builders.choiceBuilder().
191 withNodeIdentifier(identifier)).build();
193 case NodeTypes.ORDERED_MAP_NODE :
194 LOG.debug("Reading ordered map node {}", identifier);
195 return addDataContainerChildren(Builders.orderedMapBuilder().
196 withNodeIdentifier(identifier)).build();
198 case NodeTypes.UNKEYED_LIST :
199 LOG.debug("Read unkeyed list node {}", identifier);
200 return addDataContainerChildren(Builders.unkeyedListBuilder().
201 withNodeIdentifier(identifier)).build();
203 case NodeTypes.UNKEYED_LIST_ITEM :
204 LOG.debug("Read unkeyed list item node {}", identifier);
205 return addDataContainerChildren(Builders.unkeyedListEntryBuilder().
206 withNodeIdentifier(identifier)).build();
208 case NodeTypes.CONTAINER_NODE :
209 LOG.debug("Read container node {}", identifier);
210 return addDataContainerChildren(Builders.containerBuilder().
211 withNodeIdentifier(identifier)).build();
213 case NodeTypes.LEAF_SET :
214 LOG.debug("Read leaf set node {}", identifier);
215 return addLeafSetChildren(identifier.getNodeType(),
216 Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
218 case NodeTypes.ORDERED_LEAF_SET:
219 LOG.debug("Read ordered leaf set node {}", identifier);
220 ListNodeBuilder<Object, LeafSetEntryNode<Object>> orderedLeafSetBuilder =
221 Builders.orderedLeafSetBuilder().withNodeIdentifier(identifier);
222 orderedLeafSetBuilder = addLeafSetChildren(identifier.getNodeType(), orderedLeafSetBuilder);
223 return orderedLeafSetBuilder.build();
230 private QName readQName() throws IOException {
231 // Read in the same sequence of writing
232 String localName = readCodedString();
233 String namespace = readCodedString();
234 String revision = readCodedString();
237 if(!Strings.isNullOrEmpty(revision)) {
238 qName = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG).
239 append(revision).append(')').append(localName).toString();
241 qName = reusableStringBuilder.append('(').append(namespace).append(')').
242 append(localName).toString();
245 reusableStringBuilder.delete(0, reusableStringBuilder.length());
246 return QNameFactory.create(qName);
250 private String readCodedString() throws IOException {
251 byte valueType = input.readByte();
252 if(valueType == TokenTypes.IS_CODE_VALUE) {
253 return codedStringMap.get(input.readInt());
254 } else if(valueType == TokenTypes.IS_STRING_VALUE) {
255 String value = input.readUTF().intern();
256 codedStringMap.put(Integer.valueOf(codedStringMap.size()), value);
263 private Set<QName> readQNameSet() throws IOException{
264 // Read the children count
265 int count = input.readInt();
266 Set<QName> children = new HashSet<>(count);
267 for(int i = 0; i < count; i++) {
268 children.add(readQName());
273 private Map<QName, Object> readKeyValueMap() throws IOException {
274 int count = input.readInt();
275 Map<QName, Object> keyValueMap = new HashMap<>(count);
277 for(int i = 0; i < count; i++) {
278 keyValueMap.put(readQName(), readObject());
284 private Object readObject() throws IOException {
285 byte objectType = input.readByte();
287 case ValueTypes.BITS_TYPE:
290 case ValueTypes.BOOL_TYPE :
291 return Boolean.valueOf(input.readBoolean());
293 case ValueTypes.BYTE_TYPE :
294 return Byte.valueOf(input.readByte());
296 case ValueTypes.INT_TYPE :
297 return Integer.valueOf(input.readInt());
299 case ValueTypes.LONG_TYPE :
300 return Long.valueOf(input.readLong());
302 case ValueTypes.QNAME_TYPE :
305 case ValueTypes.SHORT_TYPE :
306 return Short.valueOf(input.readShort());
308 case ValueTypes.STRING_TYPE :
309 return input.readUTF();
311 case ValueTypes.STRING_BYTES_TYPE:
312 return readStringBytes();
314 case ValueTypes.BIG_DECIMAL_TYPE :
315 return new BigDecimal(input.readUTF());
317 case ValueTypes.BIG_INTEGER_TYPE :
318 return new BigInteger(input.readUTF());
320 case ValueTypes.BINARY_TYPE :
321 byte[] bytes = new byte[input.readInt()];
322 input.readFully(bytes);
325 case ValueTypes.YANG_IDENTIFIER_TYPE :
326 return readYangInstanceIdentifierInternal();
333 private String readStringBytes() throws IOException {
334 byte[] bytes = new byte[input.readInt()];
335 input.readFully(bytes);
336 return new String(bytes, StandardCharsets.UTF_8);
340 public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
341 readSignatureMarkerAndVersionIfNeeded();
342 return readYangInstanceIdentifierInternal();
345 private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
346 int size = input.readInt();
348 List<PathArgument> pathArguments = new ArrayList<>(size);
350 for(int i = 0; i < size; i++) {
351 pathArguments.add(readPathArgument());
353 return YangInstanceIdentifier.create(pathArguments);
356 private Set<String> readObjSet() throws IOException {
357 int count = input.readInt();
358 Set<String> children = new HashSet<>(count);
359 for(int i = 0; i < count; i++) {
360 children.add(readCodedString());
366 public PathArgument readPathArgument() throws IOException {
368 int type = input.readByte();
372 case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
373 return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
375 case PathArgumentTypes.NODE_IDENTIFIER :
376 return new NodeIdentifier(readQName());
378 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES :
379 return new NodeIdentifierWithPredicates(readQName(), readKeyValueMap());
381 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
382 return new NodeWithValue<>(readQName(), readObject());
389 @SuppressWarnings("unchecked")
390 private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(final QName nodeType,
391 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
393 LOG.debug("Reading children of leaf set");
395 lastLeafSetQName = nodeType;
397 LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
399 while(child != null) {
400 builder.withChild(child);
401 child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
406 @SuppressWarnings({ "unchecked", "rawtypes" })
407 private NormalizedNodeContainerBuilder addDataContainerChildren(
408 final NormalizedNodeContainerBuilder builder) throws IOException {
409 LOG.debug("Reading data container (leaf nodes) nodes");
411 NormalizedNode<?, ?> child = readNormalizedNodeInternal();
413 while(child != null) {
414 builder.addChild(child);
415 child = readNormalizedNodeInternal();
421 public void readFully(final byte[] b) throws IOException {
422 readSignatureMarkerAndVersionIfNeeded();
427 public void readFully(final byte[] b, final int off, final int len) throws IOException {
428 readSignatureMarkerAndVersionIfNeeded();
429 input.readFully(b, off, len);
433 public int skipBytes(final int n) throws IOException {
434 readSignatureMarkerAndVersionIfNeeded();
435 return input.skipBytes(n);
439 public boolean readBoolean() throws IOException {
440 readSignatureMarkerAndVersionIfNeeded();
441 return input.readBoolean();
445 public byte readByte() throws IOException {
446 readSignatureMarkerAndVersionIfNeeded();
447 return input.readByte();
451 public int readUnsignedByte() throws IOException {
452 readSignatureMarkerAndVersionIfNeeded();
453 return input.readUnsignedByte();
457 public short readShort() throws IOException {
458 readSignatureMarkerAndVersionIfNeeded();
459 return input.readShort();
463 public int readUnsignedShort() throws IOException {
464 readSignatureMarkerAndVersionIfNeeded();
465 return input.readUnsignedShort();
469 public char readChar() throws IOException {
470 readSignatureMarkerAndVersionIfNeeded();
471 return input.readChar();
475 public int readInt() throws IOException {
476 readSignatureMarkerAndVersionIfNeeded();
477 return input.readInt();
481 public long readLong() throws IOException {
482 readSignatureMarkerAndVersionIfNeeded();
483 return input.readLong();
487 public float readFloat() throws IOException {
488 readSignatureMarkerAndVersionIfNeeded();
489 return input.readFloat();
493 public double readDouble() throws IOException {
494 readSignatureMarkerAndVersionIfNeeded();
495 return input.readDouble();
499 public String readLine() throws IOException {
500 readSignatureMarkerAndVersionIfNeeded();
501 return input.readLine();
505 public String readUTF() throws IOException {
506 readSignatureMarkerAndVersionIfNeeded();
507 return input.readUTF();