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.util.ArrayList;
22 import java.util.HashMap;
23 import java.util.HashSet;
24 import java.util.List;
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.Node;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
35 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
38 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
39 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
40 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
41 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
46 * NormalizedNodeInputStreamReader reads the byte stream and constructs the normalized node including its children nodes.
47 * This process goes in recursive manner, where each NodeTypes object signifies the start of the object, except END_NODE.
48 * If a node can have children, then that node's end is calculated based on appearance of END_NODE.
52 public class NormalizedNodeInputStreamReader implements NormalizedNodeStreamReader {
54 private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeInputStreamReader.class);
56 private static final String REVISION_ARG = "?revision=";
58 private final DataInput input;
60 private final Map<Integer, String> codedStringMap = new HashMap<>();
62 private QName lastLeafSetQName;
64 private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
65 Object, LeafNode<Object>> leafBuilder;
67 private NormalizedNodeAttrBuilder<NodeWithValue, Object,
68 LeafSetEntryNode<Object>> leafSetEntryBuilder;
70 private final StringBuilder reusableStringBuilder = new StringBuilder(50);
72 private boolean readSignatureMarker = true;
74 public NormalizedNodeInputStreamReader(InputStream stream) throws IOException {
75 Preconditions.checkNotNull(stream);
76 input = new DataInputStream(stream);
79 public NormalizedNodeInputStreamReader(DataInput input) throws IOException {
80 this.input = Preconditions.checkNotNull(input);
84 public NormalizedNode<?, ?> readNormalizedNode() throws IOException {
85 readSignatureMarkerAndVersionIfNeeded();
86 return readNormalizedNodeInternal();
89 private void readSignatureMarkerAndVersionIfNeeded() throws IOException {
90 if(readSignatureMarker) {
91 readSignatureMarker = false;
93 byte marker = input.readByte();
94 if(marker != NormalizedNodeOutputStreamWriter.SIGNATURE_MARKER) {
95 throw new InvalidNormalizedNodeStreamException(String.format(
96 "Invalid signature marker: %d", marker));
99 input.readShort(); // read the version - not currently used/needed.
103 private NormalizedNode<?, ?> readNormalizedNodeInternal() throws IOException {
104 // each node should start with a byte
105 byte nodeType = input.readByte();
107 if(nodeType == NodeTypes.END_NODE) {
108 LOG.debug("End node reached. return");
113 case NodeTypes.AUGMENTATION_NODE :
114 YangInstanceIdentifier.AugmentationIdentifier augIdentifier =
115 new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
117 LOG.debug("Reading augmentation node {} ", augIdentifier);
119 return addDataContainerChildren(Builders.augmentationBuilder().
120 withNodeIdentifier(augIdentifier)).build();
122 case NodeTypes.LEAF_SET_ENTRY_NODE :
123 Object value = readObject();
124 NodeWithValue leafIdentifier = new NodeWithValue(lastLeafSetQName, value);
126 LOG.debug("Reading leaf set entry node {}, value {}", leafIdentifier, value);
128 return leafSetEntryBuilder().withNodeIdentifier(leafIdentifier).withValue(value).build();
130 case NodeTypes.MAP_ENTRY_NODE :
131 NodeIdentifierWithPredicates entryIdentifier = new NodeIdentifierWithPredicates(
132 readQName(), readKeyValueMap());
134 LOG.debug("Reading map entry node {} ", entryIdentifier);
136 return addDataContainerChildren(Builders.mapEntryBuilder().
137 withNodeIdentifier(entryIdentifier)).build();
140 return readNodeIdentifierDependentNode(nodeType, new NodeIdentifier(readQName()));
144 private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
145 Object, LeafNode<Object>> leafBuilder() {
146 if(leafBuilder == null) {
147 leafBuilder = Builders.leafBuilder();
153 private NormalizedNodeAttrBuilder<NodeWithValue, Object,
154 LeafSetEntryNode<Object>> leafSetEntryBuilder() {
155 if(leafSetEntryBuilder == null) {
156 leafSetEntryBuilder = Builders.leafSetEntryBuilder();
159 return leafSetEntryBuilder;
162 private NormalizedNode<?, ?> readNodeIdentifierDependentNode(byte nodeType, NodeIdentifier identifier)
166 case NodeTypes.LEAF_NODE :
167 LOG.debug("Read leaf node {}", identifier);
168 // Read the object value
169 return leafBuilder().withNodeIdentifier(identifier).withValue(readObject()).build();
171 case NodeTypes.ANY_XML_NODE :
172 LOG.debug("Read xml node");
173 return Builders.anyXmlBuilder().withValue((Node<?>) readObject()).build();
175 case NodeTypes.MAP_NODE :
176 LOG.debug("Read map node {}", identifier);
177 return addDataContainerChildren(Builders.mapBuilder().
178 withNodeIdentifier(identifier)).build();
180 case NodeTypes.CHOICE_NODE :
181 LOG.debug("Read choice node {}", identifier);
182 return addDataContainerChildren(Builders.choiceBuilder().
183 withNodeIdentifier(identifier)).build();
185 case NodeTypes.ORDERED_MAP_NODE :
186 LOG.debug("Reading ordered map node {}", identifier);
187 return addDataContainerChildren(Builders.orderedMapBuilder().
188 withNodeIdentifier(identifier)).build();
190 case NodeTypes.UNKEYED_LIST :
191 LOG.debug("Read unkeyed list node {}", identifier);
192 return addDataContainerChildren(Builders.unkeyedListBuilder().
193 withNodeIdentifier(identifier)).build();
195 case NodeTypes.UNKEYED_LIST_ITEM :
196 LOG.debug("Read unkeyed list item node {}", identifier);
197 return addDataContainerChildren(Builders.unkeyedListEntryBuilder().
198 withNodeIdentifier(identifier)).build();
200 case NodeTypes.CONTAINER_NODE :
201 LOG.debug("Read container node {}", identifier);
202 return addDataContainerChildren(Builders.containerBuilder().
203 withNodeIdentifier(identifier)).build();
205 case NodeTypes.LEAF_SET :
206 LOG.debug("Read leaf set node {}", identifier);
207 return addLeafSetChildren(identifier.getNodeType(),
208 Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
215 private QName readQName() throws IOException {
216 // Read in the same sequence of writing
217 String localName = readCodedString();
218 String namespace = readCodedString();
219 String revision = readCodedString();
222 if(!Strings.isNullOrEmpty(revision)) {
223 qName = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG).
224 append(revision).append(')').append(localName).toString();
226 qName = reusableStringBuilder.append('(').append(namespace).append(')').
227 append(localName).toString();
230 reusableStringBuilder.delete(0, reusableStringBuilder.length());
231 return QNameFactory.create(qName);
235 private String readCodedString() throws IOException {
236 byte valueType = input.readByte();
237 if(valueType == NormalizedNodeOutputStreamWriter.IS_CODE_VALUE) {
238 return codedStringMap.get(input.readInt());
239 } else if(valueType == NormalizedNodeOutputStreamWriter.IS_STRING_VALUE) {
240 String value = input.readUTF().intern();
241 codedStringMap.put(Integer.valueOf(codedStringMap.size()), value);
248 private Set<QName> readQNameSet() throws IOException{
249 // Read the children count
250 int count = input.readInt();
251 Set<QName> children = new HashSet<>(count);
252 for(int i = 0; i < count; i++) {
253 children.add(readQName());
258 private Map<QName, Object> readKeyValueMap() throws IOException {
259 int count = input.readInt();
260 Map<QName, Object> keyValueMap = new HashMap<>(count);
262 for(int i = 0; i < count; i++) {
263 keyValueMap.put(readQName(), readObject());
269 private Object readObject() throws IOException {
270 byte objectType = input.readByte();
272 case ValueTypes.BITS_TYPE:
275 case ValueTypes.BOOL_TYPE :
276 return Boolean.valueOf(input.readBoolean());
278 case ValueTypes.BYTE_TYPE :
279 return Byte.valueOf(input.readByte());
281 case ValueTypes.INT_TYPE :
282 return Integer.valueOf(input.readInt());
284 case ValueTypes.LONG_TYPE :
285 return Long.valueOf(input.readLong());
287 case ValueTypes.QNAME_TYPE :
290 case ValueTypes.SHORT_TYPE :
291 return Short.valueOf(input.readShort());
293 case ValueTypes.STRING_TYPE :
294 return input.readUTF();
296 case ValueTypes.BIG_DECIMAL_TYPE :
297 return new BigDecimal(input.readUTF());
299 case ValueTypes.BIG_INTEGER_TYPE :
300 return new BigInteger(input.readUTF());
302 case ValueTypes.BINARY_TYPE :
303 byte[] bytes = new byte[input.readInt()];
304 input.readFully(bytes);
307 case ValueTypes.YANG_IDENTIFIER_TYPE :
308 return readYangInstanceIdentifierInternal();
315 public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
316 readSignatureMarkerAndVersionIfNeeded();
317 return readYangInstanceIdentifierInternal();
320 private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
321 int size = input.readInt();
323 List<PathArgument> pathArguments = new ArrayList<>(size);
325 for(int i = 0; i < size; i++) {
326 pathArguments.add(readPathArgument());
328 return YangInstanceIdentifier.create(pathArguments);
331 private Set<String> readObjSet() throws IOException {
332 int count = input.readInt();
333 Set<String> children = new HashSet<>(count);
334 for(int i = 0; i < count; i++) {
335 children.add(readCodedString());
340 private PathArgument readPathArgument() throws IOException {
342 int type = input.readByte();
346 case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
347 return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
349 case PathArgumentTypes.NODE_IDENTIFIER :
350 return new NodeIdentifier(readQName());
352 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES :
353 return new NodeIdentifierWithPredicates(readQName(), readKeyValueMap());
355 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
356 return new NodeWithValue(readQName(), readObject());
363 @SuppressWarnings("unchecked")
364 private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(QName nodeType,
365 ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
367 LOG.debug("Reading children of leaf set");
369 lastLeafSetQName = nodeType;
371 LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
373 while(child != null) {
374 builder.withChild(child);
375 child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
380 @SuppressWarnings({ "unchecked", "rawtypes" })
381 private NormalizedNodeContainerBuilder addDataContainerChildren(
382 NormalizedNodeContainerBuilder builder) throws IOException {
383 LOG.debug("Reading data container (leaf nodes) nodes");
385 NormalizedNode<?, ?> child = readNormalizedNodeInternal();
387 while(child != null) {
388 builder.addChild(child);
389 child = readNormalizedNodeInternal();