Bug 5280: Add ProgressTracker
[controller.git] / opendaylight / md-sal / sal-clustering-commons / src / main / java / org / opendaylight / controller / cluster / datastore / node / utils / stream / AbstractNormalizedNodeDataOutput.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.cluster.datastore.node.utils.stream;
9
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;
19 import java.util.Set;
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;
37
38 abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOutput, NormalizedNodeStreamWriter {
39     private static final Logger LOG = LoggerFactory.getLogger(AbstractNormalizedNodeDataOutput.class);
40
41     private final DataOutput output;
42
43     private NormalizedNodeWriter normalizedNodeWriter;
44     private boolean headerWritten;
45     private QName lastLeafSetQName;
46
47     AbstractNormalizedNodeDataOutput(final DataOutput output) {
48         this.output = Preconditions.checkNotNull(output);
49     }
50
51     private void ensureHeaderWritten() throws IOException {
52         if (!headerWritten) {
53             output.writeByte(TokenTypes.SIGNATURE_MARKER);
54             output.writeShort(streamVersion());
55             headerWritten = true;
56         }
57     }
58
59     protected abstract short streamVersion();
60
61     protected abstract void writeQName(QName qname) throws IOException;
62
63     protected abstract void writeString(String string) throws IOException;
64
65     @Override
66     public final void write(final int value) throws IOException {
67         ensureHeaderWritten();
68         output.write(value);
69     }
70
71     @Override
72     public final void write(final byte[] bytes) throws IOException {
73         ensureHeaderWritten();
74         output.write(bytes);
75     }
76
77     @Override
78     public final void write(final byte[] bytes, final int off, final int len) throws IOException {
79         ensureHeaderWritten();
80         output.write(bytes, off, len);
81     }
82
83     @Override
84     public final void writeBoolean(final boolean value) throws IOException {
85         ensureHeaderWritten();
86         output.writeBoolean(value);
87     }
88
89     @Override
90     public final void writeByte(final int value) throws IOException {
91         ensureHeaderWritten();
92         output.writeByte(value);
93     }
94
95     @Override
96     public final void writeShort(final int value) throws IOException {
97         ensureHeaderWritten();
98         output.writeShort(value);
99     }
100
101     @Override
102     public final void writeChar(final int value) throws IOException {
103         ensureHeaderWritten();
104         output.writeChar(value);
105     }
106
107     @Override
108     public final void writeInt(final int value) throws IOException {
109         ensureHeaderWritten();
110         output.writeInt(value);
111     }
112
113     @Override
114     public final void writeLong(final long value) throws IOException {
115         ensureHeaderWritten();
116         output.writeLong(value);
117     }
118
119     @Override
120     public final void writeFloat(final float value) throws IOException {
121         ensureHeaderWritten();
122         output.writeFloat(value);
123     }
124
125     @Override
126     public final void writeDouble(final double value) throws IOException {
127         ensureHeaderWritten();
128         output.writeDouble(value);
129     }
130
131     @Override
132     public final void writeBytes(final String str) throws IOException {
133         ensureHeaderWritten();
134         output.writeBytes(str);
135     }
136
137     @Override
138     public final void writeChars(final String str) throws IOException {
139         ensureHeaderWritten();
140         output.writeChars(str);
141     }
142
143     @Override
144     public final void writeUTF(final String str) throws IOException {
145         ensureHeaderWritten();
146         output.writeUTF(str);
147     }
148
149     private NormalizedNodeWriter normalizedNodeWriter() {
150         if (normalizedNodeWriter == null) {
151             normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(this);
152         }
153
154         return normalizedNodeWriter;
155     }
156
157     @Override
158     public void writeNormalizedNode(final NormalizedNode<?, ?> node) throws IOException {
159         ensureHeaderWritten();
160         normalizedNodeWriter().write(node);
161     }
162
163     @Override
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);
168
169         writeObject(value);
170     }
171
172     @Override
173     public void startLeafSet(final NodeIdentifier name, final int childSizeHint)
174
175             throws IOException, IllegalArgumentException {
176         Preconditions.checkNotNull(name, "Node identifier should not be null");
177         LOG.debug("Starting a new leaf set");
178
179         lastLeafSetQName = name.getNodeType();
180         startNode(name.getNodeType(), NodeTypes.LEAF_SET);
181     }
182
183     @Override
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");
188
189         lastLeafSetQName = name.getNodeType();
190         startNode(name.getNodeType(), NodeTypes.ORDERED_LEAF_SET);
191     }
192
193     @Override
194     public void leafSetEntryNode(final QName name, final Object value) throws IOException, IllegalArgumentException {
195         LOG.debug("Writing a new leaf set entry node");
196
197         output.writeByte(NodeTypes.LEAF_SET_ENTRY_NODE);
198
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) {
202             writeQName(name);
203         }
204
205         writeObject(value);
206     }
207
208     @Override
209     public void startContainerNode(final NodeIdentifier name, final int childSizeHint)
210             throws IOException, IllegalArgumentException {
211         Preconditions.checkNotNull(name, "Node identifier should not be null");
212
213         LOG.debug("Starting a new container node");
214
215         startNode(name.getNodeType(), NodeTypes.CONTAINER_NODE);
216     }
217
218     @Override
219     public void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint)
220             throws IOException, IllegalArgumentException {
221         Preconditions.checkNotNull(name, "Node identifier should not be null");
222
223         LOG.debug("Starting a new yang modeled anyXml node");
224
225         startNode(name.getNodeType(), NodeTypes.YANG_MODELED_ANY_XML_NODE);
226     }
227
228     @Override
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");
233
234         startNode(name.getNodeType(), NodeTypes.UNKEYED_LIST);
235     }
236
237     @Override
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");
242
243         startNode(name.getNodeType(), NodeTypes.UNKEYED_LIST_ITEM);
244     }
245
246     @Override
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");
251
252         startNode(name.getNodeType(), NodeTypes.MAP_NODE);
253     }
254
255     @Override
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);
261
262         writeKeyValueMap(identifier.getKeyValues());
263
264     }
265
266     @Override
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");
271
272         startNode(name.getNodeType(), NodeTypes.ORDERED_MAP_NODE);
273     }
274
275     @Override
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");
280
281         startNode(name.getNodeType(), NodeTypes.CHOICE_NODE);
282     }
283
284     @Override
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");
289
290         output.writeByte(NodeTypes.AUGMENTATION_NODE);
291         writeQNameSet(identifier.getPossibleChildNames());
292     }
293
294     @Override
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");
298
299         startNode(name.getNodeType(), NodeTypes.ANY_XML_NODE);
300
301         try {
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);
307         }
308     }
309
310     @Override
311     public void endNode() throws IOException, IllegalStateException {
312         LOG.debug("Ending the node");
313
314         output.writeByte(NodeTypes.END_NODE);
315     }
316
317     @Override
318     public void close() throws IOException {
319         flush();
320     }
321
322     @Override
323     public void flush() throws IOException {
324         if (output instanceof OutputStream) {
325             ((OutputStream)output).flush();
326         }
327     }
328
329     private void startNode(final QName qname, final byte nodeType) throws IOException {
330         Preconditions.checkNotNull(qname, "QName of node identifier should not be null.");
331
332         ensureHeaderWritten();
333
334         // First write the type of node
335         output.writeByte(nodeType);
336         // Write Start Tag
337         writeQName(qname);
338     }
339
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)",
344                 o.getClass(), o);
345
346             writeString((String) o);
347         }
348     }
349
350     @Override
351     public void writeYangInstanceIdentifier(final YangInstanceIdentifier identifier) throws IOException {
352         ensureHeaderWritten();
353         writeYangInstanceIdentifierInternal(identifier);
354     }
355
356     private void writeYangInstanceIdentifierInternal(final YangInstanceIdentifier identifier) throws IOException {
357         Collection<PathArgument> pathArguments = identifier.getPathArguments();
358         output.writeInt(pathArguments.size());
359
360         for (PathArgument pathArgument : pathArguments) {
361             writePathArgument(pathArgument);
362         }
363     }
364
365     @SuppressFBWarnings(value = "BC_UNCONFIRMED_CAST",
366             justification = "The casts in the switch clauses are indirectly confirmed via the determination of 'type'.")
367     @Override
368     public void writePathArgument(final PathArgument pathArgument) throws IOException {
369
370         byte type = PathArgumentTypes.getSerializablePathArgumentType(pathArgument);
371
372         output.writeByte(type);
373
374         switch (type) {
375             case PathArgumentTypes.NODE_IDENTIFIER:
376
377                 NodeIdentifier nodeIdentifier = (NodeIdentifier) pathArgument;
378
379                 writeQName(nodeIdentifier.getNodeType());
380                 break;
381
382             case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES:
383
384                 NodeIdentifierWithPredicates nodeIdentifierWithPredicates =
385                     (NodeIdentifierWithPredicates) pathArgument;
386                 writeQName(nodeIdentifierWithPredicates.getNodeType());
387
388                 writeKeyValueMap(nodeIdentifierWithPredicates.getKeyValues());
389                 break;
390
391             case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
392
393                 NodeWithValue<?> nodeWithValue = (NodeWithValue<?>) pathArgument;
394
395                 writeQName(nodeWithValue.getNodeType());
396                 writeObject(nodeWithValue.getValue());
397                 break;
398
399             case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
400
401                 AugmentationIdentifier augmentationIdentifier = (AugmentationIdentifier) pathArgument;
402
403                 // No Qname in augmentation identifier
404                 writeQNameSet(augmentationIdentifier.getPossibleChildNames());
405                 break;
406             default :
407                 throw new IllegalStateException("Unknown node identifier type is found : "
408                         + pathArgument.getClass().toString() );
409         }
410     }
411
412     private void writeKeyValueMap(final Map<QName, Object> keyValueMap) throws IOException {
413         if (keyValueMap != null && !keyValueMap.isEmpty()) {
414             output.writeInt(keyValueMap.size());
415
416             for (Map.Entry<QName, Object> entry : keyValueMap.entrySet()) {
417                 writeQName(entry.getKey());
418                 writeObject(entry.getValue());
419             }
420         } else {
421             output.writeInt(0);
422         }
423     }
424
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) {
430                 writeQName(qname);
431             }
432         } else {
433             LOG.debug("augmentation node does not have any child");
434             output.writeInt(0);
435         }
436     }
437
438     private void writeObject(final Object value) throws IOException {
439
440         byte type = ValueTypes.getSerializableType(value);
441         // Write object type first
442         output.writeByte(type);
443
444         switch (type) {
445             case ValueTypes.BOOL_TYPE:
446                 output.writeBoolean((Boolean) value);
447                 break;
448             case ValueTypes.QNAME_TYPE:
449                 writeQName((QName) value);
450                 break;
451             case ValueTypes.INT_TYPE:
452                 output.writeInt((Integer) value);
453                 break;
454             case ValueTypes.BYTE_TYPE:
455                 output.writeByte((Byte) value);
456                 break;
457             case ValueTypes.LONG_TYPE:
458                 output.writeLong((Long) value);
459                 break;
460             case ValueTypes.SHORT_TYPE:
461                 output.writeShort((Short) value);
462                 break;
463             case ValueTypes.BITS_TYPE:
464                 writeObjSet((Set<?>) value);
465                 break;
466             case ValueTypes.BINARY_TYPE:
467                 byte[] bytes = (byte[]) value;
468                 output.writeInt(bytes.length);
469                 output.write(bytes);
470                 break;
471             case ValueTypes.YANG_IDENTIFIER_TYPE:
472                 writeYangInstanceIdentifierInternal((YangInstanceIdentifier) value);
473                 break;
474             case ValueTypes.NULL_TYPE :
475                 break;
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);
480                 break;
481             default:
482                 output.writeUTF(value.toString());
483                 break;
484         }
485     }
486 }