Migrate NodeIdentifierWithPredicates.getKeyValues()
[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.Entry;
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.opendaylight.yangtools.yang.model.api.SchemaPath;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOutput, NormalizedNodeStreamWriter {
40     private static final Logger LOG = LoggerFactory.getLogger(AbstractNormalizedNodeDataOutput.class);
41
42     private final DataOutput output;
43
44     private NormalizedNodeWriter normalizedNodeWriter;
45     private boolean headerWritten;
46     private QName lastLeafSetQName;
47     private boolean inSimple;
48
49     AbstractNormalizedNodeDataOutput(final DataOutput output) {
50         this.output = Preconditions.checkNotNull(output);
51     }
52
53     private void ensureHeaderWritten() throws IOException {
54         if (!headerWritten) {
55             output.writeByte(TokenTypes.SIGNATURE_MARKER);
56             output.writeShort(streamVersion());
57             headerWritten = true;
58         }
59     }
60
61     protected abstract short streamVersion();
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 startLeafNode(final NodeIdentifier name) throws IOException {
165         Preconditions.checkNotNull(name, "Node identifier should not be null");
166         LOG.trace("Starting a new leaf node");
167         startNode(name.getNodeType(), NodeTypes.LEAF_NODE);
168         inSimple = true;
169     }
170
171     @Override
172     public void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
173         Preconditions.checkNotNull(name, "Node identifier should not be null");
174         LOG.trace("Starting a new leaf set");
175
176         lastLeafSetQName = name.getNodeType();
177         startNode(name.getNodeType(), NodeTypes.LEAF_SET);
178     }
179
180     @Override
181     public void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
182         Preconditions.checkNotNull(name, "Node identifier should not be null");
183         LOG.trace("Starting a new ordered leaf set");
184
185         lastLeafSetQName = name.getNodeType();
186         startNode(name.getNodeType(), NodeTypes.ORDERED_LEAF_SET);
187     }
188
189     @Override
190     public void startLeafSetEntryNode(final NodeWithValue<?> name) throws IOException {
191         LOG.trace("Starting a new leaf set entry node");
192
193         output.writeByte(NodeTypes.LEAF_SET_ENTRY_NODE);
194
195         // lastLeafSetQName is set if the parent LeafSetNode was previously written. Otherwise this is a
196         // stand alone LeafSetEntryNode so write out it's name here.
197         if (lastLeafSetQName == null) {
198             writeQName(name.getNodeType());
199         }
200         inSimple = true;
201     }
202
203     @Override
204     public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
205         Preconditions.checkNotNull(name, "Node identifier should not be null");
206
207         LOG.trace("Starting a new container node");
208
209         startNode(name.getNodeType(), NodeTypes.CONTAINER_NODE);
210     }
211
212     @Override
213     public void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
214         Preconditions.checkNotNull(name, "Node identifier should not be null");
215
216         LOG.trace("Starting a new yang modeled anyXml node");
217
218         startNode(name.getNodeType(), NodeTypes.YANG_MODELED_ANY_XML_NODE);
219     }
220
221     @Override
222     public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
223         Preconditions.checkNotNull(name, "Node identifier should not be null");
224         LOG.trace("Starting a new unkeyed list");
225
226         startNode(name.getNodeType(), NodeTypes.UNKEYED_LIST);
227     }
228
229     @Override
230     public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
231         Preconditions.checkNotNull(name, "Node identifier should not be null");
232         LOG.trace("Starting a new unkeyed list item");
233
234         startNode(name.getNodeType(), NodeTypes.UNKEYED_LIST_ITEM);
235     }
236
237     @Override
238     public void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
239         Preconditions.checkNotNull(name, "Node identifier should not be null");
240         LOG.trace("Starting a new map node");
241
242         startNode(name.getNodeType(), NodeTypes.MAP_NODE);
243     }
244
245     @Override
246     public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
247             throws IOException {
248         Preconditions.checkNotNull(identifier, "Node identifier should not be null");
249         LOG.trace("Starting a new map entry node");
250         startNode(identifier.getNodeType(), NodeTypes.MAP_ENTRY_NODE);
251
252         writeKeyValueMap(identifier.entrySet());
253     }
254
255     @Override
256     public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
257         Preconditions.checkNotNull(name, "Node identifier should not be null");
258         LOG.trace("Starting a new ordered map node");
259
260         startNode(name.getNodeType(), NodeTypes.ORDERED_MAP_NODE);
261     }
262
263     @Override
264     public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
265         Preconditions.checkNotNull(name, "Node identifier should not be null");
266         LOG.trace("Starting a new choice node");
267
268         startNode(name.getNodeType(), NodeTypes.CHOICE_NODE);
269     }
270
271     @Override
272     public void startAugmentationNode(final AugmentationIdentifier identifier) throws IOException {
273         Preconditions.checkNotNull(identifier, "Node identifier should not be null");
274         LOG.trace("Starting a new augmentation node");
275
276         output.writeByte(NodeTypes.AUGMENTATION_NODE);
277         writeAugmentationIdentifier(identifier);
278     }
279
280     @Override
281     public void startAnyxmlNode(final NodeIdentifier name) throws IOException {
282         Preconditions.checkNotNull(name, "Node identifier should not be null");
283         LOG.trace("Starting any xml node");
284         startNode(name.getNodeType(), NodeTypes.ANY_XML_NODE);
285         inSimple = true;
286     }
287
288     @Override
289     public void scalarValue(final Object value) throws IOException {
290         writeObject(value);
291     }
292
293     @Override
294     public void domSourceValue(final DOMSource value) throws IOException {
295         try {
296             StreamResult xmlOutput = new StreamResult(new StringWriter());
297             TransformerFactory.newInstance().newTransformer().transform(value, xmlOutput);
298             writeObject(xmlOutput.getWriter().toString());
299         } catch (TransformerException | TransformerFactoryConfigurationError e) {
300             throw new IOException("Error writing anyXml", e);
301         }
302     }
303
304     @Override
305     public void endNode() throws IOException {
306         LOG.trace("Ending the node");
307         if (!inSimple) {
308             lastLeafSetQName = null;
309             output.writeByte(NodeTypes.END_NODE);
310         }
311         inSimple = false;
312     }
313
314     @Override
315     public void close() throws IOException {
316         flush();
317     }
318
319     @Override
320     public void flush() throws IOException {
321         if (output instanceof OutputStream) {
322             ((OutputStream)output).flush();
323         }
324     }
325
326     private void startNode(final QName qname, final byte nodeType) throws IOException {
327         Preconditions.checkNotNull(qname, "QName of node identifier should not be null.");
328         Preconditions.checkState(!inSimple, "Attempted to start a child in a simple node");
329
330         ensureHeaderWritten();
331
332         // First write the type of node
333         output.writeByte(nodeType);
334         // Write Start Tag
335         writeQName(qname);
336     }
337
338     private void writeObjSet(final Set<?> set) throws IOException {
339         output.writeInt(set.size());
340         for (Object o : set) {
341             Preconditions.checkArgument(o instanceof String, "Expected value type to be String but was %s (%s)",
342                 o.getClass(), o);
343
344             writeString((String) o);
345         }
346     }
347
348     @Override
349     public void writeSchemaPath(final SchemaPath path) throws IOException {
350         ensureHeaderWritten();
351         output.writeBoolean(path.isAbsolute());
352
353         final Collection<QName> qnames = path.getPath();
354         output.writeInt(qnames.size());
355         for (QName qname : qnames) {
356             writeQName(qname);
357         }
358     }
359
360     @Override
361     public void writeYangInstanceIdentifier(final YangInstanceIdentifier identifier) throws IOException {
362         ensureHeaderWritten();
363         writeYangInstanceIdentifierInternal(identifier);
364     }
365
366     private void writeYangInstanceIdentifierInternal(final YangInstanceIdentifier identifier) throws IOException {
367         Collection<PathArgument> pathArguments = identifier.getPathArguments();
368         output.writeInt(pathArguments.size());
369
370         for (PathArgument pathArgument : pathArguments) {
371             writePathArgument(pathArgument);
372         }
373     }
374
375     @SuppressFBWarnings(value = "BC_UNCONFIRMED_CAST",
376             justification = "The casts in the switch clauses are indirectly confirmed via the determination of 'type'.")
377     @Override
378     public void writePathArgument(final PathArgument pathArgument) throws IOException {
379
380         byte type = PathArgumentTypes.getSerializablePathArgumentType(pathArgument);
381
382         output.writeByte(type);
383
384         switch (type) {
385             case PathArgumentTypes.NODE_IDENTIFIER:
386
387                 NodeIdentifier nodeIdentifier = (NodeIdentifier) pathArgument;
388
389                 writeQName(nodeIdentifier.getNodeType());
390                 break;
391
392             case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES:
393
394                 NodeIdentifierWithPredicates nodeIdentifierWithPredicates =
395                     (NodeIdentifierWithPredicates) pathArgument;
396                 writeQName(nodeIdentifierWithPredicates.getNodeType());
397
398                 writeKeyValueMap(nodeIdentifierWithPredicates.entrySet());
399                 break;
400
401             case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
402
403                 NodeWithValue<?> nodeWithValue = (NodeWithValue<?>) pathArgument;
404
405                 writeQName(nodeWithValue.getNodeType());
406                 writeObject(nodeWithValue.getValue());
407                 break;
408
409             case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
410
411                 // No Qname in augmentation identifier
412                 writeAugmentationIdentifier((AugmentationIdentifier) pathArgument);
413                 break;
414             default :
415                 throw new IllegalStateException("Unknown node identifier type is found : "
416                         + pathArgument.getClass().toString());
417         }
418     }
419
420     private void writeKeyValueMap(final Set<Entry<QName, Object>> entrySet) throws IOException {
421         if (!entrySet.isEmpty()) {
422             output.writeInt(entrySet.size());
423             for (Entry<QName, Object> entry : entrySet) {
424                 writeQName(entry.getKey());
425                 writeObject(entry.getValue());
426             }
427         } else {
428             output.writeInt(0);
429         }
430     }
431
432     void writeAugmentationIdentifier(final AugmentationIdentifier aid) throws IOException {
433         final Set<QName> qnames = aid.getPossibleChildNames();
434         // Write each child's qname separately, if list is empty send count as 0
435         if (!qnames.isEmpty()) {
436             output.writeInt(qnames.size());
437             for (QName qname : qnames) {
438                 writeQName(qname);
439             }
440         } else {
441             LOG.debug("augmentation node does not have any child");
442             output.writeInt(0);
443         }
444     }
445
446     private void writeObject(final Object value) throws IOException {
447
448         byte type = ValueTypes.getSerializableType(value);
449         // Write object type first
450         output.writeByte(type);
451
452         switch (type) {
453             case ValueTypes.BOOL_TYPE:
454                 output.writeBoolean((Boolean) value);
455                 break;
456             case ValueTypes.QNAME_TYPE:
457                 writeQName((QName) value);
458                 break;
459             case ValueTypes.INT_TYPE:
460                 output.writeInt((Integer) value);
461                 break;
462             case ValueTypes.BYTE_TYPE:
463                 output.writeByte((Byte) value);
464                 break;
465             case ValueTypes.LONG_TYPE:
466                 output.writeLong((Long) value);
467                 break;
468             case ValueTypes.SHORT_TYPE:
469                 output.writeShort((Short) value);
470                 break;
471             case ValueTypes.BITS_TYPE:
472                 writeObjSet((Set<?>) value);
473                 break;
474             case ValueTypes.BINARY_TYPE:
475                 byte[] bytes = (byte[]) value;
476                 output.writeInt(bytes.length);
477                 output.write(bytes);
478                 break;
479             case ValueTypes.YANG_IDENTIFIER_TYPE:
480                 writeYangInstanceIdentifierInternal((YangInstanceIdentifier) value);
481                 break;
482             case ValueTypes.EMPTY_TYPE:
483                 break;
484             case ValueTypes.STRING_BYTES_TYPE:
485                 final byte[] valueBytes = value.toString().getBytes(StandardCharsets.UTF_8);
486                 output.writeInt(valueBytes.length);
487                 output.write(valueBytes);
488                 break;
489             default:
490                 output.writeUTF(value.toString());
491                 break;
492         }
493     }
494 }