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.util.ArrayList;
20 import java.util.HashMap;
21 import java.util.HashSet;
22 import java.util.List;
25 import javax.xml.transform.dom.DOMSource;
26 import org.opendaylight.controller.cluster.datastore.node.utils.QNameFactory;
27 import org.opendaylight.yangtools.yang.common.QName;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
33 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
36 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
37 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
38 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
39 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
44 * NormalizedNodeInputStreamReader reads the byte stream and constructs the normalized node including its children nodes.
45 * This process goes in recursive manner, where each NodeTypes object signifies the start of the object, except END_NODE.
46 * If a node can have children, then that node's end is calculated based on appearance of END_NODE.
50 public class NormalizedNodeInputStreamReader implements NormalizedNodeStreamReader {
52 private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeInputStreamReader.class);
54 private static final String REVISION_ARG = "?revision=";
56 private final DataInput input;
58 private final Map<Integer, String> codedStringMap = new HashMap<>();
60 private QName lastLeafSetQName;
62 private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
63 Object, LeafNode<Object>> leafBuilder;
65 private NormalizedNodeAttrBuilder<NodeWithValue, Object,
66 LeafSetEntryNode<Object>> leafSetEntryBuilder;
68 private final StringBuilder reusableStringBuilder = new StringBuilder(50);
70 private boolean readSignatureMarker = true;
72 public NormalizedNodeInputStreamReader(InputStream stream) throws IOException {
73 Preconditions.checkNotNull(stream);
74 input = new DataInputStream(stream);
77 public NormalizedNodeInputStreamReader(DataInput input) {
78 this.input = Preconditions.checkNotNull(input);
82 public NormalizedNode<?, ?> readNormalizedNode() throws IOException {
83 readSignatureMarkerAndVersionIfNeeded();
84 return readNormalizedNodeInternal();
87 private void readSignatureMarkerAndVersionIfNeeded() throws IOException {
88 if(readSignatureMarker) {
89 readSignatureMarker = false;
91 byte marker = input.readByte();
92 if(marker != NormalizedNodeOutputStreamWriter.SIGNATURE_MARKER) {
93 throw new InvalidNormalizedNodeStreamException(String.format(
94 "Invalid signature marker: %d", marker));
97 input.readShort(); // read the version - not currently used/needed.
101 private NormalizedNode<?, ?> readNormalizedNodeInternal() throws IOException {
102 // each node should start with a byte
103 byte nodeType = input.readByte();
105 if(nodeType == NodeTypes.END_NODE) {
106 LOG.debug("End node reached. return");
111 case NodeTypes.AUGMENTATION_NODE :
112 YangInstanceIdentifier.AugmentationIdentifier augIdentifier =
113 new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
115 LOG.debug("Reading augmentation node {} ", augIdentifier);
117 return addDataContainerChildren(Builders.augmentationBuilder().
118 withNodeIdentifier(augIdentifier)).build();
120 case NodeTypes.LEAF_SET_ENTRY_NODE :
121 Object value = readObject();
122 NodeWithValue leafIdentifier = new NodeWithValue(lastLeafSetQName, value);
124 LOG.debug("Reading leaf set entry node {}, value {}", leafIdentifier, value);
126 return leafSetEntryBuilder().withNodeIdentifier(leafIdentifier).withValue(value).build();
128 case NodeTypes.MAP_ENTRY_NODE :
129 NodeIdentifierWithPredicates entryIdentifier = new NodeIdentifierWithPredicates(
130 readQName(), readKeyValueMap());
132 LOG.debug("Reading map entry node {} ", entryIdentifier);
134 return addDataContainerChildren(Builders.mapEntryBuilder().
135 withNodeIdentifier(entryIdentifier)).build();
138 return readNodeIdentifierDependentNode(nodeType, new NodeIdentifier(readQName()));
142 private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
143 Object, LeafNode<Object>> leafBuilder() {
144 if(leafBuilder == null) {
145 leafBuilder = Builders.leafBuilder();
151 private NormalizedNodeAttrBuilder<NodeWithValue, Object,
152 LeafSetEntryNode<Object>> leafSetEntryBuilder() {
153 if(leafSetEntryBuilder == null) {
154 leafSetEntryBuilder = Builders.leafSetEntryBuilder();
157 return leafSetEntryBuilder;
160 private NormalizedNode<?, ?> readNodeIdentifierDependentNode(byte nodeType, NodeIdentifier identifier)
164 case NodeTypes.LEAF_NODE :
165 LOG.debug("Read leaf node {}", identifier);
166 // Read the object value
167 return leafBuilder().withNodeIdentifier(identifier).withValue(readObject()).build();
169 case NodeTypes.ANY_XML_NODE :
170 LOG.debug("Read xml node");
171 return Builders.anyXmlBuilder().withValue((DOMSource) readObject()).build();
173 case NodeTypes.MAP_NODE :
174 LOG.debug("Read map node {}", identifier);
175 return addDataContainerChildren(Builders.mapBuilder().
176 withNodeIdentifier(identifier)).build();
178 case NodeTypes.CHOICE_NODE :
179 LOG.debug("Read choice node {}", identifier);
180 return addDataContainerChildren(Builders.choiceBuilder().
181 withNodeIdentifier(identifier)).build();
183 case NodeTypes.ORDERED_MAP_NODE :
184 LOG.debug("Reading ordered map node {}", identifier);
185 return addDataContainerChildren(Builders.orderedMapBuilder().
186 withNodeIdentifier(identifier)).build();
188 case NodeTypes.UNKEYED_LIST :
189 LOG.debug("Read unkeyed list node {}", identifier);
190 return addDataContainerChildren(Builders.unkeyedListBuilder().
191 withNodeIdentifier(identifier)).build();
193 case NodeTypes.UNKEYED_LIST_ITEM :
194 LOG.debug("Read unkeyed list item node {}", identifier);
195 return addDataContainerChildren(Builders.unkeyedListEntryBuilder().
196 withNodeIdentifier(identifier)).build();
198 case NodeTypes.CONTAINER_NODE :
199 LOG.debug("Read container node {}", identifier);
200 return addDataContainerChildren(Builders.containerBuilder().
201 withNodeIdentifier(identifier)).build();
203 case NodeTypes.LEAF_SET :
204 LOG.debug("Read leaf set node {}", identifier);
205 return addLeafSetChildren(identifier.getNodeType(),
206 Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
213 private QName readQName() throws IOException {
214 // Read in the same sequence of writing
215 String localName = readCodedString();
216 String namespace = readCodedString();
217 String revision = readCodedString();
220 if(!Strings.isNullOrEmpty(revision)) {
221 qName = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG).
222 append(revision).append(')').append(localName).toString();
224 qName = reusableStringBuilder.append('(').append(namespace).append(')').
225 append(localName).toString();
228 reusableStringBuilder.delete(0, reusableStringBuilder.length());
229 return QNameFactory.create(qName);
233 private String readCodedString() throws IOException {
234 byte valueType = input.readByte();
235 if(valueType == NormalizedNodeOutputStreamWriter.IS_CODE_VALUE) {
236 return codedStringMap.get(input.readInt());
237 } else if(valueType == NormalizedNodeOutputStreamWriter.IS_STRING_VALUE) {
238 String value = input.readUTF().intern();
239 codedStringMap.put(Integer.valueOf(codedStringMap.size()), value);
246 private Set<QName> readQNameSet() throws IOException{
247 // Read the children count
248 int count = input.readInt();
249 Set<QName> children = new HashSet<>(count);
250 for(int i = 0; i < count; i++) {
251 children.add(readQName());
256 private Map<QName, Object> readKeyValueMap() throws IOException {
257 int count = input.readInt();
258 Map<QName, Object> keyValueMap = new HashMap<>(count);
260 for(int i = 0; i < count; i++) {
261 keyValueMap.put(readQName(), readObject());
267 private Object readObject() throws IOException {
268 byte objectType = input.readByte();
270 case ValueTypes.BITS_TYPE:
273 case ValueTypes.BOOL_TYPE :
274 return Boolean.valueOf(input.readBoolean());
276 case ValueTypes.BYTE_TYPE :
277 return Byte.valueOf(input.readByte());
279 case ValueTypes.INT_TYPE :
280 return Integer.valueOf(input.readInt());
282 case ValueTypes.LONG_TYPE :
283 return Long.valueOf(input.readLong());
285 case ValueTypes.QNAME_TYPE :
288 case ValueTypes.SHORT_TYPE :
289 return Short.valueOf(input.readShort());
291 case ValueTypes.STRING_TYPE :
292 return input.readUTF();
294 case ValueTypes.BIG_DECIMAL_TYPE :
295 return new BigDecimal(input.readUTF());
297 case ValueTypes.BIG_INTEGER_TYPE :
298 return new BigInteger(input.readUTF());
300 case ValueTypes.BINARY_TYPE :
301 byte[] bytes = new byte[input.readInt()];
302 input.readFully(bytes);
305 case ValueTypes.YANG_IDENTIFIER_TYPE :
306 return readYangInstanceIdentifierInternal();
313 public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
314 readSignatureMarkerAndVersionIfNeeded();
315 return readYangInstanceIdentifierInternal();
318 private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
319 int size = input.readInt();
321 List<PathArgument> pathArguments = new ArrayList<>(size);
323 for(int i = 0; i < size; i++) {
324 pathArguments.add(readPathArgument());
326 return YangInstanceIdentifier.create(pathArguments);
329 private Set<String> readObjSet() throws IOException {
330 int count = input.readInt();
331 Set<String> children = new HashSet<>(count);
332 for(int i = 0; i < count; i++) {
333 children.add(readCodedString());
338 public PathArgument readPathArgument() throws IOException {
340 int type = input.readByte();
344 case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
345 return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
347 case PathArgumentTypes.NODE_IDENTIFIER :
348 return new NodeIdentifier(readQName());
350 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES :
351 return new NodeIdentifierWithPredicates(readQName(), readKeyValueMap());
353 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
354 return new NodeWithValue(readQName(), readObject());
361 @SuppressWarnings("unchecked")
362 private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(QName nodeType,
363 ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
365 LOG.debug("Reading children of leaf set");
367 lastLeafSetQName = nodeType;
369 LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
371 while(child != null) {
372 builder.withChild(child);
373 child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
378 @SuppressWarnings({ "unchecked", "rawtypes" })
379 private NormalizedNodeContainerBuilder addDataContainerChildren(
380 NormalizedNodeContainerBuilder builder) throws IOException {
381 LOG.debug("Reading data container (leaf nodes) nodes");
383 NormalizedNode<?, ?> child = readNormalizedNodeInternal();
385 while(child != null) {
386 builder.addChild(child);
387 child = readNormalizedNodeInternal();