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 static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
14 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
15 import java.io.DataOutput;
16 import java.io.IOException;
17 import java.io.OutputStream;
18 import java.io.StringWriter;
19 import java.util.Collection;
20 import java.util.Map.Entry;
22 import javax.xml.transform.TransformerException;
23 import javax.xml.transform.TransformerFactory;
24 import javax.xml.transform.TransformerFactoryConfigurationError;
25 import javax.xml.transform.dom.DOMSource;
26 import javax.xml.transform.stream.StreamResult;
27 import org.eclipse.jdt.annotation.NonNull;
28 import org.opendaylight.yangtools.yang.common.QName;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
35 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
37 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
38 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
43 * NormalizedNodeOutputStreamWriter will be used by distributed datastore to send normalized node in
45 * A stream writer wrapper around this class will write node objects to stream in recursive manner.
46 * for example - If you have a ContainerNode which has a two LeafNode as children, then
48 * {@link #startContainerNode(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier, int)},
50 * {@link #leafNode(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier, Object)} twice
51 * and then, {@link #endNode()} to end container node.
53 * <p>Based on the each node, the node type is also written to the stream, that helps in reconstructing the object,
56 abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOutput, NormalizedNodeStreamWriter {
57 private static final Logger LOG = LoggerFactory.getLogger(AbstractNormalizedNodeDataOutput.class);
59 private final DataOutput output;
61 private NormalizedNodeWriter normalizedNodeWriter;
62 private boolean headerWritten;
63 private QName lastLeafSetQName;
64 private boolean inSimple;
66 AbstractNormalizedNodeDataOutput(final DataOutput output) {
67 this.output = requireNonNull(output);
70 private void ensureHeaderWritten() throws IOException {
72 output.writeByte(TokenTypes.SIGNATURE_MARKER);
73 output.writeShort(streamVersion());
79 public final void write(final int value) throws IOException {
80 ensureHeaderWritten();
85 public final void write(final byte[] bytes) throws IOException {
86 ensureHeaderWritten();
91 public final void write(final byte[] bytes, final int off, final int len) throws IOException {
92 ensureHeaderWritten();
93 output.write(bytes, off, len);
97 public final void writeBoolean(final boolean value) throws IOException {
98 ensureHeaderWritten();
99 output.writeBoolean(value);
103 public final void writeByte(final int value) throws IOException {
104 ensureHeaderWritten();
105 output.writeByte(value);
109 public final void writeShort(final int value) throws IOException {
110 ensureHeaderWritten();
111 output.writeShort(value);
115 public final void writeChar(final int value) throws IOException {
116 ensureHeaderWritten();
117 output.writeChar(value);
121 public final void writeInt(final int value) throws IOException {
122 ensureHeaderWritten();
123 output.writeInt(value);
127 public final void writeLong(final long value) throws IOException {
128 ensureHeaderWritten();
129 output.writeLong(value);
133 public final void writeFloat(final float value) throws IOException {
134 ensureHeaderWritten();
135 output.writeFloat(value);
139 public final void writeDouble(final double value) throws IOException {
140 ensureHeaderWritten();
141 output.writeDouble(value);
145 public final void writeBytes(final String str) throws IOException {
146 ensureHeaderWritten();
147 output.writeBytes(str);
151 public final void writeChars(final String str) throws IOException {
152 ensureHeaderWritten();
153 output.writeChars(str);
157 public final void writeUTF(final String str) throws IOException {
158 ensureHeaderWritten();
159 output.writeUTF(str);
163 public final void writeQName(final QName qname) throws IOException {
164 ensureHeaderWritten();
165 writeQNameInternal(qname);
169 public final void writeNormalizedNode(final NormalizedNode<?, ?> node) throws IOException {
170 ensureHeaderWritten();
171 if (normalizedNodeWriter == null) {
172 normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(this);
174 normalizedNodeWriter.write(node);
178 public final void writePathArgument(final PathArgument pathArgument) throws IOException {
179 ensureHeaderWritten();
180 writePathArgumentInternal(pathArgument);
184 public final void writeYangInstanceIdentifier(final YangInstanceIdentifier identifier) throws IOException {
185 ensureHeaderWritten();
186 writeYangInstanceIdentifierInternal(identifier);
190 public final void writeSchemaPath(final SchemaPath path) throws IOException {
191 ensureHeaderWritten();
192 output.writeBoolean(path.isAbsolute());
194 final Collection<QName> qnames = path.getPath();
195 output.writeInt(qnames.size());
196 for (QName qname : qnames) {
197 writeQNameInternal(qname);
202 public final void close() throws IOException {
207 public void startLeafNode(final NodeIdentifier name) throws IOException {
208 LOG.trace("Starting a new leaf node");
209 startNode(name, NodeTypes.LEAF_NODE);
214 public void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
215 LOG.trace("Starting a new leaf set");
216 commonStartLeafSet(name, NodeTypes.LEAF_SET);
220 public void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
221 LOG.trace("Starting a new ordered leaf set");
222 commonStartLeafSet(name, NodeTypes.ORDERED_LEAF_SET);
225 private void commonStartLeafSet(final NodeIdentifier name, final byte nodeType) throws IOException {
226 startNode(name, nodeType);
227 lastLeafSetQName = name.getNodeType();
231 public void startLeafSetEntryNode(final NodeWithValue<?> name) throws IOException {
232 LOG.trace("Starting a new leaf set entry node");
234 output.writeByte(NodeTypes.LEAF_SET_ENTRY_NODE);
236 // lastLeafSetQName is set if the parent LeafSetNode was previously written. Otherwise this is a
237 // stand alone LeafSetEntryNode so write out it's name here.
238 if (lastLeafSetQName == null) {
239 writeQNameInternal(name.getNodeType());
245 public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
246 LOG.trace("Starting a new container node");
247 startNode(name, NodeTypes.CONTAINER_NODE);
251 public void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
252 LOG.trace("Starting a new yang modeled anyXml node");
253 startNode(name, NodeTypes.YANG_MODELED_ANY_XML_NODE);
257 public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
258 LOG.trace("Starting a new unkeyed list");
259 startNode(name, NodeTypes.UNKEYED_LIST);
263 public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
264 LOG.trace("Starting a new unkeyed list item");
265 startNode(name, NodeTypes.UNKEYED_LIST_ITEM);
269 public void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
270 LOG.trace("Starting a new map node");
271 startNode(name, NodeTypes.MAP_NODE);
275 public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
277 LOG.trace("Starting a new map entry node");
278 startNode(identifier, NodeTypes.MAP_ENTRY_NODE);
279 writeKeyValueMap(identifier.entrySet());
283 public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
284 LOG.trace("Starting a new ordered map node");
285 startNode(name, NodeTypes.ORDERED_MAP_NODE);
289 public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
290 LOG.trace("Starting a new choice node");
291 startNode(name, NodeTypes.CHOICE_NODE);
295 public void startAugmentationNode(final AugmentationIdentifier identifier) throws IOException {
296 requireNonNull(identifier, "Node identifier should not be null");
297 LOG.trace("Starting a new augmentation node");
299 output.writeByte(NodeTypes.AUGMENTATION_NODE);
300 writeAugmentationIdentifier(identifier);
304 public void startAnyxmlNode(final NodeIdentifier name) throws IOException {
305 LOG.trace("Starting any xml node");
306 startNode(name, NodeTypes.ANY_XML_NODE);
311 public void scalarValue(final Object value) throws IOException {
316 public void domSourceValue(final DOMSource value) throws IOException {
318 StreamResult xmlOutput = new StreamResult(new StringWriter());
319 TransformerFactory.newInstance().newTransformer().transform(value, xmlOutput);
320 writeObject(xmlOutput.getWriter().toString());
321 } catch (TransformerException | TransformerFactoryConfigurationError e) {
322 throw new IOException("Error writing anyXml", e);
327 public void endNode() throws IOException {
328 LOG.trace("Ending the node");
330 lastLeafSetQName = null;
331 output.writeByte(NodeTypes.END_NODE);
337 public void flush() throws IOException {
338 if (output instanceof OutputStream) {
339 ((OutputStream)output).flush();
343 private void startNode(final PathArgument arg, final byte nodeType) throws IOException {
344 requireNonNull(arg, "Node identifier should not be null");
345 checkState(!inSimple, "Attempted to start a child in a simple node");
347 ensureHeaderWritten();
349 // First write the type of node
350 output.writeByte(nodeType);
352 writeQNameInternal(arg.getNodeType());
355 final void writeObjSet(final Set<?> set) throws IOException {
356 output.writeInt(set.size());
357 for (Object o : set) {
358 checkArgument(o instanceof String, "Expected value type to be String but was %s (%s)", o.getClass(), o);
359 writeString((String) o);
363 final void writeYangInstanceIdentifierInternal(final YangInstanceIdentifier identifier) throws IOException {
364 Collection<PathArgument> pathArguments = identifier.getPathArguments();
365 output.writeInt(pathArguments.size());
367 for (PathArgument pathArgument : pathArguments) {
368 writePathArgumentInternal(pathArgument);
372 @SuppressFBWarnings(value = "BC_UNCONFIRMED_CAST",
373 justification = "The casts in the switch clauses are indirectly confirmed via the determination of 'type'.")
374 final void writePathArgumentInternal(final PathArgument pathArgument) throws IOException {
375 final byte type = PathArgumentTypes.getSerializablePathArgumentType(pathArgument);
376 output.writeByte(type);
379 case PathArgumentTypes.NODE_IDENTIFIER:
380 NodeIdentifier nodeIdentifier = (NodeIdentifier) pathArgument;
381 writeQNameInternal(nodeIdentifier.getNodeType());
383 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES:
384 NodeIdentifierWithPredicates nodeIdentifierWithPredicates =
385 (NodeIdentifierWithPredicates) pathArgument;
386 writeQNameInternal(nodeIdentifierWithPredicates.getNodeType());
387 writeKeyValueMap(nodeIdentifierWithPredicates.entrySet());
389 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE:
390 NodeWithValue<?> nodeWithValue = (NodeWithValue<?>) pathArgument;
391 writeQNameInternal(nodeWithValue.getNodeType());
392 writeObject(nodeWithValue.getValue());
394 case PathArgumentTypes.AUGMENTATION_IDENTIFIER:
395 // No Qname in augmentation identifier
396 writeAugmentationIdentifier((AugmentationIdentifier) pathArgument);
399 throw new IllegalStateException("Unknown node identifier type is found : "
400 + pathArgument.getClass().toString());
404 private void writeKeyValueMap(final Set<Entry<QName, Object>> entrySet) throws IOException {
405 if (!entrySet.isEmpty()) {
406 output.writeInt(entrySet.size());
407 for (Entry<QName, Object> entry : entrySet) {
408 writeQNameInternal(entry.getKey());
409 writeObject(entry.getValue());
416 final void defaultWriteAugmentationIdentifier(final @NonNull AugmentationIdentifier aid) throws IOException {
417 final Set<QName> qnames = aid.getPossibleChildNames();
418 // Write each child's qname separately, if list is empty send count as 0
419 if (!qnames.isEmpty()) {
420 output.writeInt(qnames.size());
421 for (QName qname : qnames) {
422 writeQNameInternal(qname);
425 LOG.debug("augmentation node does not have any child");
430 abstract short streamVersion();
432 abstract void writeString(@NonNull String string) throws IOException;
434 abstract void writeQNameInternal(@NonNull QName qname) throws IOException;
436 abstract void writeAugmentationIdentifier(@NonNull AugmentationIdentifier aid) throws IOException;
438 abstract void writeObject(@NonNull DataOutput output, @NonNull Object value) throws IOException;
440 private void writeObject(final Object value) throws IOException {
441 writeObject(output, value);