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;
74 * @deprecated Use {@link #NormalizedNodeInputStreamReader(DataInput)} instead.
77 public NormalizedNodeInputStreamReader(final InputStream stream) throws IOException {
78 Preconditions.checkNotNull(stream);
79 input = new DataInputStream(stream);
82 public NormalizedNodeInputStreamReader(final DataInput input) {
83 this.input = Preconditions.checkNotNull(input);
87 public NormalizedNode<?, ?> readNormalizedNode() throws IOException {
88 readSignatureMarkerAndVersionIfNeeded();
89 return readNormalizedNodeInternal();
92 private void readSignatureMarkerAndVersionIfNeeded() throws IOException {
93 if(readSignatureMarker) {
94 readSignatureMarker = false;
96 final byte marker = input.readByte();
97 if (marker != TokenTypes.SIGNATURE_MARKER) {
98 throw new InvalidNormalizedNodeStreamException(String.format(
99 "Invalid signature marker: %d", marker));
102 final short version = input.readShort();
103 if (version != TokenTypes.LITHIUM_VERSION) {
104 throw new InvalidNormalizedNodeStreamException(String.format("Unhandled stream version %s", version));
109 private NormalizedNode<?, ?> readNormalizedNodeInternal() throws IOException {
110 // each node should start with a byte
111 byte nodeType = input.readByte();
113 if(nodeType == NodeTypes.END_NODE) {
114 LOG.debug("End node reached. return");
119 case NodeTypes.AUGMENTATION_NODE :
120 YangInstanceIdentifier.AugmentationIdentifier augIdentifier =
121 new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
123 LOG.debug("Reading augmentation node {} ", augIdentifier);
125 return addDataContainerChildren(Builders.augmentationBuilder().
126 withNodeIdentifier(augIdentifier)).build();
128 case NodeTypes.LEAF_SET_ENTRY_NODE :
129 Object value = readObject();
130 NodeWithValue leafIdentifier = new NodeWithValue(lastLeafSetQName, value);
132 LOG.debug("Reading leaf set entry node {}, value {}", leafIdentifier, value);
134 return leafSetEntryBuilder().withNodeIdentifier(leafIdentifier).withValue(value).build();
136 case NodeTypes.MAP_ENTRY_NODE :
137 NodeIdentifierWithPredicates entryIdentifier = new NodeIdentifierWithPredicates(
138 readQName(), readKeyValueMap());
140 LOG.debug("Reading map entry node {} ", entryIdentifier);
142 return addDataContainerChildren(Builders.mapEntryBuilder().
143 withNodeIdentifier(entryIdentifier)).build();
146 return readNodeIdentifierDependentNode(nodeType, new NodeIdentifier(readQName()));
150 private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
151 Object, LeafNode<Object>> leafBuilder() {
152 if(leafBuilder == null) {
153 leafBuilder = Builders.leafBuilder();
159 private NormalizedNodeAttrBuilder<NodeWithValue, Object,
160 LeafSetEntryNode<Object>> leafSetEntryBuilder() {
161 if(leafSetEntryBuilder == null) {
162 leafSetEntryBuilder = Builders.leafSetEntryBuilder();
165 return leafSetEntryBuilder;
168 private NormalizedNode<?, ?> readNodeIdentifierDependentNode(final byte nodeType, final NodeIdentifier identifier)
172 case NodeTypes.LEAF_NODE :
173 LOG.debug("Read leaf node {}", identifier);
174 // Read the object value
175 return leafBuilder().withNodeIdentifier(identifier).withValue(readObject()).build();
177 case NodeTypes.ANY_XML_NODE :
178 LOG.debug("Read xml node");
179 return Builders.anyXmlBuilder().withValue((DOMSource) readObject()).build();
181 case NodeTypes.MAP_NODE :
182 LOG.debug("Read map node {}", identifier);
183 return addDataContainerChildren(Builders.mapBuilder().
184 withNodeIdentifier(identifier)).build();
186 case NodeTypes.CHOICE_NODE :
187 LOG.debug("Read choice node {}", identifier);
188 return addDataContainerChildren(Builders.choiceBuilder().
189 withNodeIdentifier(identifier)).build();
191 case NodeTypes.ORDERED_MAP_NODE :
192 LOG.debug("Reading ordered map node {}", identifier);
193 return addDataContainerChildren(Builders.orderedMapBuilder().
194 withNodeIdentifier(identifier)).build();
196 case NodeTypes.UNKEYED_LIST :
197 LOG.debug("Read unkeyed list node {}", identifier);
198 return addDataContainerChildren(Builders.unkeyedListBuilder().
199 withNodeIdentifier(identifier)).build();
201 case NodeTypes.UNKEYED_LIST_ITEM :
202 LOG.debug("Read unkeyed list item node {}", identifier);
203 return addDataContainerChildren(Builders.unkeyedListEntryBuilder().
204 withNodeIdentifier(identifier)).build();
206 case NodeTypes.CONTAINER_NODE :
207 LOG.debug("Read container node {}", identifier);
208 return addDataContainerChildren(Builders.containerBuilder().
209 withNodeIdentifier(identifier)).build();
211 case NodeTypes.LEAF_SET :
212 LOG.debug("Read leaf set node {}", identifier);
213 return addLeafSetChildren(identifier.getNodeType(),
214 Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
221 private QName readQName() throws IOException {
222 // Read in the same sequence of writing
223 String localName = readCodedString();
224 String namespace = readCodedString();
225 String revision = readCodedString();
228 if(!Strings.isNullOrEmpty(revision)) {
229 qName = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG).
230 append(revision).append(')').append(localName).toString();
232 qName = reusableStringBuilder.append('(').append(namespace).append(')').
233 append(localName).toString();
236 reusableStringBuilder.delete(0, reusableStringBuilder.length());
237 return QNameFactory.create(qName);
241 private String readCodedString() throws IOException {
242 byte valueType = input.readByte();
243 if(valueType == TokenTypes.IS_CODE_VALUE) {
244 return codedStringMap.get(input.readInt());
245 } else if(valueType == TokenTypes.IS_STRING_VALUE) {
246 String value = input.readUTF().intern();
247 codedStringMap.put(Integer.valueOf(codedStringMap.size()), value);
254 private Set<QName> readQNameSet() throws IOException{
255 // Read the children count
256 int count = input.readInt();
257 Set<QName> children = new HashSet<>(count);
258 for(int i = 0; i < count; i++) {
259 children.add(readQName());
264 private Map<QName, Object> readKeyValueMap() throws IOException {
265 int count = input.readInt();
266 Map<QName, Object> keyValueMap = new HashMap<>(count);
268 for(int i = 0; i < count; i++) {
269 keyValueMap.put(readQName(), readObject());
275 private Object readObject() throws IOException {
276 byte objectType = input.readByte();
278 case ValueTypes.BITS_TYPE:
281 case ValueTypes.BOOL_TYPE :
282 return Boolean.valueOf(input.readBoolean());
284 case ValueTypes.BYTE_TYPE :
285 return Byte.valueOf(input.readByte());
287 case ValueTypes.INT_TYPE :
288 return Integer.valueOf(input.readInt());
290 case ValueTypes.LONG_TYPE :
291 return Long.valueOf(input.readLong());
293 case ValueTypes.QNAME_TYPE :
296 case ValueTypes.SHORT_TYPE :
297 return Short.valueOf(input.readShort());
299 case ValueTypes.STRING_TYPE :
300 return input.readUTF();
302 case ValueTypes.STRING_BYTES_TYPE:
303 return readStringBytes();
305 case ValueTypes.BIG_DECIMAL_TYPE :
306 return new BigDecimal(input.readUTF());
308 case ValueTypes.BIG_INTEGER_TYPE :
309 return new BigInteger(input.readUTF());
311 case ValueTypes.BINARY_TYPE :
312 byte[] bytes = new byte[input.readInt()];
313 input.readFully(bytes);
316 case ValueTypes.YANG_IDENTIFIER_TYPE :
317 return readYangInstanceIdentifierInternal();
324 private String readStringBytes() throws IOException {
325 byte[] bytes = new byte[input.readInt()];
326 input.readFully(bytes);
327 return new String(bytes, StandardCharsets.UTF_8);
330 public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
331 readSignatureMarkerAndVersionIfNeeded();
332 return readYangInstanceIdentifierInternal();
335 private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
336 int size = input.readInt();
338 List<PathArgument> pathArguments = new ArrayList<>(size);
340 for(int i = 0; i < size; i++) {
341 pathArguments.add(readPathArgument());
343 return YangInstanceIdentifier.create(pathArguments);
346 private Set<String> readObjSet() throws IOException {
347 int count = input.readInt();
348 Set<String> children = new HashSet<>(count);
349 for(int i = 0; i < count; i++) {
350 children.add(readCodedString());
355 public PathArgument readPathArgument() throws IOException {
357 int type = input.readByte();
361 case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
362 return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
364 case PathArgumentTypes.NODE_IDENTIFIER :
365 return new NodeIdentifier(readQName());
367 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES :
368 return new NodeIdentifierWithPredicates(readQName(), readKeyValueMap());
370 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
371 return new NodeWithValue(readQName(), readObject());
378 @SuppressWarnings("unchecked")
379 private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(final QName nodeType,
380 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
382 LOG.debug("Reading children of leaf set");
384 lastLeafSetQName = nodeType;
386 LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
388 while(child != null) {
389 builder.withChild(child);
390 child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
395 @SuppressWarnings({ "unchecked", "rawtypes" })
396 private NormalizedNodeContainerBuilder addDataContainerChildren(
397 final NormalizedNodeContainerBuilder builder) throws IOException {
398 LOG.debug("Reading data container (leaf nodes) nodes");
400 NormalizedNode<?, ?> child = readNormalizedNodeInternal();
402 while(child != null) {
403 builder.addChild(child);
404 child = readNormalizedNodeInternal();