2 * Copyright (c) 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 com.google.common.base.Preconditions;
11 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
12 import java.io.DataOutput;
13 import java.io.IOException;
14 import java.io.OutputStream;
15 import java.io.StringWriter;
16 import java.nio.charset.StandardCharsets;
17 import java.util.Collection;
20 import javax.xml.transform.TransformerException;
21 import javax.xml.transform.TransformerFactory;
22 import javax.xml.transform.TransformerFactoryConfigurationError;
23 import javax.xml.transform.dom.DOMSource;
24 import javax.xml.transform.stream.StreamResult;
25 import org.opendaylight.yangtools.yang.common.QName;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
32 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
34 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
35 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
39 abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOutput, NormalizedNodeStreamWriter {
40 private static final Logger LOG = LoggerFactory.getLogger(AbstractNormalizedNodeDataOutput.class);
42 private final DataOutput output;
44 private NormalizedNodeWriter normalizedNodeWriter;
45 private boolean headerWritten;
46 private QName lastLeafSetQName;
47 private boolean inSimple;
49 AbstractNormalizedNodeDataOutput(final DataOutput output) {
50 this.output = Preconditions.checkNotNull(output);
53 private void ensureHeaderWritten() throws IOException {
55 output.writeByte(TokenTypes.SIGNATURE_MARKER);
56 output.writeShort(streamVersion());
61 protected abstract short streamVersion();
63 protected abstract void writeQName(QName qname) throws IOException;
65 protected abstract void writeString(String string) throws IOException;
68 public final void write(final int value) throws IOException {
69 ensureHeaderWritten();
74 public final void write(final byte[] bytes) throws IOException {
75 ensureHeaderWritten();
80 public final void write(final byte[] bytes, final int off, final int len) throws IOException {
81 ensureHeaderWritten();
82 output.write(bytes, off, len);
86 public final void writeBoolean(final boolean value) throws IOException {
87 ensureHeaderWritten();
88 output.writeBoolean(value);
92 public final void writeByte(final int value) throws IOException {
93 ensureHeaderWritten();
94 output.writeByte(value);
98 public final void writeShort(final int value) throws IOException {
99 ensureHeaderWritten();
100 output.writeShort(value);
104 public final void writeChar(final int value) throws IOException {
105 ensureHeaderWritten();
106 output.writeChar(value);
110 public final void writeInt(final int value) throws IOException {
111 ensureHeaderWritten();
112 output.writeInt(value);
116 public final void writeLong(final long value) throws IOException {
117 ensureHeaderWritten();
118 output.writeLong(value);
122 public final void writeFloat(final float value) throws IOException {
123 ensureHeaderWritten();
124 output.writeFloat(value);
128 public final void writeDouble(final double value) throws IOException {
129 ensureHeaderWritten();
130 output.writeDouble(value);
134 public final void writeBytes(final String str) throws IOException {
135 ensureHeaderWritten();
136 output.writeBytes(str);
140 public final void writeChars(final String str) throws IOException {
141 ensureHeaderWritten();
142 output.writeChars(str);
146 public final void writeUTF(final String str) throws IOException {
147 ensureHeaderWritten();
148 output.writeUTF(str);
151 private NormalizedNodeWriter normalizedNodeWriter() {
152 if (normalizedNodeWriter == null) {
153 normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(this);
156 return normalizedNodeWriter;
160 public void writeNormalizedNode(final NormalizedNode<?, ?> node) throws IOException {
161 ensureHeaderWritten();
162 normalizedNodeWriter().write(node);
166 public void startLeafNode(final NodeIdentifier name) throws IOException {
167 Preconditions.checkNotNull(name, "Node identifier should not be null");
168 LOG.trace("Starting a new leaf node");
169 startNode(name.getNodeType(), NodeTypes.LEAF_NODE);
174 public void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
175 Preconditions.checkNotNull(name, "Node identifier should not be null");
176 LOG.trace("Starting a new leaf set");
178 lastLeafSetQName = name.getNodeType();
179 startNode(name.getNodeType(), NodeTypes.LEAF_SET);
183 public void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
184 Preconditions.checkNotNull(name, "Node identifier should not be null");
185 LOG.trace("Starting a new ordered leaf set");
187 lastLeafSetQName = name.getNodeType();
188 startNode(name.getNodeType(), NodeTypes.ORDERED_LEAF_SET);
192 public void startLeafSetEntryNode(final NodeWithValue<?> name) throws IOException {
193 LOG.trace("Starting a new leaf set entry node");
195 output.writeByte(NodeTypes.LEAF_SET_ENTRY_NODE);
197 // lastLeafSetQName is set if the parent LeafSetNode was previously written. Otherwise this is a
198 // stand alone LeafSetEntryNode so write out it's name here.
199 if (lastLeafSetQName == null) {
200 writeQName(name.getNodeType());
206 public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
207 Preconditions.checkNotNull(name, "Node identifier should not be null");
209 LOG.trace("Starting a new container node");
211 startNode(name.getNodeType(), NodeTypes.CONTAINER_NODE);
215 public void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
216 Preconditions.checkNotNull(name, "Node identifier should not be null");
218 LOG.trace("Starting a new yang modeled anyXml node");
220 startNode(name.getNodeType(), NodeTypes.YANG_MODELED_ANY_XML_NODE);
224 public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
225 Preconditions.checkNotNull(name, "Node identifier should not be null");
226 LOG.trace("Starting a new unkeyed list");
228 startNode(name.getNodeType(), NodeTypes.UNKEYED_LIST);
232 public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
233 Preconditions.checkNotNull(name, "Node identifier should not be null");
234 LOG.trace("Starting a new unkeyed list item");
236 startNode(name.getNodeType(), NodeTypes.UNKEYED_LIST_ITEM);
240 public void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
241 Preconditions.checkNotNull(name, "Node identifier should not be null");
242 LOG.trace("Starting a new map node");
244 startNode(name.getNodeType(), NodeTypes.MAP_NODE);
248 public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
250 Preconditions.checkNotNull(identifier, "Node identifier should not be null");
251 LOG.trace("Starting a new map entry node");
252 startNode(identifier.getNodeType(), NodeTypes.MAP_ENTRY_NODE);
254 writeKeyValueMap(identifier.getKeyValues());
258 public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
259 Preconditions.checkNotNull(name, "Node identifier should not be null");
260 LOG.trace("Starting a new ordered map node");
262 startNode(name.getNodeType(), NodeTypes.ORDERED_MAP_NODE);
266 public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
267 Preconditions.checkNotNull(name, "Node identifier should not be null");
268 LOG.trace("Starting a new choice node");
270 startNode(name.getNodeType(), NodeTypes.CHOICE_NODE);
274 public void startAugmentationNode(final AugmentationIdentifier identifier) throws IOException {
275 Preconditions.checkNotNull(identifier, "Node identifier should not be null");
276 LOG.trace("Starting a new augmentation node");
278 output.writeByte(NodeTypes.AUGMENTATION_NODE);
279 writeAugmentationIdentifier(identifier);
283 public void startAnyxmlNode(final NodeIdentifier name) throws IOException {
284 Preconditions.checkNotNull(name, "Node identifier should not be null");
285 LOG.trace("Starting any xml node");
286 startNode(name.getNodeType(), NodeTypes.ANY_XML_NODE);
291 public void scalarValue(final Object value) throws IOException {
296 public void domSourceValue(final DOMSource value) throws IOException {
298 StreamResult xmlOutput = new StreamResult(new StringWriter());
299 TransformerFactory.newInstance().newTransformer().transform(value, xmlOutput);
300 writeObject(xmlOutput.getWriter().toString());
301 } catch (TransformerException | TransformerFactoryConfigurationError e) {
302 throw new IOException("Error writing anyXml", e);
307 public void endNode() throws IOException {
308 LOG.trace("Ending the node");
310 lastLeafSetQName = null;
311 output.writeByte(NodeTypes.END_NODE);
317 public void close() throws IOException {
322 public void flush() throws IOException {
323 if (output instanceof OutputStream) {
324 ((OutputStream)output).flush();
328 private void startNode(final QName qname, final byte nodeType) throws IOException {
329 Preconditions.checkNotNull(qname, "QName of node identifier should not be null.");
330 Preconditions.checkState(!inSimple, "Attempted to start a child in a simple node");
332 ensureHeaderWritten();
334 // First write the type of node
335 output.writeByte(nodeType);
340 private void writeObjSet(final Set<?> set) throws IOException {
341 output.writeInt(set.size());
342 for (Object o : set) {
343 Preconditions.checkArgument(o instanceof String, "Expected value type to be String but was %s (%s)",
346 writeString((String) o);
351 public void writeSchemaPath(final SchemaPath path) throws IOException {
352 ensureHeaderWritten();
353 output.writeBoolean(path.isAbsolute());
355 final Collection<QName> qnames = path.getPath();
356 output.writeInt(qnames.size());
357 for (QName qname : qnames) {
363 public void writeYangInstanceIdentifier(final YangInstanceIdentifier identifier) throws IOException {
364 ensureHeaderWritten();
365 writeYangInstanceIdentifierInternal(identifier);
368 private void writeYangInstanceIdentifierInternal(final YangInstanceIdentifier identifier) throws IOException {
369 Collection<PathArgument> pathArguments = identifier.getPathArguments();
370 output.writeInt(pathArguments.size());
372 for (PathArgument pathArgument : pathArguments) {
373 writePathArgument(pathArgument);
377 @SuppressFBWarnings(value = "BC_UNCONFIRMED_CAST",
378 justification = "The casts in the switch clauses are indirectly confirmed via the determination of 'type'.")
380 public void writePathArgument(final PathArgument pathArgument) throws IOException {
382 byte type = PathArgumentTypes.getSerializablePathArgumentType(pathArgument);
384 output.writeByte(type);
387 case PathArgumentTypes.NODE_IDENTIFIER:
389 NodeIdentifier nodeIdentifier = (NodeIdentifier) pathArgument;
391 writeQName(nodeIdentifier.getNodeType());
394 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES:
396 NodeIdentifierWithPredicates nodeIdentifierWithPredicates =
397 (NodeIdentifierWithPredicates) pathArgument;
398 writeQName(nodeIdentifierWithPredicates.getNodeType());
400 writeKeyValueMap(nodeIdentifierWithPredicates.getKeyValues());
403 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
405 NodeWithValue<?> nodeWithValue = (NodeWithValue<?>) pathArgument;
407 writeQName(nodeWithValue.getNodeType());
408 writeObject(nodeWithValue.getValue());
411 case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
413 // No Qname in augmentation identifier
414 writeAugmentationIdentifier((AugmentationIdentifier) pathArgument);
417 throw new IllegalStateException("Unknown node identifier type is found : "
418 + pathArgument.getClass().toString());
422 private void writeKeyValueMap(final Map<QName, Object> keyValueMap) throws IOException {
423 if (keyValueMap != null && !keyValueMap.isEmpty()) {
424 output.writeInt(keyValueMap.size());
426 for (Map.Entry<QName, Object> entry : keyValueMap.entrySet()) {
427 writeQName(entry.getKey());
428 writeObject(entry.getValue());
435 void writeAugmentationIdentifier(final AugmentationIdentifier aid) throws IOException {
436 final Set<QName> qnames = aid.getPossibleChildNames();
437 // Write each child's qname separately, if list is empty send count as 0
438 if (!qnames.isEmpty()) {
439 output.writeInt(qnames.size());
440 for (QName qname : qnames) {
444 LOG.debug("augmentation node does not have any child");
449 private void writeObject(final Object value) throws IOException {
451 byte type = ValueTypes.getSerializableType(value);
452 // Write object type first
453 output.writeByte(type);
456 case ValueTypes.BOOL_TYPE:
457 output.writeBoolean((Boolean) value);
459 case ValueTypes.QNAME_TYPE:
460 writeQName((QName) value);
462 case ValueTypes.INT_TYPE:
463 output.writeInt((Integer) value);
465 case ValueTypes.BYTE_TYPE:
466 output.writeByte((Byte) value);
468 case ValueTypes.LONG_TYPE:
469 output.writeLong((Long) value);
471 case ValueTypes.SHORT_TYPE:
472 output.writeShort((Short) value);
474 case ValueTypes.BITS_TYPE:
475 writeObjSet((Set<?>) value);
477 case ValueTypes.BINARY_TYPE:
478 byte[] bytes = (byte[]) value;
479 output.writeInt(bytes.length);
482 case ValueTypes.YANG_IDENTIFIER_TYPE:
483 writeYangInstanceIdentifierInternal((YangInstanceIdentifier) value);
485 case ValueTypes.EMPTY_TYPE:
487 case ValueTypes.STRING_BYTES_TYPE:
488 final byte[] valueBytes = value.toString().getBytes(StandardCharsets.UTF_8);
489 output.writeInt(valueBytes.length);
490 output.write(valueBytes);
493 output.writeUTF(value.toString());