Reorganize AbstractNormalizedNodeDataOutput
[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 static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
13
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;
21 import java.util.Set;
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;
41
42 /**
43  * NormalizedNodeOutputStreamWriter will be used by distributed datastore to send normalized node in
44  * a stream.
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
47  * you will first call
48  * {@link #startContainerNode(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier, int)},
49  * then will call
50  * {@link #leafNode(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier, Object)} twice
51  * and then, {@link #endNode()} to end container node.
52  *
53  * <p>Based on the each node, the node type is also written to the stream, that helps in reconstructing the object,
54  * while reading.
55  */
56 abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOutput, NormalizedNodeStreamWriter {
57     private static final Logger LOG = LoggerFactory.getLogger(AbstractNormalizedNodeDataOutput.class);
58
59     private final DataOutput output;
60
61     private NormalizedNodeWriter normalizedNodeWriter;
62     private boolean headerWritten;
63     private QName lastLeafSetQName;
64     private boolean inSimple;
65
66     AbstractNormalizedNodeDataOutput(final DataOutput output) {
67         this.output = requireNonNull(output);
68     }
69
70     private void ensureHeaderWritten() throws IOException {
71         if (!headerWritten) {
72             output.writeByte(TokenTypes.SIGNATURE_MARKER);
73             output.writeShort(streamVersion());
74             headerWritten = true;
75         }
76     }
77
78     @Override
79     public final void write(final int value) throws IOException {
80         ensureHeaderWritten();
81         output.write(value);
82     }
83
84     @Override
85     public final void write(final byte[] bytes) throws IOException {
86         ensureHeaderWritten();
87         output.write(bytes);
88     }
89
90     @Override
91     public final void write(final byte[] bytes, final int off, final int len) throws IOException {
92         ensureHeaderWritten();
93         output.write(bytes, off, len);
94     }
95
96     @Override
97     public final void writeBoolean(final boolean value) throws IOException {
98         ensureHeaderWritten();
99         output.writeBoolean(value);
100     }
101
102     @Override
103     public final void writeByte(final int value) throws IOException {
104         ensureHeaderWritten();
105         output.writeByte(value);
106     }
107
108     @Override
109     public final void writeShort(final int value) throws IOException {
110         ensureHeaderWritten();
111         output.writeShort(value);
112     }
113
114     @Override
115     public final void writeChar(final int value) throws IOException {
116         ensureHeaderWritten();
117         output.writeChar(value);
118     }
119
120     @Override
121     public final void writeInt(final int value) throws IOException {
122         ensureHeaderWritten();
123         output.writeInt(value);
124     }
125
126     @Override
127     public final void writeLong(final long value) throws IOException {
128         ensureHeaderWritten();
129         output.writeLong(value);
130     }
131
132     @Override
133     public final void writeFloat(final float value) throws IOException {
134         ensureHeaderWritten();
135         output.writeFloat(value);
136     }
137
138     @Override
139     public final void writeDouble(final double value) throws IOException {
140         ensureHeaderWritten();
141         output.writeDouble(value);
142     }
143
144     @Override
145     public final void writeBytes(final String str) throws IOException {
146         ensureHeaderWritten();
147         output.writeBytes(str);
148     }
149
150     @Override
151     public final void writeChars(final String str) throws IOException {
152         ensureHeaderWritten();
153         output.writeChars(str);
154     }
155
156     @Override
157     public final void writeUTF(final String str) throws IOException {
158         ensureHeaderWritten();
159         output.writeUTF(str);
160     }
161
162     @Override
163     public final void writeQName(final QName qname) throws IOException {
164         ensureHeaderWritten();
165         writeQNameInternal(qname);
166     }
167
168     @Override
169     public final void writeNormalizedNode(final NormalizedNode<?, ?> node) throws IOException {
170         ensureHeaderWritten();
171         if (normalizedNodeWriter == null) {
172             normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(this);
173         }
174         normalizedNodeWriter.write(node);
175     }
176
177     @Override
178     public final void writePathArgument(final PathArgument pathArgument) throws IOException {
179         ensureHeaderWritten();
180         writePathArgumentInternal(pathArgument);
181     }
182
183     @Override
184     public final void writeYangInstanceIdentifier(final YangInstanceIdentifier identifier) throws IOException {
185         ensureHeaderWritten();
186         writeYangInstanceIdentifierInternal(identifier);
187     }
188
189     @Override
190     public final void writeSchemaPath(final SchemaPath path) throws IOException {
191         ensureHeaderWritten();
192         output.writeBoolean(path.isAbsolute());
193
194         final Collection<QName> qnames = path.getPath();
195         output.writeInt(qnames.size());
196         for (QName qname : qnames) {
197             writeQNameInternal(qname);
198         }
199     }
200
201     @Override
202     public final void close() throws IOException {
203         flush();
204     }
205
206     @Override
207     public void startLeafNode(final NodeIdentifier name) throws IOException {
208         LOG.trace("Starting a new leaf node");
209         startNode(name, NodeTypes.LEAF_NODE);
210         inSimple = true;
211     }
212
213     @Override
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);
217     }
218
219     @Override
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);
223     }
224
225     private void commonStartLeafSet(final NodeIdentifier name, final byte nodeType) throws IOException {
226         startNode(name, nodeType);
227         lastLeafSetQName = name.getNodeType();
228     }
229
230     @Override
231     public void startLeafSetEntryNode(final NodeWithValue<?> name) throws IOException {
232         LOG.trace("Starting a new leaf set entry node");
233
234         output.writeByte(NodeTypes.LEAF_SET_ENTRY_NODE);
235
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());
240         }
241         inSimple = true;
242     }
243
244     @Override
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);
248     }
249
250     @Override
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);
254     }
255
256     @Override
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);
260     }
261
262     @Override
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);
266     }
267
268     @Override
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);
272     }
273
274     @Override
275     public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
276             throws IOException {
277         LOG.trace("Starting a new map entry node");
278         startNode(identifier, NodeTypes.MAP_ENTRY_NODE);
279         writeKeyValueMap(identifier.entrySet());
280     }
281
282     @Override
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);
286     }
287
288     @Override
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);
292     }
293
294     @Override
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");
298
299         output.writeByte(NodeTypes.AUGMENTATION_NODE);
300         writeAugmentationIdentifier(identifier);
301     }
302
303     @Override
304     public void startAnyxmlNode(final NodeIdentifier name) throws IOException {
305         LOG.trace("Starting any xml node");
306         startNode(name, NodeTypes.ANY_XML_NODE);
307         inSimple = true;
308     }
309
310     @Override
311     public void scalarValue(final Object value) throws IOException {
312         writeObject(value);
313     }
314
315     @Override
316     public void domSourceValue(final DOMSource value) throws IOException {
317         try {
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);
323         }
324     }
325
326     @Override
327     public void endNode() throws IOException {
328         LOG.trace("Ending the node");
329         if (!inSimple) {
330             lastLeafSetQName = null;
331             output.writeByte(NodeTypes.END_NODE);
332         }
333         inSimple = false;
334     }
335
336     @Override
337     public void flush() throws IOException {
338         if (output instanceof OutputStream) {
339             ((OutputStream)output).flush();
340         }
341     }
342
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");
346
347         ensureHeaderWritten();
348
349         // First write the type of node
350         output.writeByte(nodeType);
351         // Write Start Tag
352         writeQNameInternal(arg.getNodeType());
353     }
354
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);
360         }
361     }
362
363     final void writeYangInstanceIdentifierInternal(final YangInstanceIdentifier identifier) throws IOException {
364         Collection<PathArgument> pathArguments = identifier.getPathArguments();
365         output.writeInt(pathArguments.size());
366
367         for (PathArgument pathArgument : pathArguments) {
368             writePathArgumentInternal(pathArgument);
369         }
370     }
371
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);
377
378         switch (type) {
379             case PathArgumentTypes.NODE_IDENTIFIER:
380                 NodeIdentifier nodeIdentifier = (NodeIdentifier) pathArgument;
381                 writeQNameInternal(nodeIdentifier.getNodeType());
382                 break;
383             case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES:
384                 NodeIdentifierWithPredicates nodeIdentifierWithPredicates =
385                     (NodeIdentifierWithPredicates) pathArgument;
386                 writeQNameInternal(nodeIdentifierWithPredicates.getNodeType());
387                 writeKeyValueMap(nodeIdentifierWithPredicates.entrySet());
388                 break;
389             case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE:
390                 NodeWithValue<?> nodeWithValue = (NodeWithValue<?>) pathArgument;
391                 writeQNameInternal(nodeWithValue.getNodeType());
392                 writeObject(nodeWithValue.getValue());
393                 break;
394             case PathArgumentTypes.AUGMENTATION_IDENTIFIER:
395                 // No Qname in augmentation identifier
396                 writeAugmentationIdentifier((AugmentationIdentifier) pathArgument);
397                 break;
398             default:
399                 throw new IllegalStateException("Unknown node identifier type is found : "
400                         + pathArgument.getClass().toString());
401         }
402     }
403
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());
410             }
411         } else {
412             output.writeInt(0);
413         }
414     }
415
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);
423             }
424         } else {
425             LOG.debug("augmentation node does not have any child");
426             output.writeInt(0);
427         }
428     }
429
430     abstract short streamVersion();
431
432     abstract void writeString(@NonNull String string) throws IOException;
433
434     abstract void writeQNameInternal(@NonNull QName qname) throws IOException;
435
436     abstract void writeAugmentationIdentifier(@NonNull AugmentationIdentifier aid) throws IOException;
437
438     abstract void writeObject(@NonNull DataOutput output, @NonNull Object value) throws IOException;
439
440     private void writeObject(final Object value) throws IOException {
441         writeObject(output, value);
442     }
443 }