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 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;
73 public NormalizedNodeInputStreamReader(InputStream stream) throws IOException {
74 Preconditions.checkNotNull(stream);
75 input = new DataInputStream(stream);
78 public NormalizedNodeInputStreamReader(DataInput input) {
79 this.input = Preconditions.checkNotNull(input);
83 public NormalizedNode<?, ?> readNormalizedNode() throws IOException {
84 readSignatureMarkerAndVersionIfNeeded();
85 return readNormalizedNodeInternal();
88 private void readSignatureMarkerAndVersionIfNeeded() throws IOException {
89 if(readSignatureMarker) {
90 readSignatureMarker = false;
92 byte marker = input.readByte();
93 if(marker != NormalizedNodeOutputStreamWriter.SIGNATURE_MARKER) {
94 throw new InvalidNormalizedNodeStreamException(String.format(
95 "Invalid signature marker: %d", marker));
98 input.readShort(); // read the version - not currently used/needed.
102 private NormalizedNode<?, ?> readNormalizedNodeInternal() throws IOException {
103 // each node should start with a byte
104 byte nodeType = input.readByte();
106 if(nodeType == NodeTypes.END_NODE) {
107 LOG.debug("End node reached. return");
112 case NodeTypes.AUGMENTATION_NODE :
113 YangInstanceIdentifier.AugmentationIdentifier augIdentifier =
114 new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
116 LOG.debug("Reading augmentation node {} ", augIdentifier);
118 return addDataContainerChildren(Builders.augmentationBuilder().
119 withNodeIdentifier(augIdentifier)).build();
121 case NodeTypes.LEAF_SET_ENTRY_NODE :
122 Object value = readObject();
123 NodeWithValue leafIdentifier = new NodeWithValue(lastLeafSetQName, value);
125 LOG.debug("Reading leaf set entry node {}, value {}", leafIdentifier, value);
127 return leafSetEntryBuilder().withNodeIdentifier(leafIdentifier).withValue(value).build();
129 case NodeTypes.MAP_ENTRY_NODE :
130 NodeIdentifierWithPredicates entryIdentifier = new NodeIdentifierWithPredicates(
131 readQName(), readKeyValueMap());
133 LOG.debug("Reading map entry node {} ", entryIdentifier);
135 return addDataContainerChildren(Builders.mapEntryBuilder().
136 withNodeIdentifier(entryIdentifier)).build();
139 return readNodeIdentifierDependentNode(nodeType, new NodeIdentifier(readQName()));
143 private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
144 Object, LeafNode<Object>> leafBuilder() {
145 if(leafBuilder == null) {
146 leafBuilder = Builders.leafBuilder();
152 private NormalizedNodeAttrBuilder<NodeWithValue, Object,
153 LeafSetEntryNode<Object>> leafSetEntryBuilder() {
154 if(leafSetEntryBuilder == null) {
155 leafSetEntryBuilder = Builders.leafSetEntryBuilder();
158 return leafSetEntryBuilder;
161 private NormalizedNode<?, ?> readNodeIdentifierDependentNode(byte nodeType, NodeIdentifier identifier)
165 case NodeTypes.LEAF_NODE :
166 LOG.debug("Read leaf node {}", identifier);
167 // Read the object value
168 return leafBuilder().withNodeIdentifier(identifier).withValue(readObject()).build();
170 case NodeTypes.ANY_XML_NODE :
171 LOG.debug("Read xml node");
172 return Builders.anyXmlBuilder().withValue((DOMSource) readObject()).build();
174 case NodeTypes.MAP_NODE :
175 LOG.debug("Read map node {}", identifier);
176 return addDataContainerChildren(Builders.mapBuilder().
177 withNodeIdentifier(identifier)).build();
179 case NodeTypes.CHOICE_NODE :
180 LOG.debug("Read choice node {}", identifier);
181 return addDataContainerChildren(Builders.choiceBuilder().
182 withNodeIdentifier(identifier)).build();
184 case NodeTypes.ORDERED_MAP_NODE :
185 LOG.debug("Reading ordered map node {}", identifier);
186 return addDataContainerChildren(Builders.orderedMapBuilder().
187 withNodeIdentifier(identifier)).build();
189 case NodeTypes.UNKEYED_LIST :
190 LOG.debug("Read unkeyed list node {}", identifier);
191 return addDataContainerChildren(Builders.unkeyedListBuilder().
192 withNodeIdentifier(identifier)).build();
194 case NodeTypes.UNKEYED_LIST_ITEM :
195 LOG.debug("Read unkeyed list item node {}", identifier);
196 return addDataContainerChildren(Builders.unkeyedListEntryBuilder().
197 withNodeIdentifier(identifier)).build();
199 case NodeTypes.CONTAINER_NODE :
200 LOG.debug("Read container node {}", identifier);
201 return addDataContainerChildren(Builders.containerBuilder().
202 withNodeIdentifier(identifier)).build();
204 case NodeTypes.LEAF_SET :
205 LOG.debug("Read leaf set node {}", identifier);
206 return addLeafSetChildren(identifier.getNodeType(),
207 Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
214 private QName readQName() throws IOException {
215 // Read in the same sequence of writing
216 String localName = readCodedString();
217 String namespace = readCodedString();
218 String revision = readCodedString();
221 if(!Strings.isNullOrEmpty(revision)) {
222 qName = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG).
223 append(revision).append(')').append(localName).toString();
225 qName = reusableStringBuilder.append('(').append(namespace).append(')').
226 append(localName).toString();
229 reusableStringBuilder.delete(0, reusableStringBuilder.length());
230 return QNameFactory.create(qName);
234 private String readCodedString() throws IOException {
235 byte valueType = input.readByte();
236 if(valueType == NormalizedNodeOutputStreamWriter.IS_CODE_VALUE) {
237 return codedStringMap.get(input.readInt());
238 } else if(valueType == NormalizedNodeOutputStreamWriter.IS_STRING_VALUE) {
239 String value = input.readUTF().intern();
240 codedStringMap.put(Integer.valueOf(codedStringMap.size()), value);
247 private Set<QName> readQNameSet() throws IOException{
248 // Read the children count
249 int count = input.readInt();
250 Set<QName> children = new HashSet<>(count);
251 for(int i = 0; i < count; i++) {
252 children.add(readQName());
257 private Map<QName, Object> readKeyValueMap() throws IOException {
258 int count = input.readInt();
259 Map<QName, Object> keyValueMap = new HashMap<>(count);
261 for(int i = 0; i < count; i++) {
262 keyValueMap.put(readQName(), readObject());
268 private Object readObject() throws IOException {
269 byte objectType = input.readByte();
271 case ValueTypes.BITS_TYPE:
274 case ValueTypes.BOOL_TYPE :
275 return Boolean.valueOf(input.readBoolean());
277 case ValueTypes.BYTE_TYPE :
278 return Byte.valueOf(input.readByte());
280 case ValueTypes.INT_TYPE :
281 return Integer.valueOf(input.readInt());
283 case ValueTypes.LONG_TYPE :
284 return Long.valueOf(input.readLong());
286 case ValueTypes.QNAME_TYPE :
289 case ValueTypes.SHORT_TYPE :
290 return Short.valueOf(input.readShort());
292 case ValueTypes.STRING_TYPE :
293 return input.readUTF();
295 case ValueTypes.STRING_BYTES_TYPE:
296 return readStringBytes();
298 case ValueTypes.BIG_DECIMAL_TYPE :
299 return new BigDecimal(input.readUTF());
301 case ValueTypes.BIG_INTEGER_TYPE :
302 return new BigInteger(input.readUTF());
304 case ValueTypes.BINARY_TYPE :
305 byte[] bytes = new byte[input.readInt()];
306 input.readFully(bytes);
309 case ValueTypes.YANG_IDENTIFIER_TYPE :
310 return readYangInstanceIdentifierInternal();
317 private String readStringBytes() throws IOException {
318 byte[] bytes = new byte[input.readInt()];
319 input.readFully(bytes);
320 return new String(bytes, StandardCharsets.UTF_8);
323 public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
324 readSignatureMarkerAndVersionIfNeeded();
325 return readYangInstanceIdentifierInternal();
328 private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
329 int size = input.readInt();
331 List<PathArgument> pathArguments = new ArrayList<>(size);
333 for(int i = 0; i < size; i++) {
334 pathArguments.add(readPathArgument());
336 return YangInstanceIdentifier.create(pathArguments);
339 private Set<String> readObjSet() throws IOException {
340 int count = input.readInt();
341 Set<String> children = new HashSet<>(count);
342 for(int i = 0; i < count; i++) {
343 children.add(readCodedString());
348 public PathArgument readPathArgument() throws IOException {
350 int type = input.readByte();
354 case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
355 return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
357 case PathArgumentTypes.NODE_IDENTIFIER :
358 return new NodeIdentifier(readQName());
360 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES :
361 return new NodeIdentifierWithPredicates(readQName(), readKeyValueMap());
363 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
364 return new NodeWithValue(readQName(), readObject());
371 @SuppressWarnings("unchecked")
372 private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(QName nodeType,
373 ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
375 LOG.debug("Reading children of leaf set");
377 lastLeafSetQName = nodeType;
379 LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
381 while(child != null) {
382 builder.withChild(child);
383 child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
388 @SuppressWarnings({ "unchecked", "rawtypes" })
389 private NormalizedNodeContainerBuilder addDataContainerChildren(
390 NormalizedNodeContainerBuilder builder) throws IOException {
391 LOG.debug("Reading data container (leaf nodes) nodes");
393 NormalizedNode<?, ?> child = readNormalizedNodeInternal();
395 while(child != null) {
396 builder.addChild(child);
397 child = readNormalizedNodeInternal();