3 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
5 * This program and the accompanying materials are made available under the
6 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7 * and is available at http://www.eclipse.org/legal/epl-v10.html
11 package org.opendaylight.controller.cluster.datastore.node.utils.stream;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Strings;
15 import java.io.DataInput;
16 import java.io.DataInputStream;
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.math.BigDecimal;
20 import java.math.BigInteger;
21 import java.nio.charset.StandardCharsets;
22 import java.util.ArrayList;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.List;
28 import javax.xml.transform.dom.DOMSource;
29 import org.opendaylight.controller.cluster.datastore.node.utils.QNameFactory;
30 import org.opendaylight.yangtools.yang.common.QName;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
36 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
39 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
40 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
41 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
42 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
47 * NormalizedNodeInputStreamReader reads the byte stream and constructs the normalized node including its children nodes.
48 * This process goes in recursive manner, where each NodeTypes object signifies the start of the object, except END_NODE.
49 * If a node can have children, then that node's end is calculated based on appearance of END_NODE.
53 public class NormalizedNodeInputStreamReader implements NormalizedNodeStreamReader {
55 private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeInputStreamReader.class);
57 private static final String REVISION_ARG = "?revision=";
59 private final DataInput input;
61 private final Map<Integer, String> codedStringMap = new HashMap<>();
63 private QName lastLeafSetQName;
65 private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
66 Object, LeafNode<Object>> leafBuilder;
68 private NormalizedNodeAttrBuilder<NodeWithValue, Object,
69 LeafSetEntryNode<Object>> leafSetEntryBuilder;
71 private final StringBuilder reusableStringBuilder = new StringBuilder(50);
73 private boolean readSignatureMarker = true;
75 public NormalizedNodeInputStreamReader(InputStream stream) throws IOException {
76 Preconditions.checkNotNull(stream);
77 input = new DataInputStream(stream);
80 public NormalizedNodeInputStreamReader(DataInput input) {
81 this.input = Preconditions.checkNotNull(input);
85 public NormalizedNode<?, ?> readNormalizedNode() throws IOException {
86 readSignatureMarkerAndVersionIfNeeded();
87 return readNormalizedNodeInternal();
90 private void readSignatureMarkerAndVersionIfNeeded() throws IOException {
91 if(readSignatureMarker) {
92 readSignatureMarker = false;
94 byte marker = input.readByte();
95 if(marker != NormalizedNodeOutputStreamWriter.SIGNATURE_MARKER) {
96 throw new InvalidNormalizedNodeStreamException(String.format(
97 "Invalid signature marker: %d", marker));
100 input.readShort(); // read the version - not currently used/needed.
104 private NormalizedNode<?, ?> readNormalizedNodeInternal() throws IOException {
105 // each node should start with a byte
106 byte nodeType = input.readByte();
108 if(nodeType == NodeTypes.END_NODE) {
109 LOG.debug("End node reached. return");
114 case NodeTypes.AUGMENTATION_NODE :
115 YangInstanceIdentifier.AugmentationIdentifier augIdentifier =
116 new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
118 LOG.debug("Reading augmentation node {} ", augIdentifier);
120 return addDataContainerChildren(Builders.augmentationBuilder().
121 withNodeIdentifier(augIdentifier)).build();
123 case NodeTypes.LEAF_SET_ENTRY_NODE :
124 Object value = readObject();
125 NodeWithValue leafIdentifier = new NodeWithValue(lastLeafSetQName, value);
127 LOG.debug("Reading leaf set entry node {}, value {}", leafIdentifier, value);
129 return leafSetEntryBuilder().withNodeIdentifier(leafIdentifier).withValue(value).build();
131 case NodeTypes.MAP_ENTRY_NODE :
132 NodeIdentifierWithPredicates entryIdentifier = new NodeIdentifierWithPredicates(
133 readQName(), readKeyValueMap());
135 LOG.debug("Reading map entry node {} ", entryIdentifier);
137 return addDataContainerChildren(Builders.mapEntryBuilder().
138 withNodeIdentifier(entryIdentifier)).build();
141 return readNodeIdentifierDependentNode(nodeType, new NodeIdentifier(readQName()));
145 private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
146 Object, LeafNode<Object>> leafBuilder() {
147 if(leafBuilder == null) {
148 leafBuilder = Builders.leafBuilder();
154 private NormalizedNodeAttrBuilder<NodeWithValue, Object,
155 LeafSetEntryNode<Object>> leafSetEntryBuilder() {
156 if(leafSetEntryBuilder == null) {
157 leafSetEntryBuilder = Builders.leafSetEntryBuilder();
160 return leafSetEntryBuilder;
163 private NormalizedNode<?, ?> readNodeIdentifierDependentNode(byte nodeType, NodeIdentifier identifier)
167 case NodeTypes.LEAF_NODE :
168 LOG.debug("Read leaf node {}", identifier);
169 // Read the object value
170 return leafBuilder().withNodeIdentifier(identifier).withValue(readObject()).build();
172 case NodeTypes.ANY_XML_NODE :
173 LOG.debug("Read xml node");
174 return Builders.anyXmlBuilder().withValue((DOMSource) readObject()).build();
176 case NodeTypes.MAP_NODE :
177 LOG.debug("Read map node {}", identifier);
178 return addDataContainerChildren(Builders.mapBuilder().
179 withNodeIdentifier(identifier)).build();
181 case NodeTypes.CHOICE_NODE :
182 LOG.debug("Read choice node {}", identifier);
183 return addDataContainerChildren(Builders.choiceBuilder().
184 withNodeIdentifier(identifier)).build();
186 case NodeTypes.ORDERED_MAP_NODE :
187 LOG.debug("Reading ordered map node {}", identifier);
188 return addDataContainerChildren(Builders.orderedMapBuilder().
189 withNodeIdentifier(identifier)).build();
191 case NodeTypes.UNKEYED_LIST :
192 LOG.debug("Read unkeyed list node {}", identifier);
193 return addDataContainerChildren(Builders.unkeyedListBuilder().
194 withNodeIdentifier(identifier)).build();
196 case NodeTypes.UNKEYED_LIST_ITEM :
197 LOG.debug("Read unkeyed list item node {}", identifier);
198 return addDataContainerChildren(Builders.unkeyedListEntryBuilder().
199 withNodeIdentifier(identifier)).build();
201 case NodeTypes.CONTAINER_NODE :
202 LOG.debug("Read container node {}", identifier);
203 return addDataContainerChildren(Builders.containerBuilder().
204 withNodeIdentifier(identifier)).build();
206 case NodeTypes.LEAF_SET :
207 LOG.debug("Read leaf set node {}", identifier);
208 return addLeafSetChildren(identifier.getNodeType(),
209 Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
216 private QName readQName() throws IOException {
217 // Read in the same sequence of writing
218 String localName = readCodedString();
219 String namespace = readCodedString();
220 String revision = readCodedString();
223 if(!Strings.isNullOrEmpty(revision)) {
224 qName = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG).
225 append(revision).append(')').append(localName).toString();
227 qName = reusableStringBuilder.append('(').append(namespace).append(')').
228 append(localName).toString();
231 reusableStringBuilder.delete(0, reusableStringBuilder.length());
232 return QNameFactory.create(qName);
236 private String readCodedString() throws IOException {
237 byte valueType = input.readByte();
238 if(valueType == NormalizedNodeOutputStreamWriter.IS_CODE_VALUE) {
239 return codedStringMap.get(input.readInt());
240 } else if(valueType == NormalizedNodeOutputStreamWriter.IS_STRING_VALUE) {
241 String value = input.readUTF().intern();
242 codedStringMap.put(Integer.valueOf(codedStringMap.size()), value);
249 private Set<QName> readQNameSet() throws IOException{
250 // Read the children count
251 int count = input.readInt();
252 Set<QName> children = new HashSet<>(count);
253 for(int i = 0; i < count; i++) {
254 children.add(readQName());
259 private Map<QName, Object> readKeyValueMap() throws IOException {
260 int count = input.readInt();
261 Map<QName, Object> keyValueMap = new HashMap<>(count);
263 for(int i = 0; i < count; i++) {
264 keyValueMap.put(readQName(), readObject());
270 private Object readObject() throws IOException {
271 byte objectType = input.readByte();
273 case ValueTypes.BITS_TYPE:
276 case ValueTypes.BOOL_TYPE :
277 return Boolean.valueOf(input.readBoolean());
279 case ValueTypes.BYTE_TYPE :
280 return Byte.valueOf(input.readByte());
282 case ValueTypes.INT_TYPE :
283 return Integer.valueOf(input.readInt());
285 case ValueTypes.LONG_TYPE :
286 return Long.valueOf(input.readLong());
288 case ValueTypes.QNAME_TYPE :
291 case ValueTypes.SHORT_TYPE :
292 return Short.valueOf(input.readShort());
294 case ValueTypes.STRING_TYPE :
295 return input.readUTF();
297 case ValueTypes.STRING_BYTES_TYPE:
298 return readStringBytes();
300 case ValueTypes.BIG_DECIMAL_TYPE :
301 return new BigDecimal(input.readUTF());
303 case ValueTypes.BIG_INTEGER_TYPE :
304 return new BigInteger(input.readUTF());
306 case ValueTypes.BINARY_TYPE :
307 byte[] bytes = new byte[input.readInt()];
308 input.readFully(bytes);
311 case ValueTypes.YANG_IDENTIFIER_TYPE :
312 return readYangInstanceIdentifierInternal();
319 private String readStringBytes() throws IOException {
320 byte[] bytes = new byte[input.readInt()];
321 input.readFully(bytes);
322 return new String(bytes, StandardCharsets.UTF_8);
325 public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
326 readSignatureMarkerAndVersionIfNeeded();
327 return readYangInstanceIdentifierInternal();
330 private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
331 int size = input.readInt();
333 List<PathArgument> pathArguments = new ArrayList<>(size);
335 for(int i = 0; i < size; i++) {
336 pathArguments.add(readPathArgument());
338 return YangInstanceIdentifier.create(pathArguments);
341 private Set<String> readObjSet() throws IOException {
342 int count = input.readInt();
343 Set<String> children = new HashSet<>(count);
344 for(int i = 0; i < count; i++) {
345 children.add(readCodedString());
350 public PathArgument readPathArgument() throws IOException {
352 int type = input.readByte();
356 case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
357 return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
359 case PathArgumentTypes.NODE_IDENTIFIER :
360 return new NodeIdentifier(readQName());
362 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES :
363 return new NodeIdentifierWithPredicates(readQName(), readKeyValueMap());
365 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
366 return new NodeWithValue(readQName(), readObject());
373 @SuppressWarnings("unchecked")
374 private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(QName nodeType,
375 ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
377 LOG.debug("Reading children of leaf set");
379 lastLeafSetQName = nodeType;
381 LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
383 while(child != null) {
384 builder.withChild(child);
385 child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
390 @SuppressWarnings({ "unchecked", "rawtypes" })
391 private NormalizedNodeContainerBuilder addDataContainerChildren(
392 NormalizedNodeContainerBuilder builder) throws IOException {
393 LOG.debug("Reading data container (leaf nodes) nodes");
395 NormalizedNode<?, ?> child = readNormalizedNodeInternal();
397 while(child != null) {
398 builder.addChild(child);
399 child = readNormalizedNodeInternal();