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
8 package org.opendaylight.controller.cluster.datastore.node.utils.stream;
10 import static java.util.Objects.requireNonNull;
12 import com.google.common.base.Strings;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.ImmutableList.Builder;
15 import java.io.DataInput;
16 import java.io.IOException;
17 import java.io.StringReader;
18 import java.math.BigDecimal;
19 import java.math.BigInteger;
20 import java.nio.charset.StandardCharsets;
21 import java.util.ArrayList;
22 import java.util.HashSet;
23 import java.util.List;
25 import javax.xml.parsers.DocumentBuilderFactory;
26 import javax.xml.parsers.ParserConfigurationException;
27 import javax.xml.transform.dom.DOMSource;
28 import org.eclipse.jdt.annotation.NonNull;
29 import org.opendaylight.controller.cluster.datastore.node.utils.QNameFactory;
30 import org.opendaylight.yangtools.util.ImmutableOffsetMapTemplate;
31 import org.opendaylight.yangtools.yang.common.Empty;
32 import org.opendaylight.yangtools.yang.common.QName;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
39 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
42 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
43 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
44 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
45 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
46 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.w3c.dom.Element;
50 import org.xml.sax.InputSource;
51 import org.xml.sax.SAXException;
54 * NormalizedNodeInputStreamReader reads the byte stream and constructs the normalized node including its children
55 * nodes. This process goes in recursive manner, where each NodeTypes object signifies the start of the object, except
56 * END_NODE. If a node can have children, then that node's end is calculated based on appearance of END_NODE.
58 public class NormalizedNodeInputStreamReader extends ForwardingDataInput implements NormalizedNodeDataInput {
60 private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeInputStreamReader.class);
62 private final @NonNull DataInput input;
64 private final List<String> codedStringMap = new ArrayList<>();
66 private QName lastLeafSetQName;
68 private NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder;
70 @SuppressWarnings("rawtypes")
71 private NormalizedNodeBuilder<NodeWithValue, Object, LeafSetEntryNode<Object>> leafSetEntryBuilder;
73 NormalizedNodeInputStreamReader(final DataInput input) {
74 this.input = requireNonNull(input);
78 final DataInput delegate() {
83 public NormalizedNode<?, ?> readNormalizedNode() throws IOException {
84 return readNormalizedNodeInternal();
87 private NormalizedNode<?, ?> readNormalizedNodeInternal() throws IOException {
88 // each node should start with a byte
89 byte nodeType = input.readByte();
91 if (nodeType == NodeTypes.END_NODE) {
92 LOG.trace("End node reached. return");
93 lastLeafSetQName = null;
98 case NodeTypes.AUGMENTATION_NODE:
99 AugmentationIdentifier augIdentifier = readAugmentationIdentifier();
100 LOG.trace("Reading augmentation node {} ", augIdentifier);
101 return addDataContainerChildren(Builders.augmentationBuilder().withNodeIdentifier(augIdentifier))
104 case NodeTypes.LEAF_SET_ENTRY_NODE:
105 final QName name = lastLeafSetQName != null ? lastLeafSetQName : readQName();
106 final Object value = readObject();
107 final NodeWithValue<Object> leafIdentifier = new NodeWithValue<>(name, value);
108 LOG.trace("Reading leaf set entry node {}, value {}", leafIdentifier, value);
109 return leafSetEntryBuilder().withNodeIdentifier(leafIdentifier).withValue(value).build();
111 case NodeTypes.MAP_ENTRY_NODE:
112 final NodeIdentifierWithPredicates entryIdentifier = readNormalizedNodeWithPredicates();
113 LOG.trace("Reading map entry node {} ", entryIdentifier);
114 return addDataContainerChildren(Builders.mapEntryBuilder().withNodeIdentifier(entryIdentifier))
118 return readNodeIdentifierDependentNode(nodeType, readNodeIdentifier());
122 private NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder() {
123 if (leafBuilder == null) {
124 leafBuilder = Builders.leafBuilder();
130 @SuppressWarnings("rawtypes")
131 private NormalizedNodeBuilder<NodeWithValue, Object, LeafSetEntryNode<Object>> leafSetEntryBuilder() {
132 if (leafSetEntryBuilder == null) {
133 leafSetEntryBuilder = Builders.leafSetEntryBuilder();
136 return leafSetEntryBuilder;
139 private NormalizedNode<?, ?> readNodeIdentifierDependentNode(final byte nodeType, final NodeIdentifier identifier)
143 case NodeTypes.LEAF_NODE:
144 LOG.trace("Read leaf node {}", identifier);
145 // Read the object value
146 return leafBuilder().withNodeIdentifier(identifier).withValue(readObject()).build();
148 case NodeTypes.ANY_XML_NODE:
149 LOG.trace("Read xml node");
150 return Builders.anyXmlBuilder().withNodeIdentifier(identifier).withValue(readDOMSource()).build();
152 case NodeTypes.MAP_NODE:
153 LOG.trace("Read map node {}", identifier);
154 return addDataContainerChildren(Builders.mapBuilder().withNodeIdentifier(identifier)).build();
156 case NodeTypes.CHOICE_NODE:
157 LOG.trace("Read choice node {}", identifier);
158 return addDataContainerChildren(Builders.choiceBuilder().withNodeIdentifier(identifier)).build();
160 case NodeTypes.ORDERED_MAP_NODE:
161 LOG.trace("Reading ordered map node {}", identifier);
162 return addDataContainerChildren(Builders.orderedMapBuilder().withNodeIdentifier(identifier)).build();
164 case NodeTypes.UNKEYED_LIST:
165 LOG.trace("Read unkeyed list node {}", identifier);
166 return addDataContainerChildren(Builders.unkeyedListBuilder().withNodeIdentifier(identifier)).build();
168 case NodeTypes.UNKEYED_LIST_ITEM:
169 LOG.trace("Read unkeyed list item node {}", identifier);
170 return addDataContainerChildren(Builders.unkeyedListEntryBuilder()
171 .withNodeIdentifier(identifier)).build();
173 case NodeTypes.CONTAINER_NODE:
174 LOG.trace("Read container node {}", identifier);
175 return addDataContainerChildren(Builders.containerBuilder().withNodeIdentifier(identifier)).build();
177 case NodeTypes.LEAF_SET:
178 LOG.trace("Read leaf set node {}", identifier);
179 return addLeafSetChildren(identifier.getNodeType(),
180 Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
182 case NodeTypes.ORDERED_LEAF_SET:
183 LOG.trace("Read ordered leaf set node {}", identifier);
184 return addLeafSetChildren(identifier.getNodeType(),
185 Builders.orderedLeafSetBuilder().withNodeIdentifier(identifier)).build();
192 private DOMSource readDOMSource() throws IOException {
193 String xml = readObject().toString();
195 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
196 factory.setNamespaceAware(true);
197 Element node = factory.newDocumentBuilder().parse(
198 new InputSource(new StringReader(xml))).getDocumentElement();
199 return new DOMSource(node);
200 } catch (SAXException | ParserConfigurationException e) {
201 throw new IOException("Error parsing XML: " + xml, e);
205 private QName readQName() throws IOException {
206 // Read in the same sequence of writing
207 String localName = readCodedString();
208 String namespace = readCodedString();
209 String revision = Strings.emptyToNull(readCodedString());
211 return QNameFactory.create(new QNameFactory.Key(localName, namespace, revision));
215 private String readCodedString() throws IOException {
216 final byte valueType = input.readByte();
218 case TokenTypes.IS_NULL_VALUE:
220 case TokenTypes.IS_CODE_VALUE:
221 final int code = input.readInt();
223 return codedStringMap.get(code);
224 } catch (IndexOutOfBoundsException e) {
225 throw new IOException("String code " + code + " was not found", e);
227 case TokenTypes.IS_STRING_VALUE:
228 final String value = input.readUTF().intern();
229 codedStringMap.add(value);
232 throw new IOException("Unhandled string value type " + valueType);
236 private Set<QName> readQNameSet() throws IOException {
237 // Read the children count
238 int count = input.readInt();
239 Set<QName> children = new HashSet<>(count);
240 for (int i = 0; i < count; i++) {
241 children.add(readQName());
246 private AugmentationIdentifier readAugmentationIdentifier() throws IOException {
247 // FIXME: we should have a cache for these, too
248 return new AugmentationIdentifier(readQNameSet());
251 private NodeIdentifier readNodeIdentifier() throws IOException {
252 // FIXME: we should have a cache for these, too
253 return new NodeIdentifier(readQName());
256 private NodeIdentifierWithPredicates readNormalizedNodeWithPredicates() throws IOException {
257 final QName qname = readQName();
258 final int count = input.readInt();
261 return new NodeIdentifierWithPredicates(qname);
263 return new NodeIdentifierWithPredicates(qname, readQName(), readObject());
265 // ImmutableList is used by ImmutableOffsetMapTemplate for lookups, hence we use that.
266 final Builder<QName> keys = ImmutableList.builderWithExpectedSize(count);
267 final Object[] values = new Object[count];
268 for (int i = 0; i < count; i++) {
269 keys.add(readQName());
270 values[i] = readObject();
273 return new NodeIdentifierWithPredicates(qname, ImmutableOffsetMapTemplate.ordered(keys.build())
274 .instantiateWithValues(values));
278 private Object readObject() throws IOException {
279 byte objectType = input.readByte();
280 switch (objectType) {
281 case ValueTypes.BITS_TYPE:
284 case ValueTypes.BOOL_TYPE:
285 return input.readBoolean();
287 case ValueTypes.BYTE_TYPE:
288 return input.readByte();
290 case ValueTypes.INT_TYPE:
291 return input.readInt();
293 case ValueTypes.LONG_TYPE:
294 return input.readLong();
296 case ValueTypes.QNAME_TYPE:
299 case ValueTypes.SHORT_TYPE:
300 return input.readShort();
302 case ValueTypes.STRING_TYPE:
303 return input.readUTF();
305 case ValueTypes.STRING_BYTES_TYPE:
306 return readStringBytes();
308 case ValueTypes.BIG_DECIMAL_TYPE:
309 return new BigDecimal(input.readUTF());
311 case ValueTypes.BIG_INTEGER_TYPE:
312 return new BigInteger(input.readUTF());
314 case ValueTypes.BINARY_TYPE:
315 byte[] bytes = new byte[input.readInt()];
316 input.readFully(bytes);
319 case ValueTypes.YANG_IDENTIFIER_TYPE:
320 return readYangInstanceIdentifierInternal();
322 case ValueTypes.EMPTY_TYPE:
323 // Leaf nodes no longer allow null values and thus we no longer emit null values. Previously, the "empty"
324 // yang type was represented as null so we translate an incoming null value to Empty. It was possible for
325 // a BI user to set a string leaf to null and we're rolling the dice here but the chances for that are
326 // very low. We'd have to know the yang type but, even if we did, we can't let a null value pass upstream
327 // so we'd have to drop the leaf which might cause other issues.
328 case ValueTypes.NULL_TYPE:
329 return Empty.getInstance();
336 private String readStringBytes() throws IOException {
337 byte[] bytes = new byte[input.readInt()];
338 input.readFully(bytes);
339 return new String(bytes, StandardCharsets.UTF_8);
343 public SchemaPath readSchemaPath() throws IOException {
344 final boolean absolute = input.readBoolean();
345 final int size = input.readInt();
347 final Builder<QName> qnames = ImmutableList.builderWithExpectedSize(size);
348 for (int i = 0; i < size; ++i) {
349 qnames.add(readQName());
351 return SchemaPath.create(qnames.build(), absolute);
355 public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
356 return readYangInstanceIdentifierInternal();
359 private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
360 int size = input.readInt();
361 final Builder<PathArgument> pathArguments = ImmutableList.builderWithExpectedSize(size);
362 for (int i = 0; i < size; i++) {
363 pathArguments.add(readPathArgument());
365 return YangInstanceIdentifier.create(pathArguments.build());
368 private Set<String> readObjSet() throws IOException {
369 int count = input.readInt();
370 Set<String> children = new HashSet<>(count);
371 for (int i = 0; i < count; i++) {
372 children.add(readCodedString());
378 public PathArgument readPathArgument() throws IOException {
380 int type = input.readByte();
383 case PathArgumentTypes.AUGMENTATION_IDENTIFIER:
384 return readAugmentationIdentifier();
385 case PathArgumentTypes.NODE_IDENTIFIER:
386 return readNodeIdentifier();
387 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES:
388 return readNormalizedNodeWithPredicates();
389 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE:
390 return new NodeWithValue<>(readQName(), readObject());
392 // FIXME: throw hard error
397 @SuppressWarnings("unchecked")
398 private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(final QName nodeType,
399 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
401 LOG.trace("Reading children of leaf set");
403 lastLeafSetQName = nodeType;
405 LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
407 while (child != null) {
408 builder.withChild(child);
409 child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
414 @SuppressWarnings({ "unchecked", "rawtypes" })
415 private NormalizedNodeContainerBuilder addDataContainerChildren(
416 final NormalizedNodeContainerBuilder builder) throws IOException {
417 LOG.trace("Reading data container (leaf nodes) nodes");
419 NormalizedNode<?, ?> child = readNormalizedNodeInternal();
421 while (child != null) {
422 builder.addChild(child);
423 child = readNormalizedNodeInternal();