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;
18 import java.util.Map.Entry;
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 writeString(String string) throws IOException;
66 public final void write(final int value) throws IOException {
67 ensureHeaderWritten();
72 public final void write(final byte[] bytes) throws IOException {
73 ensureHeaderWritten();
78 public final void write(final byte[] bytes, final int off, final int len) throws IOException {
79 ensureHeaderWritten();
80 output.write(bytes, off, len);
84 public final void writeBoolean(final boolean value) throws IOException {
85 ensureHeaderWritten();
86 output.writeBoolean(value);
90 public final void writeByte(final int value) throws IOException {
91 ensureHeaderWritten();
92 output.writeByte(value);
96 public final void writeShort(final int value) throws IOException {
97 ensureHeaderWritten();
98 output.writeShort(value);
102 public final void writeChar(final int value) throws IOException {
103 ensureHeaderWritten();
104 output.writeChar(value);
108 public final void writeInt(final int value) throws IOException {
109 ensureHeaderWritten();
110 output.writeInt(value);
114 public final void writeLong(final long value) throws IOException {
115 ensureHeaderWritten();
116 output.writeLong(value);
120 public final void writeFloat(final float value) throws IOException {
121 ensureHeaderWritten();
122 output.writeFloat(value);
126 public final void writeDouble(final double value) throws IOException {
127 ensureHeaderWritten();
128 output.writeDouble(value);
132 public final void writeBytes(final String str) throws IOException {
133 ensureHeaderWritten();
134 output.writeBytes(str);
138 public final void writeChars(final String str) throws IOException {
139 ensureHeaderWritten();
140 output.writeChars(str);
144 public final void writeUTF(final String str) throws IOException {
145 ensureHeaderWritten();
146 output.writeUTF(str);
149 private NormalizedNodeWriter normalizedNodeWriter() {
150 if (normalizedNodeWriter == null) {
151 normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(this);
154 return normalizedNodeWriter;
158 public void writeNormalizedNode(final NormalizedNode<?, ?> node) throws IOException {
159 ensureHeaderWritten();
160 normalizedNodeWriter().write(node);
164 public void startLeafNode(final NodeIdentifier name) throws IOException {
165 Preconditions.checkNotNull(name, "Node identifier should not be null");
166 LOG.trace("Starting a new leaf node");
167 startNode(name.getNodeType(), NodeTypes.LEAF_NODE);
172 public void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
173 Preconditions.checkNotNull(name, "Node identifier should not be null");
174 LOG.trace("Starting a new leaf set");
176 lastLeafSetQName = name.getNodeType();
177 startNode(name.getNodeType(), NodeTypes.LEAF_SET);
181 public void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
182 Preconditions.checkNotNull(name, "Node identifier should not be null");
183 LOG.trace("Starting a new ordered leaf set");
185 lastLeafSetQName = name.getNodeType();
186 startNode(name.getNodeType(), NodeTypes.ORDERED_LEAF_SET);
190 public void startLeafSetEntryNode(final NodeWithValue<?> name) throws IOException {
191 LOG.trace("Starting a new leaf set entry node");
193 output.writeByte(NodeTypes.LEAF_SET_ENTRY_NODE);
195 // lastLeafSetQName is set if the parent LeafSetNode was previously written. Otherwise this is a
196 // stand alone LeafSetEntryNode so write out it's name here.
197 if (lastLeafSetQName == null) {
198 writeQName(name.getNodeType());
204 public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
205 Preconditions.checkNotNull(name, "Node identifier should not be null");
207 LOG.trace("Starting a new container node");
209 startNode(name.getNodeType(), NodeTypes.CONTAINER_NODE);
213 public void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
214 Preconditions.checkNotNull(name, "Node identifier should not be null");
216 LOG.trace("Starting a new yang modeled anyXml node");
218 startNode(name.getNodeType(), NodeTypes.YANG_MODELED_ANY_XML_NODE);
222 public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
223 Preconditions.checkNotNull(name, "Node identifier should not be null");
224 LOG.trace("Starting a new unkeyed list");
226 startNode(name.getNodeType(), NodeTypes.UNKEYED_LIST);
230 public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
231 Preconditions.checkNotNull(name, "Node identifier should not be null");
232 LOG.trace("Starting a new unkeyed list item");
234 startNode(name.getNodeType(), NodeTypes.UNKEYED_LIST_ITEM);
238 public void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
239 Preconditions.checkNotNull(name, "Node identifier should not be null");
240 LOG.trace("Starting a new map node");
242 startNode(name.getNodeType(), NodeTypes.MAP_NODE);
246 public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
248 Preconditions.checkNotNull(identifier, "Node identifier should not be null");
249 LOG.trace("Starting a new map entry node");
250 startNode(identifier.getNodeType(), NodeTypes.MAP_ENTRY_NODE);
252 writeKeyValueMap(identifier.entrySet());
256 public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
257 Preconditions.checkNotNull(name, "Node identifier should not be null");
258 LOG.trace("Starting a new ordered map node");
260 startNode(name.getNodeType(), NodeTypes.ORDERED_MAP_NODE);
264 public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
265 Preconditions.checkNotNull(name, "Node identifier should not be null");
266 LOG.trace("Starting a new choice node");
268 startNode(name.getNodeType(), NodeTypes.CHOICE_NODE);
272 public void startAugmentationNode(final AugmentationIdentifier identifier) throws IOException {
273 Preconditions.checkNotNull(identifier, "Node identifier should not be null");
274 LOG.trace("Starting a new augmentation node");
276 output.writeByte(NodeTypes.AUGMENTATION_NODE);
277 writeAugmentationIdentifier(identifier);
281 public void startAnyxmlNode(final NodeIdentifier name) throws IOException {
282 Preconditions.checkNotNull(name, "Node identifier should not be null");
283 LOG.trace("Starting any xml node");
284 startNode(name.getNodeType(), NodeTypes.ANY_XML_NODE);
289 public void scalarValue(final Object value) throws IOException {
294 public void domSourceValue(final DOMSource value) throws IOException {
296 StreamResult xmlOutput = new StreamResult(new StringWriter());
297 TransformerFactory.newInstance().newTransformer().transform(value, xmlOutput);
298 writeObject(xmlOutput.getWriter().toString());
299 } catch (TransformerException | TransformerFactoryConfigurationError e) {
300 throw new IOException("Error writing anyXml", e);
305 public void endNode() throws IOException {
306 LOG.trace("Ending the node");
308 lastLeafSetQName = null;
309 output.writeByte(NodeTypes.END_NODE);
315 public void close() throws IOException {
320 public void flush() throws IOException {
321 if (output instanceof OutputStream) {
322 ((OutputStream)output).flush();
326 private void startNode(final QName qname, final byte nodeType) throws IOException {
327 Preconditions.checkNotNull(qname, "QName of node identifier should not be null.");
328 Preconditions.checkState(!inSimple, "Attempted to start a child in a simple node");
330 ensureHeaderWritten();
332 // First write the type of node
333 output.writeByte(nodeType);
338 private void writeObjSet(final Set<?> set) throws IOException {
339 output.writeInt(set.size());
340 for (Object o : set) {
341 Preconditions.checkArgument(o instanceof String, "Expected value type to be String but was %s (%s)",
344 writeString((String) o);
349 public void writeSchemaPath(final SchemaPath path) throws IOException {
350 ensureHeaderWritten();
351 output.writeBoolean(path.isAbsolute());
353 final Collection<QName> qnames = path.getPath();
354 output.writeInt(qnames.size());
355 for (QName qname : qnames) {
361 public void writeYangInstanceIdentifier(final YangInstanceIdentifier identifier) throws IOException {
362 ensureHeaderWritten();
363 writeYangInstanceIdentifierInternal(identifier);
366 private void writeYangInstanceIdentifierInternal(final YangInstanceIdentifier identifier) throws IOException {
367 Collection<PathArgument> pathArguments = identifier.getPathArguments();
368 output.writeInt(pathArguments.size());
370 for (PathArgument pathArgument : pathArguments) {
371 writePathArgument(pathArgument);
375 @SuppressFBWarnings(value = "BC_UNCONFIRMED_CAST",
376 justification = "The casts in the switch clauses are indirectly confirmed via the determination of 'type'.")
378 public void writePathArgument(final PathArgument pathArgument) throws IOException {
380 byte type = PathArgumentTypes.getSerializablePathArgumentType(pathArgument);
382 output.writeByte(type);
385 case PathArgumentTypes.NODE_IDENTIFIER:
387 NodeIdentifier nodeIdentifier = (NodeIdentifier) pathArgument;
389 writeQName(nodeIdentifier.getNodeType());
392 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES:
394 NodeIdentifierWithPredicates nodeIdentifierWithPredicates =
395 (NodeIdentifierWithPredicates) pathArgument;
396 writeQName(nodeIdentifierWithPredicates.getNodeType());
398 writeKeyValueMap(nodeIdentifierWithPredicates.entrySet());
401 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
403 NodeWithValue<?> nodeWithValue = (NodeWithValue<?>) pathArgument;
405 writeQName(nodeWithValue.getNodeType());
406 writeObject(nodeWithValue.getValue());
409 case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
411 // No Qname in augmentation identifier
412 writeAugmentationIdentifier((AugmentationIdentifier) pathArgument);
415 throw new IllegalStateException("Unknown node identifier type is found : "
416 + pathArgument.getClass().toString());
420 private void writeKeyValueMap(final Set<Entry<QName, Object>> entrySet) throws IOException {
421 if (!entrySet.isEmpty()) {
422 output.writeInt(entrySet.size());
423 for (Entry<QName, Object> entry : entrySet) {
424 writeQName(entry.getKey());
425 writeObject(entry.getValue());
432 void writeAugmentationIdentifier(final AugmentationIdentifier aid) throws IOException {
433 final Set<QName> qnames = aid.getPossibleChildNames();
434 // Write each child's qname separately, if list is empty send count as 0
435 if (!qnames.isEmpty()) {
436 output.writeInt(qnames.size());
437 for (QName qname : qnames) {
441 LOG.debug("augmentation node does not have any child");
446 private void writeObject(final Object value) throws IOException {
448 byte type = ValueTypes.getSerializableType(value);
449 // Write object type first
450 output.writeByte(type);
453 case ValueTypes.BOOL_TYPE:
454 output.writeBoolean((Boolean) value);
456 case ValueTypes.QNAME_TYPE:
457 writeQName((QName) value);
459 case ValueTypes.INT_TYPE:
460 output.writeInt((Integer) value);
462 case ValueTypes.BYTE_TYPE:
463 output.writeByte((Byte) value);
465 case ValueTypes.LONG_TYPE:
466 output.writeLong((Long) value);
468 case ValueTypes.SHORT_TYPE:
469 output.writeShort((Short) value);
471 case ValueTypes.BITS_TYPE:
472 writeObjSet((Set<?>) value);
474 case ValueTypes.BINARY_TYPE:
475 byte[] bytes = (byte[]) value;
476 output.writeInt(bytes.length);
479 case ValueTypes.YANG_IDENTIFIER_TYPE:
480 writeYangInstanceIdentifierInternal((YangInstanceIdentifier) value);
482 case ValueTypes.EMPTY_TYPE:
484 case ValueTypes.STRING_BYTES_TYPE:
485 final byte[] valueBytes = value.toString().getBytes(StandardCharsets.UTF_8);
486 output.writeInt(valueBytes.length);
487 output.write(valueBytes);
490 output.writeUTF(value.toString());