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, LeafSetEntryNode<Object>> leafSetEntryBuilder;
68 private final StringBuilder reusableStringBuilder = new StringBuilder(50);
70 private boolean readSignatureMarker = true;
73 * @deprecated Use {@link #NormalizedNodeInputStreamReader(DataInput)} instead.
76 public NormalizedNodeInputStreamReader(final InputStream stream) throws IOException {
77 this((DataInput) new DataInputStream(Preconditions.checkNotNull(stream)));
81 * @deprecated Use {@link NormalizedNodeInputOutput#newDataInput(DataInput)} instead.
84 public NormalizedNodeInputStreamReader(final DataInput input) {
88 NormalizedNodeInputStreamReader(final DataInput input, final boolean versionChecked) {
89 this.input = Preconditions.checkNotNull(input);
90 readSignatureMarker = !versionChecked;
94 public NormalizedNode<?, ?> readNormalizedNode() throws IOException {
95 readSignatureMarkerAndVersionIfNeeded();
96 return readNormalizedNodeInternal();
99 private void readSignatureMarkerAndVersionIfNeeded() throws IOException {
100 if(readSignatureMarker) {
101 readSignatureMarker = false;
103 final byte marker = input.readByte();
104 if (marker != TokenTypes.SIGNATURE_MARKER) {
105 throw new InvalidNormalizedNodeStreamException(String.format(
106 "Invalid signature marker: %d", marker));
109 final short version = input.readShort();
110 if (version != TokenTypes.LITHIUM_VERSION) {
111 throw new InvalidNormalizedNodeStreamException(String.format("Unhandled stream version %s", version));
116 private NormalizedNode<?, ?> readNormalizedNodeInternal() throws IOException {
117 // each node should start with a byte
118 byte nodeType = input.readByte();
120 if(nodeType == NodeTypes.END_NODE) {
121 LOG.debug("End node reached. return");
126 case NodeTypes.AUGMENTATION_NODE :
127 YangInstanceIdentifier.AugmentationIdentifier augIdentifier =
128 new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
130 LOG.debug("Reading augmentation node {} ", augIdentifier);
132 return addDataContainerChildren(Builders.augmentationBuilder().
133 withNodeIdentifier(augIdentifier)).build();
135 case NodeTypes.LEAF_SET_ENTRY_NODE :
136 QName name = lastLeafSetQName;
141 Object value = readObject();
142 NodeWithValue<Object> leafIdentifier = new NodeWithValue<>(name, value);
144 LOG.debug("Reading leaf set entry node {}, value {}", leafIdentifier, value);
146 return leafSetEntryBuilder().withNodeIdentifier(leafIdentifier).withValue(value).build();
148 case NodeTypes.MAP_ENTRY_NODE :
149 NodeIdentifierWithPredicates entryIdentifier = new NodeIdentifierWithPredicates(
150 readQName(), readKeyValueMap());
152 LOG.debug("Reading map entry node {} ", entryIdentifier);
154 return addDataContainerChildren(Builders.mapEntryBuilder().
155 withNodeIdentifier(entryIdentifier)).build();
158 return readNodeIdentifierDependentNode(nodeType, new NodeIdentifier(readQName()));
162 private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
163 Object, LeafNode<Object>> leafBuilder() {
164 if(leafBuilder == null) {
165 leafBuilder = Builders.leafBuilder();
171 private NormalizedNodeAttrBuilder<NodeWithValue, Object,
172 LeafSetEntryNode<Object>> leafSetEntryBuilder() {
173 if(leafSetEntryBuilder == null) {
174 leafSetEntryBuilder = Builders.leafSetEntryBuilder();
177 return leafSetEntryBuilder;
180 private NormalizedNode<?, ?> readNodeIdentifierDependentNode(final byte nodeType, final NodeIdentifier identifier)
184 case NodeTypes.LEAF_NODE :
185 LOG.debug("Read leaf node {}", identifier);
186 // Read the object value
187 return leafBuilder().withNodeIdentifier(identifier).withValue(readObject()).build();
189 case NodeTypes.ANY_XML_NODE :
190 LOG.debug("Read xml node");
191 return Builders.anyXmlBuilder().withValue((DOMSource) readObject()).build();
193 case NodeTypes.MAP_NODE :
194 LOG.debug("Read map node {}", identifier);
195 return addDataContainerChildren(Builders.mapBuilder().
196 withNodeIdentifier(identifier)).build();
198 case NodeTypes.CHOICE_NODE :
199 LOG.debug("Read choice node {}", identifier);
200 return addDataContainerChildren(Builders.choiceBuilder().
201 withNodeIdentifier(identifier)).build();
203 case NodeTypes.ORDERED_MAP_NODE :
204 LOG.debug("Reading ordered map node {}", identifier);
205 return addDataContainerChildren(Builders.orderedMapBuilder().
206 withNodeIdentifier(identifier)).build();
208 case NodeTypes.UNKEYED_LIST :
209 LOG.debug("Read unkeyed list node {}", identifier);
210 return addDataContainerChildren(Builders.unkeyedListBuilder().
211 withNodeIdentifier(identifier)).build();
213 case NodeTypes.UNKEYED_LIST_ITEM :
214 LOG.debug("Read unkeyed list item node {}", identifier);
215 return addDataContainerChildren(Builders.unkeyedListEntryBuilder().
216 withNodeIdentifier(identifier)).build();
218 case NodeTypes.CONTAINER_NODE :
219 LOG.debug("Read container node {}", identifier);
220 return addDataContainerChildren(Builders.containerBuilder().
221 withNodeIdentifier(identifier)).build();
223 case NodeTypes.LEAF_SET :
224 LOG.debug("Read leaf set node {}", identifier);
225 return addLeafSetChildren(identifier.getNodeType(),
226 Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
228 case NodeTypes.ORDERED_LEAF_SET:
229 LOG.debug("Read ordered leaf set node {}", identifier);
230 ListNodeBuilder<Object, LeafSetEntryNode<Object>> orderedLeafSetBuilder =
231 Builders.orderedLeafSetBuilder().withNodeIdentifier(identifier);
232 orderedLeafSetBuilder = addLeafSetChildren(identifier.getNodeType(), orderedLeafSetBuilder);
233 return orderedLeafSetBuilder.build();
240 private QName readQName() throws IOException {
241 // Read in the same sequence of writing
242 String localName = readCodedString();
243 String namespace = readCodedString();
244 String revision = readCodedString();
247 if(!Strings.isNullOrEmpty(revision)) {
248 qName = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG).
249 append(revision).append(')').append(localName).toString();
251 qName = reusableStringBuilder.append('(').append(namespace).append(')').
252 append(localName).toString();
255 reusableStringBuilder.delete(0, reusableStringBuilder.length());
256 return QNameFactory.create(qName);
260 private String readCodedString() throws IOException {
261 byte valueType = input.readByte();
262 if(valueType == TokenTypes.IS_CODE_VALUE) {
263 return codedStringMap.get(input.readInt());
264 } else if(valueType == TokenTypes.IS_STRING_VALUE) {
265 String value = input.readUTF().intern();
266 codedStringMap.put(Integer.valueOf(codedStringMap.size()), value);
273 private Set<QName> readQNameSet() throws IOException{
274 // Read the children count
275 int count = input.readInt();
276 Set<QName> children = new HashSet<>(count);
277 for(int i = 0; i < count; i++) {
278 children.add(readQName());
283 private Map<QName, Object> readKeyValueMap() throws IOException {
284 int count = input.readInt();
285 Map<QName, Object> keyValueMap = new HashMap<>(count);
287 for(int i = 0; i < count; i++) {
288 keyValueMap.put(readQName(), readObject());
294 private Object readObject() throws IOException {
295 byte objectType = input.readByte();
297 case ValueTypes.BITS_TYPE:
300 case ValueTypes.BOOL_TYPE :
301 return Boolean.valueOf(input.readBoolean());
303 case ValueTypes.BYTE_TYPE :
304 return Byte.valueOf(input.readByte());
306 case ValueTypes.INT_TYPE :
307 return Integer.valueOf(input.readInt());
309 case ValueTypes.LONG_TYPE :
310 return Long.valueOf(input.readLong());
312 case ValueTypes.QNAME_TYPE :
315 case ValueTypes.SHORT_TYPE :
316 return Short.valueOf(input.readShort());
318 case ValueTypes.STRING_TYPE :
319 return input.readUTF();
321 case ValueTypes.STRING_BYTES_TYPE:
322 return readStringBytes();
324 case ValueTypes.BIG_DECIMAL_TYPE :
325 return new BigDecimal(input.readUTF());
327 case ValueTypes.BIG_INTEGER_TYPE :
328 return new BigInteger(input.readUTF());
330 case ValueTypes.BINARY_TYPE :
331 byte[] bytes = new byte[input.readInt()];
332 input.readFully(bytes);
335 case ValueTypes.YANG_IDENTIFIER_TYPE :
336 return readYangInstanceIdentifierInternal();
343 private String readStringBytes() throws IOException {
344 byte[] bytes = new byte[input.readInt()];
345 input.readFully(bytes);
346 return new String(bytes, StandardCharsets.UTF_8);
350 public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
351 readSignatureMarkerAndVersionIfNeeded();
352 return readYangInstanceIdentifierInternal();
355 private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
356 int size = input.readInt();
358 List<PathArgument> pathArguments = new ArrayList<>(size);
360 for(int i = 0; i < size; i++) {
361 pathArguments.add(readPathArgument());
363 return YangInstanceIdentifier.create(pathArguments);
366 private Set<String> readObjSet() throws IOException {
367 int count = input.readInt();
368 Set<String> children = new HashSet<>(count);
369 for(int i = 0; i < count; i++) {
370 children.add(readCodedString());
376 public PathArgument readPathArgument() throws IOException {
378 int type = input.readByte();
382 case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
383 return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
385 case PathArgumentTypes.NODE_IDENTIFIER :
386 return new NodeIdentifier(readQName());
388 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES :
389 return new NodeIdentifierWithPredicates(readQName(), readKeyValueMap());
391 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
392 return new NodeWithValue<>(readQName(), readObject());
399 @SuppressWarnings("unchecked")
400 private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(final QName nodeType,
401 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
403 LOG.debug("Reading children of leaf set");
405 lastLeafSetQName = nodeType;
407 LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
409 while(child != null) {
410 builder.withChild(child);
411 child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
416 @SuppressWarnings({ "unchecked", "rawtypes" })
417 private NormalizedNodeContainerBuilder addDataContainerChildren(
418 final NormalizedNodeContainerBuilder builder) throws IOException {
419 LOG.debug("Reading data container (leaf nodes) nodes");
421 NormalizedNode<?, ?> child = readNormalizedNodeInternal();
423 while(child != null) {
424 builder.addChild(child);
425 child = readNormalizedNodeInternal();
431 public void readFully(final byte[] b) throws IOException {
432 readSignatureMarkerAndVersionIfNeeded();
437 public void readFully(final byte[] b, final int off, final int len) throws IOException {
438 readSignatureMarkerAndVersionIfNeeded();
439 input.readFully(b, off, len);
443 public int skipBytes(final int n) throws IOException {
444 readSignatureMarkerAndVersionIfNeeded();
445 return input.skipBytes(n);
449 public boolean readBoolean() throws IOException {
450 readSignatureMarkerAndVersionIfNeeded();
451 return input.readBoolean();
455 public byte readByte() throws IOException {
456 readSignatureMarkerAndVersionIfNeeded();
457 return input.readByte();
461 public int readUnsignedByte() throws IOException {
462 readSignatureMarkerAndVersionIfNeeded();
463 return input.readUnsignedByte();
467 public short readShort() throws IOException {
468 readSignatureMarkerAndVersionIfNeeded();
469 return input.readShort();
473 public int readUnsignedShort() throws IOException {
474 readSignatureMarkerAndVersionIfNeeded();
475 return input.readUnsignedShort();
479 public char readChar() throws IOException {
480 readSignatureMarkerAndVersionIfNeeded();
481 return input.readChar();
485 public int readInt() throws IOException {
486 readSignatureMarkerAndVersionIfNeeded();
487 return input.readInt();
491 public long readLong() throws IOException {
492 readSignatureMarkerAndVersionIfNeeded();
493 return input.readLong();
497 public float readFloat() throws IOException {
498 readSignatureMarkerAndVersionIfNeeded();
499 return input.readFloat();
503 public double readDouble() throws IOException {
504 readSignatureMarkerAndVersionIfNeeded();
505 return input.readDouble();
509 public String readLine() throws IOException {
510 readSignatureMarkerAndVersionIfNeeded();
511 return input.readLine();
515 public String readUTF() throws IOException {
516 readSignatureMarkerAndVersionIfNeeded();
517 return input.readUTF();