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.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
38 abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOutput, NormalizedNodeStreamWriter {
39 private static final Logger LOG = LoggerFactory.getLogger(AbstractNormalizedNodeDataOutput.class);
41 private final DataOutput output;
43 private NormalizedNodeWriter normalizedNodeWriter;
44 private boolean headerWritten;
45 private QName lastLeafSetQName;
47 AbstractNormalizedNodeDataOutput(final DataOutput output) {
48 this.output = Preconditions.checkNotNull(output);
51 private void ensureHeaderWritten() throws IOException {
53 output.writeByte(TokenTypes.SIGNATURE_MARKER);
54 output.writeShort(streamVersion());
59 protected abstract short streamVersion();
61 protected abstract void writeQName(QName qname) throws IOException;
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 leafNode(final NodeIdentifier name, final Object value) throws IOException, IllegalArgumentException {
165 Preconditions.checkNotNull(name, "Node identifier should not be null");
166 LOG.debug("Writing a new leaf node");
167 startNode(name.getNodeType(), NodeTypes.LEAF_NODE);
173 public void startLeafSet(final NodeIdentifier name, final int childSizeHint)
175 throws IOException, IllegalArgumentException {
176 Preconditions.checkNotNull(name, "Node identifier should not be null");
177 LOG.debug("Starting a new leaf set");
179 lastLeafSetQName = name.getNodeType();
180 startNode(name.getNodeType(), NodeTypes.LEAF_SET);
184 public void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint)
185 throws IOException, IllegalArgumentException {
186 Preconditions.checkNotNull(name, "Node identifier should not be null");
187 LOG.debug("Starting a new ordered leaf set");
189 lastLeafSetQName = name.getNodeType();
190 startNode(name.getNodeType(), NodeTypes.ORDERED_LEAF_SET);
194 public void leafSetEntryNode(final QName name, final Object value) throws IOException, IllegalArgumentException {
195 LOG.debug("Writing a new leaf set entry node");
197 output.writeByte(NodeTypes.LEAF_SET_ENTRY_NODE);
199 // lastLeafSetQName is set if the parent LeafSetNode was previously written. Otherwise this is a
200 // stand alone LeafSetEntryNode so write out it's name here.
201 if (lastLeafSetQName == null) {
209 public void startContainerNode(final NodeIdentifier name, final int childSizeHint)
210 throws IOException, IllegalArgumentException {
211 Preconditions.checkNotNull(name, "Node identifier should not be null");
213 LOG.debug("Starting a new container node");
215 startNode(name.getNodeType(), NodeTypes.CONTAINER_NODE);
219 public void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint)
220 throws IOException, IllegalArgumentException {
221 Preconditions.checkNotNull(name, "Node identifier should not be null");
223 LOG.debug("Starting a new yang modeled anyXml node");
225 startNode(name.getNodeType(), NodeTypes.YANG_MODELED_ANY_XML_NODE);
229 public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint)
230 throws IOException, IllegalArgumentException {
231 Preconditions.checkNotNull(name, "Node identifier should not be null");
232 LOG.debug("Starting a new unkeyed list");
234 startNode(name.getNodeType(), NodeTypes.UNKEYED_LIST);
238 public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint)
239 throws IOException, IllegalStateException {
240 Preconditions.checkNotNull(name, "Node identifier should not be null");
241 LOG.debug("Starting a new unkeyed list item");
243 startNode(name.getNodeType(), NodeTypes.UNKEYED_LIST_ITEM);
247 public void startMapNode(final NodeIdentifier name, final int childSizeHint)
248 throws IOException, IllegalArgumentException {
249 Preconditions.checkNotNull(name, "Node identifier should not be null");
250 LOG.debug("Starting a new map node");
252 startNode(name.getNodeType(), NodeTypes.MAP_NODE);
256 public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
257 throws IOException, IllegalArgumentException {
258 Preconditions.checkNotNull(identifier, "Node identifier should not be null");
259 LOG.debug("Starting a new map entry node");
260 startNode(identifier.getNodeType(), NodeTypes.MAP_ENTRY_NODE);
262 writeKeyValueMap(identifier.getKeyValues());
267 public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint)
268 throws IOException, IllegalArgumentException {
269 Preconditions.checkNotNull(name, "Node identifier should not be null");
270 LOG.debug("Starting a new ordered map node");
272 startNode(name.getNodeType(), NodeTypes.ORDERED_MAP_NODE);
276 public void startChoiceNode(final NodeIdentifier name, final int childSizeHint)
277 throws IOException, IllegalArgumentException {
278 Preconditions.checkNotNull(name, "Node identifier should not be null");
279 LOG.debug("Starting a new choice node");
281 startNode(name.getNodeType(), NodeTypes.CHOICE_NODE);
285 public void startAugmentationNode(final AugmentationIdentifier identifier)
286 throws IOException, IllegalArgumentException {
287 Preconditions.checkNotNull(identifier, "Node identifier should not be null");
288 LOG.debug("Starting a new augmentation node");
290 output.writeByte(NodeTypes.AUGMENTATION_NODE);
291 writeQNameSet(identifier.getPossibleChildNames());
295 public void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException, IllegalArgumentException {
296 Preconditions.checkNotNull(name, "Node identifier should not be null");
297 LOG.debug("Writing any xml node");
299 startNode(name.getNodeType(), NodeTypes.ANY_XML_NODE);
302 StreamResult xmlOutput = new StreamResult(new StringWriter());
303 TransformerFactory.newInstance().newTransformer().transform((DOMSource)value, xmlOutput);
304 writeObject(xmlOutput.getWriter().toString());
305 } catch (TransformerException | TransformerFactoryConfigurationError e) {
306 throw new IOException("Error writing anyXml", e);
311 public void endNode() throws IOException, IllegalStateException {
312 LOG.debug("Ending the node");
314 output.writeByte(NodeTypes.END_NODE);
318 public void close() throws IOException {
323 public void flush() throws IOException {
324 if (output instanceof OutputStream) {
325 ((OutputStream)output).flush();
329 private void startNode(final QName qname, final byte nodeType) throws IOException {
330 Preconditions.checkNotNull(qname, "QName of node identifier should not be null.");
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 writeYangInstanceIdentifier(final YangInstanceIdentifier identifier) throws IOException {
352 ensureHeaderWritten();
353 writeYangInstanceIdentifierInternal(identifier);
356 private void writeYangInstanceIdentifierInternal(final YangInstanceIdentifier identifier) throws IOException {
357 Collection<PathArgument> pathArguments = identifier.getPathArguments();
358 output.writeInt(pathArguments.size());
360 for (PathArgument pathArgument : pathArguments) {
361 writePathArgument(pathArgument);
365 @SuppressFBWarnings(value = "BC_UNCONFIRMED_CAST",
366 justification = "The casts in the switch clauses are indirectly confirmed via the determination of 'type'.")
368 public void writePathArgument(final PathArgument pathArgument) throws IOException {
370 byte type = PathArgumentTypes.getSerializablePathArgumentType(pathArgument);
372 output.writeByte(type);
375 case PathArgumentTypes.NODE_IDENTIFIER:
377 NodeIdentifier nodeIdentifier = (NodeIdentifier) pathArgument;
379 writeQName(nodeIdentifier.getNodeType());
382 case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES:
384 NodeIdentifierWithPredicates nodeIdentifierWithPredicates =
385 (NodeIdentifierWithPredicates) pathArgument;
386 writeQName(nodeIdentifierWithPredicates.getNodeType());
388 writeKeyValueMap(nodeIdentifierWithPredicates.getKeyValues());
391 case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
393 NodeWithValue<?> nodeWithValue = (NodeWithValue<?>) pathArgument;
395 writeQName(nodeWithValue.getNodeType());
396 writeObject(nodeWithValue.getValue());
399 case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
401 AugmentationIdentifier augmentationIdentifier = (AugmentationIdentifier) pathArgument;
403 // No Qname in augmentation identifier
404 writeQNameSet(augmentationIdentifier.getPossibleChildNames());
407 throw new IllegalStateException("Unknown node identifier type is found : "
408 + pathArgument.getClass().toString() );
412 private void writeKeyValueMap(final Map<QName, Object> keyValueMap) throws IOException {
413 if (keyValueMap != null && !keyValueMap.isEmpty()) {
414 output.writeInt(keyValueMap.size());
416 for (Map.Entry<QName, Object> entry : keyValueMap.entrySet()) {
417 writeQName(entry.getKey());
418 writeObject(entry.getValue());
425 private void writeQNameSet(final Set<QName> children) throws IOException {
426 // Write each child's qname separately, if list is empty send count as 0
427 if (children != null && !children.isEmpty()) {
428 output.writeInt(children.size());
429 for (QName qname : children) {
433 LOG.debug("augmentation node does not have any child");
438 private void writeObject(final Object value) throws IOException {
440 byte type = ValueTypes.getSerializableType(value);
441 // Write object type first
442 output.writeByte(type);
445 case ValueTypes.BOOL_TYPE:
446 output.writeBoolean((Boolean) value);
448 case ValueTypes.QNAME_TYPE:
449 writeQName((QName) value);
451 case ValueTypes.INT_TYPE:
452 output.writeInt((Integer) value);
454 case ValueTypes.BYTE_TYPE:
455 output.writeByte((Byte) value);
457 case ValueTypes.LONG_TYPE:
458 output.writeLong((Long) value);
460 case ValueTypes.SHORT_TYPE:
461 output.writeShort((Short) value);
463 case ValueTypes.BITS_TYPE:
464 writeObjSet((Set<?>) value);
466 case ValueTypes.BINARY_TYPE:
467 byte[] bytes = (byte[]) value;
468 output.writeInt(bytes.length);
471 case ValueTypes.YANG_IDENTIFIER_TYPE:
472 writeYangInstanceIdentifierInternal((YangInstanceIdentifier) value);
474 case ValueTypes.NULL_TYPE :
476 case ValueTypes.STRING_BYTES_TYPE:
477 final byte[] valueBytes = value.toString().getBytes(StandardCharsets.UTF_8);
478 output.writeInt(valueBytes.length);
479 output.write(valueBytes);
482 output.writeUTF(value.toString());