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();
229 private QName readQName() throws IOException {
230 // Read in the same sequence of writing
231 String localName = readCodedString();
232 String namespace = readCodedString();
233 String revision = readCodedString();
236 if(!Strings.isNullOrEmpty(revision)) {
237 qName = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG).
238 append(revision).append(')').append(localName).toString();
240 qName = reusableStringBuilder.append('(').append(namespace).append(')').
241 append(localName).toString();
244 reusableStringBuilder.delete(0, reusableStringBuilder.length());
245 return QNameFactory.create(qName);
249 private String readCodedString() throws IOException {
250 byte valueType = input.readByte();
251 if(valueType == TokenTypes.IS_CODE_VALUE) {
252 return codedStringMap.get(input.readInt());
253 } else if(valueType == TokenTypes.IS_STRING_VALUE) {
254 String value = input.readUTF().intern();
255 codedStringMap.put(Integer.valueOf(codedStringMap.size()), value);
262 private Set<QName> readQNameSet() throws IOException{
263 // Read the children count
264 int count = input.readInt();
265 Set<QName> children = new HashSet<>(count);
266 for(int i = 0; i < count; i++) {
267 children.add(readQName());
272 private Map<QName, Object> readKeyValueMap() throws IOException {
273 int count = input.readInt();
274 Map<QName, Object> keyValueMap = new HashMap<>(count);
276 for(int i = 0; i < count; i++) {
277 keyValueMap.put(readQName(), readObject());
283 private Object readObject() throws IOException {
284 byte objectType = input.readByte();
286 case ValueTypes.BITS_TYPE:
289 case ValueTypes.BOOL_TYPE :
290 return Boolean.valueOf(input.readBoolean());
292 case ValueTypes.BYTE_TYPE :
293 return Byte.valueOf(input.readByte());
295 case ValueTypes.INT_TYPE :
296 return Integer.valueOf(input.readInt());
298 case ValueTypes.LONG_TYPE :
299 return Long.valueOf(input.readLong());
301 case ValueTypes.QNAME_TYPE :
304 case ValueTypes.SHORT_TYPE :
305 return Short.valueOf(input.readShort());
307 case ValueTypes.STRING_TYPE :
308 return input.readUTF();
310 case ValueTypes.STRING_BYTES_TYPE:
311 return readStringBytes();
313 case ValueTypes.BIG_DECIMAL_TYPE :
314 return new BigDecimal(input.readUTF());
316 case ValueTypes.BIG_INTEGER_TYPE :
317 return new BigInteger(input.readUTF());
319 case ValueTypes.BINARY_TYPE :
320 byte[] bytes = new byte[input.readInt()];
321 input.readFully(bytes);
324 case ValueTypes.YANG_IDENTIFIER_TYPE :
325 return readYangInstanceIdentifierInternal();
332 private String readStringBytes() throws IOException {
333 byte[] bytes = new byte[input.readInt()];
334 input.readFully(bytes);
335 return new String(bytes, StandardCharsets.UTF_8);
339 public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
340 readSignatureMarkerAndVersionIfNeeded();
341 return readYangInstanceIdentifierInternal();
344 private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
345 int size = input.readInt();
347 List<PathArgument> pathArguments = new ArrayList<>(size);
349 for(int i = 0; i < size; i++) {
350 pathArguments.add(readPathArgument());
352 return YangInstanceIdentifier.create(pathArguments);
355 private Set<String> readObjSet() throws IOException {
356 int count = input.readInt();
357 Set<String> children = new HashSet<>(count);
358 for(int i = 0; i < count; i++) {
359 children.add(readCodedString());
365 public PathArgument readPathArgument() throws IOException {
367 int type = input.readByte();
371 case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
372 return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
374 case PathArgumentTypes.NODE_IDENTIFIER :
375 return new NodeIdentifier(readQName());
377 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES :
378 return new NodeIdentifierWithPredicates(readQName(), readKeyValueMap());
380 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
381 return new NodeWithValue(readQName(), readObject());
388 @SuppressWarnings("unchecked")
389 private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(final QName nodeType,
390 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
392 LOG.debug("Reading children of leaf set");
394 lastLeafSetQName = nodeType;
396 LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
398 while(child != null) {
399 builder.withChild(child);
400 child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
405 @SuppressWarnings({ "unchecked", "rawtypes" })
406 private NormalizedNodeContainerBuilder addDataContainerChildren(
407 final NormalizedNodeContainerBuilder builder) throws IOException {
408 LOG.debug("Reading data container (leaf nodes) nodes");
410 NormalizedNode<?, ?> child = readNormalizedNodeInternal();
412 while(child != null) {
413 builder.addChild(child);
414 child = readNormalizedNodeInternal();
420 public void readFully(final byte[] b) throws IOException {
421 readSignatureMarkerAndVersionIfNeeded();
426 public void readFully(final byte[] b, final int off, final int len) throws IOException {
427 readSignatureMarkerAndVersionIfNeeded();
428 input.readFully(b, off, len);
432 public int skipBytes(final int n) throws IOException {
433 readSignatureMarkerAndVersionIfNeeded();
434 return input.skipBytes(n);
438 public boolean readBoolean() throws IOException {
439 readSignatureMarkerAndVersionIfNeeded();
440 return input.readBoolean();
444 public byte readByte() throws IOException {
445 readSignatureMarkerAndVersionIfNeeded();
446 return input.readByte();
450 public int readUnsignedByte() throws IOException {
451 readSignatureMarkerAndVersionIfNeeded();
452 return input.readUnsignedByte();
456 public short readShort() throws IOException {
457 readSignatureMarkerAndVersionIfNeeded();
458 return input.readShort();
462 public int readUnsignedShort() throws IOException {
463 readSignatureMarkerAndVersionIfNeeded();
464 return input.readUnsignedShort();
468 public char readChar() throws IOException {
469 readSignatureMarkerAndVersionIfNeeded();
470 return input.readChar();
474 public int readInt() throws IOException {
475 readSignatureMarkerAndVersionIfNeeded();
476 return input.readInt();
480 public long readLong() throws IOException {
481 readSignatureMarkerAndVersionIfNeeded();
482 return input.readLong();
486 public float readFloat() throws IOException {
487 readSignatureMarkerAndVersionIfNeeded();
488 return input.readFloat();
492 public double readDouble() throws IOException {
493 readSignatureMarkerAndVersionIfNeeded();
494 return input.readDouble();
498 public String readLine() throws IOException {
499 readSignatureMarkerAndVersionIfNeeded();
500 return input.readLine();
504 public String readUTF() throws IOException {
505 readSignatureMarkerAndVersionIfNeeded();
506 return input.readUTF();