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 com.google.common.collect.Sets;
16 import java.io.DataInput;
17 import java.io.IOException;
18 import java.io.StringReader;
19 import java.math.BigDecimal;
20 import java.math.BigInteger;
21 import java.nio.charset.StandardCharsets;
22 import java.util.ArrayList;
23 import java.util.HashSet;
24 import java.util.List;
26 import javax.xml.parsers.DocumentBuilderFactory;
27 import javax.xml.parsers.ParserConfigurationException;
28 import javax.xml.transform.dom.DOMSource;
29 import org.eclipse.jdt.annotation.NonNull;
30 import org.opendaylight.controller.cluster.datastore.node.utils.QNameFactory;
31 import org.opendaylight.yangtools.util.ImmutableOffsetMapTemplate;
32 import org.opendaylight.yangtools.yang.common.Empty;
33 import org.opendaylight.yangtools.yang.common.QName;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
40 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
41 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.w3c.dom.Element;
45 import org.xml.sax.InputSource;
46 import org.xml.sax.SAXException;
49 * NormalizedNodeInputStreamReader reads the byte stream and constructs the normalized node including its children
50 * nodes. This process goes in recursive manner, where each NodeTypes object signifies the start of the object, except
51 * END_NODE. If a node can have children, then that node's end is calculated based on appearance of END_NODE.
53 abstract class AbstractLithiumDataInput extends ForwardingDataInput implements NormalizedNodeDataInput {
55 private static final Logger LOG = LoggerFactory.getLogger(AbstractLithiumDataInput.class);
57 private final @NonNull DataInput input;
59 private final List<String> codedStringMap = new ArrayList<>();
61 private QName lastLeafSetQName;
63 AbstractLithiumDataInput(final DataInput input) {
64 this.input = requireNonNull(input);
68 final DataInput delegate() {
73 public final void streamNormalizedNode(final NormalizedNodeStreamWriter writer) throws IOException {
74 streamNormalizedNode(requireNonNull(writer), input.readByte());
77 private void streamNormalizedNode(final NormalizedNodeStreamWriter writer, final byte nodeType) throws IOException {
79 case NodeTypes.ANY_XML_NODE:
82 case NodeTypes.AUGMENTATION_NODE:
83 streamAugmentation(writer);
85 case NodeTypes.CHOICE_NODE:
88 case NodeTypes.CONTAINER_NODE:
89 streamContainer(writer);
91 case NodeTypes.LEAF_NODE:
94 case NodeTypes.LEAF_SET:
95 streamLeafSet(writer);
97 case NodeTypes.ORDERED_LEAF_SET:
98 streamOrderedLeafSet(writer);
100 case NodeTypes.LEAF_SET_ENTRY_NODE:
101 streamLeafSetEntry(writer);
103 case NodeTypes.MAP_ENTRY_NODE:
104 streamMapEntry(writer);
106 case NodeTypes.MAP_NODE:
109 case NodeTypes.ORDERED_MAP_NODE:
110 streamOrderedMap(writer);
112 case NodeTypes.UNKEYED_LIST:
113 streamUnkeyedList(writer);
115 case NodeTypes.UNKEYED_LIST_ITEM:
116 streamUnkeyedListItem(writer);
119 throw new InvalidNormalizedNodeStreamException("Unexpected node " + nodeType);
123 private void streamAnyxml(final NormalizedNodeStreamWriter writer) throws IOException {
124 final NodeIdentifier identifier = readNodeIdentifier();
125 LOG.trace("Streaming anyxml node {}", identifier);
126 writer.startAnyxmlNode(identifier);
127 writer.domSourceValue(readDOMSource());
131 private void streamAugmentation(final NormalizedNodeStreamWriter writer) throws IOException {
132 final AugmentationIdentifier augIdentifier = readAugmentationIdentifier();
133 LOG.trace("Streaming augmentation node {}", augIdentifier);
134 writer.startAugmentationNode(augIdentifier);
135 commonStreamContainer(writer);
138 private void streamChoice(final NormalizedNodeStreamWriter writer) throws IOException {
139 final NodeIdentifier identifier = readNodeIdentifier();
140 LOG.trace("Streaming choice node {}", identifier);
141 writer.startChoiceNode(identifier, NormalizedNodeStreamWriter.UNKNOWN_SIZE);
142 commonStreamContainer(writer);
145 private void streamContainer(final NormalizedNodeStreamWriter writer) throws IOException {
146 final NodeIdentifier identifier = readNodeIdentifier();
147 LOG.trace("Streaming container node {}", identifier);
148 writer.startContainerNode(identifier, NormalizedNodeStreamWriter.UNKNOWN_SIZE);
149 commonStreamContainer(writer);
152 private void streamLeaf(final NormalizedNodeStreamWriter writer) throws IOException {
154 endLeaf(writer, readObject());
157 // Leaf inside a MapEntryNode, it can potentially be a key leaf, in which case we want to de-duplicate values.
158 private void streamLeaf(final NormalizedNodeStreamWriter writer, final NodeIdentifierWithPredicates entryId)
160 final NodeIdentifier identifier = startLeaf(writer);
161 final Object value = readObject();
162 final Object entryValue = entryId.getValue(identifier.getNodeType());
163 endLeaf(writer, entryValue == null ? value : entryValue);
166 private NodeIdentifier startLeaf(final NormalizedNodeStreamWriter writer) throws IOException {
167 final NodeIdentifier identifier = readNodeIdentifier();
168 LOG.trace("Streaming leaf node {}", identifier);
169 writer.startLeafNode(identifier);
173 private static void endLeaf(final NormalizedNodeStreamWriter writer, final Object value) throws IOException {
174 writer.scalarValue(value);
178 private void streamLeafSet(final NormalizedNodeStreamWriter writer) throws IOException {
179 final NodeIdentifier identifier = readNodeIdentifier();
180 LOG.trace("Streaming leaf set node {}", identifier);
181 writer.startLeafSet(identifier, NormalizedNodeStreamWriter.UNKNOWN_SIZE);
182 commonStreamLeafSet(writer, identifier);
185 private void streamOrderedLeafSet(final NormalizedNodeStreamWriter writer) throws IOException {
186 final NodeIdentifier identifier = readNodeIdentifier();
187 LOG.trace("Streaming ordered leaf set node {}", identifier);
188 writer.startOrderedLeafSet(identifier, NormalizedNodeStreamWriter.UNKNOWN_SIZE);
189 commonStreamLeafSet(writer, identifier);
192 private void commonStreamLeafSet(final NormalizedNodeStreamWriter writer, final NodeIdentifier identifier)
194 lastLeafSetQName = identifier.getNodeType();
196 commonStreamContainer(writer);
198 // Make sure we never leak this
199 lastLeafSetQName = null;
203 private void streamLeafSetEntry(final NormalizedNodeStreamWriter writer) throws IOException {
204 final QName name = lastLeafSetQName != null ? lastLeafSetQName : readQName();
205 final Object value = readObject();
206 final NodeWithValue<Object> leafIdentifier = new NodeWithValue<>(name, value);
207 LOG.trace("Streaming leaf set entry node {}, value {}", leafIdentifier, value);
208 writer.startLeafSetEntryNode(leafIdentifier);
209 writer.scalarValue(value);
213 private void streamMap(final NormalizedNodeStreamWriter writer) throws IOException {
214 final NodeIdentifier identifier = readNodeIdentifier();
215 LOG.trace("Streaming map node {}", identifier);
216 writer.startMapNode(identifier, NormalizedNodeStreamWriter.UNKNOWN_SIZE);
217 commonStreamContainer(writer);
220 private void streamOrderedMap(final NormalizedNodeStreamWriter writer) throws IOException {
221 final NodeIdentifier identifier = readNodeIdentifier();
222 LOG.trace("Streaming ordered map node {}", identifier);
223 writer.startOrderedMapNode(identifier, NormalizedNodeStreamWriter.UNKNOWN_SIZE);
224 commonStreamContainer(writer);
227 private void streamMapEntry(final NormalizedNodeStreamWriter writer) throws IOException {
228 final NodeIdentifierWithPredicates entryIdentifier = readNormalizedNodeWithPredicates();
229 LOG.trace("Streaming map entry node {}", entryIdentifier);
230 writer.startMapEntryNode(entryIdentifier, NormalizedNodeStreamWriter.UNKNOWN_SIZE);
232 // Same loop as commonStreamContainer(), but ...
233 for (byte nodeType = input.readByte(); nodeType != NodeTypes.END_NODE; nodeType = input.readByte()) {
234 if (nodeType == NodeTypes.LEAF_NODE) {
235 // ... leaf nodes may need de-duplication
236 streamLeaf(writer, entryIdentifier);
238 streamNormalizedNode(writer, nodeType);
244 private void streamUnkeyedList(final NormalizedNodeStreamWriter writer) throws IOException {
245 final NodeIdentifier identifier = readNodeIdentifier();
246 LOG.trace("Streaming unkeyed list node {}", identifier);
247 writer.startUnkeyedList(identifier, NormalizedNodeStreamWriter.UNKNOWN_SIZE);
248 commonStreamContainer(writer);
251 private void streamUnkeyedListItem(final NormalizedNodeStreamWriter writer) throws IOException {
252 final NodeIdentifier identifier = readNodeIdentifier();
253 LOG.trace("Streaming unkeyed list item node {}", identifier);
254 writer.startUnkeyedListItem(identifier, NormalizedNodeStreamWriter.UNKNOWN_SIZE);
255 commonStreamContainer(writer);
258 private void commonStreamContainer(final NormalizedNodeStreamWriter writer) throws IOException {
259 for (byte nodeType = input.readByte(); nodeType != NodeTypes.END_NODE; nodeType = input.readByte()) {
260 streamNormalizedNode(writer, nodeType);
265 private DOMSource readDOMSource() throws IOException {
266 String xml = readObject().toString();
268 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
269 factory.setNamespaceAware(true);
270 Element node = factory.newDocumentBuilder().parse(
271 new InputSource(new StringReader(xml))).getDocumentElement();
272 return new DOMSource(node);
273 } catch (SAXException | ParserConfigurationException e) {
274 throw new IOException("Error parsing XML: " + xml, e);
278 final QName defaultReadQName() throws IOException {
279 // Read in the same sequence of writing
280 String localName = readCodedString();
281 String namespace = readCodedString();
282 String revision = Strings.emptyToNull(readCodedString());
284 return QNameFactory.create(localName, namespace, revision);
287 final String readCodedString() throws IOException {
288 final byte valueType = input.readByte();
290 case TokenTypes.IS_NULL_VALUE:
292 case TokenTypes.IS_CODE_VALUE:
293 final int code = input.readInt();
295 return codedStringMap.get(code);
296 } catch (IndexOutOfBoundsException e) {
297 throw new IOException("String code " + code + " was not found", e);
299 case TokenTypes.IS_STRING_VALUE:
300 final String value = input.readUTF().intern();
301 codedStringMap.add(value);
304 throw new IOException("Unhandled string value type " + valueType);
308 private Set<QName> readQNameSet() throws IOException {
309 // Read the children count
310 final int count = input.readInt();
311 final Set<QName> children = Sets.newHashSetWithExpectedSize(count);
312 for (int i = 0; i < count; i++) {
313 children.add(readQName());
318 abstract AugmentationIdentifier readAugmentationIdentifier() throws IOException;
320 abstract NodeIdentifier readNodeIdentifier() throws IOException;
322 final AugmentationIdentifier defaultReadAugmentationIdentifier() throws IOException {
323 return AugmentationIdentifier.create(readQNameSet());
326 private NodeIdentifierWithPredicates readNormalizedNodeWithPredicates() throws IOException {
327 final QName qname = readQName();
328 final int count = input.readInt();
331 return NodeIdentifierWithPredicates.of(qname);
333 return NodeIdentifierWithPredicates.of(qname, readQName(), readObject());
335 // ImmutableList is used by ImmutableOffsetMapTemplate for lookups, hence we use that.
336 final Builder<QName> keys = ImmutableList.builderWithExpectedSize(count);
337 final Object[] values = new Object[count];
338 for (int i = 0; i < count; i++) {
339 keys.add(readQName());
340 values[i] = readObject();
343 return NodeIdentifierWithPredicates.of(qname, ImmutableOffsetMapTemplate.ordered(keys.build())
344 .instantiateWithValues(values));
348 private Object readObject() throws IOException {
349 byte objectType = input.readByte();
350 switch (objectType) {
351 case ValueTypes.BITS_TYPE:
354 case ValueTypes.BOOL_TYPE:
355 return input.readBoolean();
357 case ValueTypes.BYTE_TYPE:
358 return input.readByte();
360 case ValueTypes.INT_TYPE:
361 return input.readInt();
363 case ValueTypes.LONG_TYPE:
364 return input.readLong();
366 case ValueTypes.QNAME_TYPE:
369 case ValueTypes.SHORT_TYPE:
370 return input.readShort();
372 case ValueTypes.STRING_TYPE:
373 return input.readUTF();
375 case ValueTypes.STRING_BYTES_TYPE:
376 return readStringBytes();
378 case ValueTypes.BIG_DECIMAL_TYPE:
379 return new BigDecimal(input.readUTF());
381 case ValueTypes.BIG_INTEGER_TYPE:
382 return new BigInteger(input.readUTF());
384 case ValueTypes.BINARY_TYPE:
385 byte[] bytes = new byte[input.readInt()];
386 input.readFully(bytes);
389 case ValueTypes.YANG_IDENTIFIER_TYPE:
390 return readYangInstanceIdentifierInternal();
392 case ValueTypes.EMPTY_TYPE:
393 // Leaf nodes no longer allow null values and thus we no longer emit null values. Previously, the "empty"
394 // yang type was represented as null so we translate an incoming null value to Empty. It was possible for
395 // a BI user to set a string leaf to null and we're rolling the dice here but the chances for that are
396 // very low. We'd have to know the yang type but, even if we did, we can't let a null value pass upstream
397 // so we'd have to drop the leaf which might cause other issues.
398 case ValueTypes.NULL_TYPE:
399 return Empty.getInstance();
406 private String readStringBytes() throws IOException {
407 byte[] bytes = new byte[input.readInt()];
408 input.readFully(bytes);
409 return new String(bytes, StandardCharsets.UTF_8);
413 public final SchemaPath readSchemaPath() throws IOException {
414 final boolean absolute = input.readBoolean();
415 final int size = input.readInt();
417 final Builder<QName> qnames = ImmutableList.builderWithExpectedSize(size);
418 for (int i = 0; i < size; ++i) {
419 qnames.add(readQName());
421 return SchemaPath.create(qnames.build(), absolute);
425 public final YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
426 return readYangInstanceIdentifierInternal();
429 private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
430 int size = input.readInt();
431 final Builder<PathArgument> pathArguments = ImmutableList.builderWithExpectedSize(size);
432 for (int i = 0; i < size; i++) {
433 pathArguments.add(readPathArgument());
435 return YangInstanceIdentifier.create(pathArguments.build());
438 private Set<String> readObjSet() throws IOException {
439 int count = input.readInt();
440 Set<String> children = new HashSet<>(count);
441 for (int i = 0; i < count; i++) {
442 children.add(readCodedString());
448 public final PathArgument readPathArgument() throws IOException {
450 int type = input.readByte();
453 case PathArgumentTypes.AUGMENTATION_IDENTIFIER:
454 return readAugmentationIdentifier();
455 case PathArgumentTypes.NODE_IDENTIFIER:
456 return readNodeIdentifier();
457 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES:
458 return readNormalizedNodeWithPredicates();
459 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE:
460 return new NodeWithValue<>(readQName(), readObject());
462 // FIXME: throw hard error