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 * Abstract base class for implementing {@link NormalizedNodeDataOutput} contract. This class uses
44 * {@link NormalizedNodeStreamWriter} as an internal interface for performing the actual NormalizedNode writeout,
45 * i.e. it will defer to a {@link NormalizedNodeWriter} instance.
48 * As such, this is an implementation detail not exposed from this package, hence implementations can rely on the
49 * stream being initialized with a header and version.
51 abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOutput, NormalizedNodeStreamWriter {
52 private static final Logger LOG = LoggerFactory.getLogger(AbstractNormalizedNodeDataOutput.class);
54 private final DataOutput output;
56 private NormalizedNodeWriter normalizedNodeWriter;
57 private boolean headerWritten;
58 private QName lastLeafSetQName;
59 private boolean inSimple;
61 AbstractNormalizedNodeDataOutput(final DataOutput output) {
62 this.output = requireNonNull(output);
65 final DataOutput output() {
69 private void ensureHeaderWritten() throws IOException {
71 output.writeByte(TokenTypes.SIGNATURE_MARKER);
72 output.writeShort(streamVersion());
78 public final void write(final int value) throws IOException {
79 ensureHeaderWritten();
84 public final void write(final byte[] bytes) throws IOException {
85 ensureHeaderWritten();
90 public final void write(final byte[] bytes, final int off, final int len) throws IOException {
91 ensureHeaderWritten();
92 output.write(bytes, off, len);
96 public final void writeBoolean(final boolean value) throws IOException {
97 ensureHeaderWritten();
98 output.writeBoolean(value);
102 public final void writeByte(final int value) throws IOException {
103 ensureHeaderWritten();
104 output.writeByte(value);
108 public final void writeShort(final int value) throws IOException {
109 ensureHeaderWritten();
110 output.writeShort(value);
114 public final void writeChar(final int value) throws IOException {
115 ensureHeaderWritten();
116 output.writeChar(value);
120 public final void writeInt(final int value) throws IOException {
121 ensureHeaderWritten();
122 output.writeInt(value);
126 public final void writeLong(final long value) throws IOException {
127 ensureHeaderWritten();
128 output.writeLong(value);
132 public final void writeFloat(final float value) throws IOException {
133 ensureHeaderWritten();
134 output.writeFloat(value);
138 public final void writeDouble(final double value) throws IOException {
139 ensureHeaderWritten();
140 output.writeDouble(value);
144 public final void writeBytes(final String str) throws IOException {
145 ensureHeaderWritten();
146 output.writeBytes(str);
150 public final void writeChars(final String str) throws IOException {
151 ensureHeaderWritten();
152 output.writeChars(str);
156 public final void writeUTF(final String str) throws IOException {
157 ensureHeaderWritten();
158 output.writeUTF(str);
162 public final void writeQName(final QName qname) throws IOException {
163 ensureHeaderWritten();
164 writeQNameInternal(qname);
168 public final void writeNormalizedNode(final NormalizedNode<?, ?> node) throws IOException {
169 ensureHeaderWritten();
170 if (normalizedNodeWriter == null) {
171 normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(this);
173 normalizedNodeWriter.write(node);
177 public final void writePathArgument(final PathArgument pathArgument) throws IOException {
178 ensureHeaderWritten();
179 writePathArgumentInternal(pathArgument);
183 public final void writeYangInstanceIdentifier(final YangInstanceIdentifier identifier) throws IOException {
184 ensureHeaderWritten();
185 writeYangInstanceIdentifierInternal(identifier);
189 public final void writeSchemaPath(final SchemaPath path) throws IOException {
190 ensureHeaderWritten();
191 output.writeBoolean(path.isAbsolute());
193 final Collection<QName> qnames = path.getPath();
194 output.writeInt(qnames.size());
195 for (QName qname : qnames) {
196 writeQNameInternal(qname);
201 public final void close() throws IOException {
206 public void startLeafNode(final NodeIdentifier name) throws IOException {
207 LOG.trace("Starting a new leaf node");
208 startNode(name, NodeTypes.LEAF_NODE);
213 public void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
214 LOG.trace("Starting a new leaf set");
215 commonStartLeafSet(name, NodeTypes.LEAF_SET);
219 public void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
220 LOG.trace("Starting a new ordered leaf set");
221 commonStartLeafSet(name, NodeTypes.ORDERED_LEAF_SET);
224 private void commonStartLeafSet(final NodeIdentifier name, final byte nodeType) throws IOException {
225 startNode(name, nodeType);
226 lastLeafSetQName = name.getNodeType();
230 public void startLeafSetEntryNode(final NodeWithValue<?> name) throws IOException {
231 LOG.trace("Starting a new leaf set entry node");
233 output.writeByte(NodeTypes.LEAF_SET_ENTRY_NODE);
235 // lastLeafSetQName is set if the parent LeafSetNode was previously written. Otherwise this is a
236 // stand alone LeafSetEntryNode so write out it's name here.
237 if (lastLeafSetQName == null) {
238 writeQNameInternal(name.getNodeType());
244 public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
245 LOG.trace("Starting a new container node");
246 startNode(name, NodeTypes.CONTAINER_NODE);
250 public void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
251 LOG.trace("Starting a new yang modeled anyXml node");
252 startNode(name, NodeTypes.YANG_MODELED_ANY_XML_NODE);
256 public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
257 LOG.trace("Starting a new unkeyed list");
258 startNode(name, NodeTypes.UNKEYED_LIST);
262 public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
263 LOG.trace("Starting a new unkeyed list item");
264 startNode(name, NodeTypes.UNKEYED_LIST_ITEM);
268 public void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
269 LOG.trace("Starting a new map node");
270 startNode(name, NodeTypes.MAP_NODE);
274 public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
276 LOG.trace("Starting a new map entry node");
277 startNode(identifier, NodeTypes.MAP_ENTRY_NODE);
278 writeKeyValueMap(identifier.entrySet());
282 public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
283 LOG.trace("Starting a new ordered map node");
284 startNode(name, NodeTypes.ORDERED_MAP_NODE);
288 public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
289 LOG.trace("Starting a new choice node");
290 startNode(name, NodeTypes.CHOICE_NODE);
294 public void startAugmentationNode(final AugmentationIdentifier identifier) throws IOException {
295 requireNonNull(identifier, "Node identifier should not be null");
296 LOG.trace("Starting a new augmentation node");
298 output.writeByte(NodeTypes.AUGMENTATION_NODE);
299 writeAugmentationIdentifier(identifier);
303 public void startAnyxmlNode(final NodeIdentifier name) throws IOException {
304 LOG.trace("Starting any xml node");
305 startNode(name, NodeTypes.ANY_XML_NODE);
310 public void scalarValue(final Object value) throws IOException {
315 public void domSourceValue(final DOMSource value) throws IOException {
317 StreamResult xmlOutput = new StreamResult(new StringWriter());
318 TransformerFactory.newInstance().newTransformer().transform(value, xmlOutput);
319 writeObject(xmlOutput.getWriter().toString());
320 } catch (TransformerException | TransformerFactoryConfigurationError e) {
321 throw new IOException("Error writing anyXml", e);
326 public void endNode() throws IOException {
327 LOG.trace("Ending the node");
329 lastLeafSetQName = null;
330 output.writeByte(NodeTypes.END_NODE);
336 public void flush() throws IOException {
337 if (output instanceof OutputStream) {
338 ((OutputStream)output).flush();
342 private void startNode(final PathArgument arg, final byte nodeType) throws IOException {
343 requireNonNull(arg, "Node identifier should not be null");
344 checkState(!inSimple, "Attempted to start a child in a simple node");
346 // First write the type of node
347 output.writeByte(nodeType);
349 writeQNameInternal(arg.getNodeType());
352 final void writeObjSet(final Set<?> set) throws IOException {
353 output.writeInt(set.size());
354 for (Object o : set) {
355 checkArgument(o instanceof String, "Expected value type to be String but was %s (%s)", o.getClass(), o);
356 writeString((String) o);
360 final void writeYangInstanceIdentifierInternal(final YangInstanceIdentifier identifier) throws IOException {
361 Collection<PathArgument> pathArguments = identifier.getPathArguments();
362 output.writeInt(pathArguments.size());
364 for (PathArgument pathArgument : pathArguments) {
365 writePathArgumentInternal(pathArgument);
369 @SuppressFBWarnings(value = "BC_UNCONFIRMED_CAST",
370 justification = "The casts in the switch clauses are indirectly confirmed via the determination of 'type'.")
371 final void writePathArgumentInternal(final PathArgument pathArgument) throws IOException {
372 final byte type = PathArgumentTypes.getSerializablePathArgumentType(pathArgument);
373 output.writeByte(type);
376 case PathArgumentTypes.NODE_IDENTIFIER:
377 NodeIdentifier nodeIdentifier = (NodeIdentifier) pathArgument;
378 writeQNameInternal(nodeIdentifier.getNodeType());
380 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES:
381 NodeIdentifierWithPredicates nodeIdentifierWithPredicates =
382 (NodeIdentifierWithPredicates) pathArgument;
383 writeQNameInternal(nodeIdentifierWithPredicates.getNodeType());
384 writeKeyValueMap(nodeIdentifierWithPredicates.entrySet());
386 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE:
387 NodeWithValue<?> nodeWithValue = (NodeWithValue<?>) pathArgument;
388 writeQNameInternal(nodeWithValue.getNodeType());
389 writeObject(nodeWithValue.getValue());
391 case PathArgumentTypes.AUGMENTATION_IDENTIFIER:
392 // No Qname in augmentation identifier
393 writeAugmentationIdentifier((AugmentationIdentifier) pathArgument);
396 throw new IllegalStateException("Unknown node identifier type is found : "
397 + pathArgument.getClass().toString());
401 private void writeKeyValueMap(final Set<Entry<QName, Object>> entrySet) throws IOException {
402 if (!entrySet.isEmpty()) {
403 output.writeInt(entrySet.size());
404 for (Entry<QName, Object> entry : entrySet) {
405 writeQNameInternal(entry.getKey());
406 writeObject(entry.getValue());
413 final void defaultWriteAugmentationIdentifier(final @NonNull AugmentationIdentifier aid) throws IOException {
414 final Set<QName> qnames = aid.getPossibleChildNames();
415 // Write each child's qname separately, if list is empty send count as 0
416 if (!qnames.isEmpty()) {
417 output.writeInt(qnames.size());
418 for (QName qname : qnames) {
419 writeQNameInternal(qname);
422 LOG.debug("augmentation node does not have any child");
427 abstract short streamVersion();
429 abstract void writeString(@NonNull String string) throws IOException;
431 abstract void writeQNameInternal(@NonNull QName qname) throws IOException;
433 abstract void writeAugmentationIdentifier(@NonNull AugmentationIdentifier aid) throws IOException;
435 abstract void writeObject(@NonNull DataOutput output, @NonNull Object value) throws IOException;
437 private void writeObject(final Object value) throws IOException {
438 writeObject(output, value);