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();
211 case NodeTypes.ORDERED_LEAF_SET:
212 LOG.debug("Read leaf set node");
213 ListNodeBuilder<Object, LeafSetEntryNode<Object>> orderedLeafSetBuilder =
214 Builders.orderedLeafSetBuilder().withNodeIdentifier(identifier);
215 orderedLeafSetBuilder = addLeafSetChildren(identifier.getNodeType(), orderedLeafSetBuilder);
216 return orderedLeafSetBuilder.build();
223 private QName readQName() throws IOException {
224 // Read in the same sequence of writing
225 String localName = readCodedString();
226 String namespace = readCodedString();
227 String revision = readCodedString();
230 if(!Strings.isNullOrEmpty(revision)) {
231 qName = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG).
232 append(revision).append(')').append(localName).toString();
234 qName = reusableStringBuilder.append('(').append(namespace).append(')').
235 append(localName).toString();
238 reusableStringBuilder.delete(0, reusableStringBuilder.length());
239 return QNameFactory.create(qName);
243 private String readCodedString() throws IOException {
244 byte valueType = input.readByte();
245 if(valueType == NormalizedNodeOutputStreamWriter.IS_CODE_VALUE) {
246 return codedStringMap.get(input.readInt());
247 } else if(valueType == NormalizedNodeOutputStreamWriter.IS_STRING_VALUE) {
248 String value = input.readUTF().intern();
249 codedStringMap.put(Integer.valueOf(codedStringMap.size()), value);
256 private Set<QName> readQNameSet() throws IOException{
257 // Read the children count
258 int count = input.readInt();
259 Set<QName> children = new HashSet<>(count);
260 for(int i = 0; i < count; i++) {
261 children.add(readQName());
266 private Map<QName, Object> readKeyValueMap() throws IOException {
267 int count = input.readInt();
268 Map<QName, Object> keyValueMap = new HashMap<>(count);
270 for(int i = 0; i < count; i++) {
271 keyValueMap.put(readQName(), readObject());
277 private Object readObject() throws IOException {
278 byte objectType = input.readByte();
280 case ValueTypes.BITS_TYPE:
283 case ValueTypes.BOOL_TYPE :
284 return Boolean.valueOf(input.readBoolean());
286 case ValueTypes.BYTE_TYPE :
287 return Byte.valueOf(input.readByte());
289 case ValueTypes.INT_TYPE :
290 return Integer.valueOf(input.readInt());
292 case ValueTypes.LONG_TYPE :
293 return Long.valueOf(input.readLong());
295 case ValueTypes.QNAME_TYPE :
298 case ValueTypes.SHORT_TYPE :
299 return Short.valueOf(input.readShort());
301 case ValueTypes.STRING_TYPE :
302 return input.readUTF();
304 case ValueTypes.STRING_BYTES_TYPE:
305 return readStringBytes();
307 case ValueTypes.BIG_DECIMAL_TYPE :
308 return new BigDecimal(input.readUTF());
310 case ValueTypes.BIG_INTEGER_TYPE :
311 return new BigInteger(input.readUTF());
313 case ValueTypes.BINARY_TYPE :
314 byte[] bytes = new byte[input.readInt()];
315 input.readFully(bytes);
318 case ValueTypes.YANG_IDENTIFIER_TYPE :
319 return readYangInstanceIdentifierInternal();
326 private String readStringBytes() throws IOException {
327 byte[] bytes = new byte[input.readInt()];
328 input.readFully(bytes);
329 return new String(bytes, StandardCharsets.UTF_8);
332 public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
333 readSignatureMarkerAndVersionIfNeeded();
334 return readYangInstanceIdentifierInternal();
337 private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
338 int size = input.readInt();
340 List<PathArgument> pathArguments = new ArrayList<>(size);
342 for(int i = 0; i < size; i++) {
343 pathArguments.add(readPathArgument());
345 return YangInstanceIdentifier.create(pathArguments);
348 private Set<String> readObjSet() throws IOException {
349 int count = input.readInt();
350 Set<String> children = new HashSet<>(count);
351 for(int i = 0; i < count; i++) {
352 children.add(readCodedString());
357 public PathArgument readPathArgument() throws IOException {
359 int type = input.readByte();
363 case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
364 return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
366 case PathArgumentTypes.NODE_IDENTIFIER :
367 return new NodeIdentifier(readQName());
369 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES :
370 return new NodeIdentifierWithPredicates(readQName(), readKeyValueMap());
372 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
373 return new NodeWithValue(readQName(), readObject());
380 @SuppressWarnings("unchecked")
381 private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(QName nodeType,
382 ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
384 LOG.debug("Reading children of leaf set");
386 lastLeafSetQName = nodeType;
388 LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
390 while(child != null) {
391 builder.withChild(child);
392 child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
397 @SuppressWarnings({ "unchecked", "rawtypes" })
398 private NormalizedNodeContainerBuilder addDataContainerChildren(
399 NormalizedNodeContainerBuilder builder) throws IOException {
400 LOG.debug("Reading data container (leaf nodes) nodes");
402 NormalizedNode<?, ?> child = readNormalizedNodeInternal();
404 while(child != null) {
405 builder.addChild(child);
406 child = readNormalizedNodeInternal();