Bump yangtools to 3.0.0
[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.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 writeQName(QName qname) throws IOException;
64
65     protected abstract void writeString(String string) throws IOException;
66
67     @Override
68     public final void write(final int value) throws IOException {
69         ensureHeaderWritten();
70         output.write(value);
71     }
72
73     @Override
74     public final void write(final byte[] bytes) throws IOException {
75         ensureHeaderWritten();
76         output.write(bytes);
77     }
78
79     @Override
80     public final void write(final byte[] bytes, final int off, final int len) throws IOException {
81         ensureHeaderWritten();
82         output.write(bytes, off, len);
83     }
84
85     @Override
86     public final void writeBoolean(final boolean value) throws IOException {
87         ensureHeaderWritten();
88         output.writeBoolean(value);
89     }
90
91     @Override
92     public final void writeByte(final int value) throws IOException {
93         ensureHeaderWritten();
94         output.writeByte(value);
95     }
96
97     @Override
98     public final void writeShort(final int value) throws IOException {
99         ensureHeaderWritten();
100         output.writeShort(value);
101     }
102
103     @Override
104     public final void writeChar(final int value) throws IOException {
105         ensureHeaderWritten();
106         output.writeChar(value);
107     }
108
109     @Override
110     public final void writeInt(final int value) throws IOException {
111         ensureHeaderWritten();
112         output.writeInt(value);
113     }
114
115     @Override
116     public final void writeLong(final long value) throws IOException {
117         ensureHeaderWritten();
118         output.writeLong(value);
119     }
120
121     @Override
122     public final void writeFloat(final float value) throws IOException {
123         ensureHeaderWritten();
124         output.writeFloat(value);
125     }
126
127     @Override
128     public final void writeDouble(final double value) throws IOException {
129         ensureHeaderWritten();
130         output.writeDouble(value);
131     }
132
133     @Override
134     public final void writeBytes(final String str) throws IOException {
135         ensureHeaderWritten();
136         output.writeBytes(str);
137     }
138
139     @Override
140     public final void writeChars(final String str) throws IOException {
141         ensureHeaderWritten();
142         output.writeChars(str);
143     }
144
145     @Override
146     public final void writeUTF(final String str) throws IOException {
147         ensureHeaderWritten();
148         output.writeUTF(str);
149     }
150
151     private NormalizedNodeWriter normalizedNodeWriter() {
152         if (normalizedNodeWriter == null) {
153             normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(this);
154         }
155
156         return normalizedNodeWriter;
157     }
158
159     @Override
160     public void writeNormalizedNode(final NormalizedNode<?, ?> node) throws IOException {
161         ensureHeaderWritten();
162         normalizedNodeWriter().write(node);
163     }
164
165     @Override
166     public void startLeafNode(final NodeIdentifier name) throws IOException {
167         Preconditions.checkNotNull(name, "Node identifier should not be null");
168         LOG.trace("Starting a new leaf node");
169         startNode(name.getNodeType(), NodeTypes.LEAF_NODE);
170         inSimple = true;
171     }
172
173     @Override
174     public void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
175         Preconditions.checkNotNull(name, "Node identifier should not be null");
176         LOG.trace("Starting a new leaf set");
177
178         lastLeafSetQName = name.getNodeType();
179         startNode(name.getNodeType(), NodeTypes.LEAF_SET);
180     }
181
182     @Override
183     public void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
184         Preconditions.checkNotNull(name, "Node identifier should not be null");
185         LOG.trace("Starting a new ordered leaf set");
186
187         lastLeafSetQName = name.getNodeType();
188         startNode(name.getNodeType(), NodeTypes.ORDERED_LEAF_SET);
189     }
190
191     @Override
192     public void startLeafSetEntryNode(final NodeWithValue<?> name) throws IOException {
193         LOG.trace("Starting a new leaf set entry node");
194
195         output.writeByte(NodeTypes.LEAF_SET_ENTRY_NODE);
196
197         // lastLeafSetQName is set if the parent LeafSetNode was previously written. Otherwise this is a
198         // stand alone LeafSetEntryNode so write out it's name here.
199         if (lastLeafSetQName == null) {
200             writeQName(name.getNodeType());
201         }
202         inSimple = true;
203     }
204
205     @Override
206     public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
207         Preconditions.checkNotNull(name, "Node identifier should not be null");
208
209         LOG.trace("Starting a new container node");
210
211         startNode(name.getNodeType(), NodeTypes.CONTAINER_NODE);
212     }
213
214     @Override
215     public void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
216         Preconditions.checkNotNull(name, "Node identifier should not be null");
217
218         LOG.trace("Starting a new yang modeled anyXml node");
219
220         startNode(name.getNodeType(), NodeTypes.YANG_MODELED_ANY_XML_NODE);
221     }
222
223     @Override
224     public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
225         Preconditions.checkNotNull(name, "Node identifier should not be null");
226         LOG.trace("Starting a new unkeyed list");
227
228         startNode(name.getNodeType(), NodeTypes.UNKEYED_LIST);
229     }
230
231     @Override
232     public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
233         Preconditions.checkNotNull(name, "Node identifier should not be null");
234         LOG.trace("Starting a new unkeyed list item");
235
236         startNode(name.getNodeType(), NodeTypes.UNKEYED_LIST_ITEM);
237     }
238
239     @Override
240     public void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
241         Preconditions.checkNotNull(name, "Node identifier should not be null");
242         LOG.trace("Starting a new map node");
243
244         startNode(name.getNodeType(), NodeTypes.MAP_NODE);
245     }
246
247     @Override
248     public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
249             throws IOException {
250         Preconditions.checkNotNull(identifier, "Node identifier should not be null");
251         LOG.trace("Starting a new map entry node");
252         startNode(identifier.getNodeType(), NodeTypes.MAP_ENTRY_NODE);
253
254         writeKeyValueMap(identifier.getKeyValues());
255     }
256
257     @Override
258     public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
259         Preconditions.checkNotNull(name, "Node identifier should not be null");
260         LOG.trace("Starting a new ordered map node");
261
262         startNode(name.getNodeType(), NodeTypes.ORDERED_MAP_NODE);
263     }
264
265     @Override
266     public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
267         Preconditions.checkNotNull(name, "Node identifier should not be null");
268         LOG.trace("Starting a new choice node");
269
270         startNode(name.getNodeType(), NodeTypes.CHOICE_NODE);
271     }
272
273     @Override
274     public void startAugmentationNode(final AugmentationIdentifier identifier) throws IOException {
275         Preconditions.checkNotNull(identifier, "Node identifier should not be null");
276         LOG.trace("Starting a new augmentation node");
277
278         output.writeByte(NodeTypes.AUGMENTATION_NODE);
279         writeQNameSet(identifier.getPossibleChildNames());
280     }
281
282     @Override
283     public void startAnyxmlNode(final NodeIdentifier name) throws IOException {
284         Preconditions.checkNotNull(name, "Node identifier should not be null");
285         LOG.trace("Starting any xml node");
286         startNode(name.getNodeType(), NodeTypes.ANY_XML_NODE);
287         inSimple = true;
288     }
289
290     @Override
291     public void scalarValue(final Object value) throws IOException {
292         writeObject(value);
293     }
294
295     @Override
296     public void domSourceValue(final DOMSource value) throws IOException {
297         try {
298             StreamResult xmlOutput = new StreamResult(new StringWriter());
299             TransformerFactory.newInstance().newTransformer().transform(value, xmlOutput);
300             writeObject(xmlOutput.getWriter().toString());
301         } catch (TransformerException | TransformerFactoryConfigurationError e) {
302             throw new IOException("Error writing anyXml", e);
303         }
304     }
305
306     @Override
307     public void endNode() throws IOException {
308         LOG.trace("Ending the node");
309         if (!inSimple) {
310             lastLeafSetQName = null;
311             output.writeByte(NodeTypes.END_NODE);
312         }
313         inSimple = false;
314     }
315
316     @Override
317     public void close() throws IOException {
318         flush();
319     }
320
321     @Override
322     public void flush() throws IOException {
323         if (output instanceof OutputStream) {
324             ((OutputStream)output).flush();
325         }
326     }
327
328     private void startNode(final QName qname, final byte nodeType) throws IOException {
329         Preconditions.checkNotNull(qname, "QName of node identifier should not be null.");
330         Preconditions.checkState(!inSimple, "Attempted to start a child in a simple node");
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 writeSchemaPath(final SchemaPath path) throws IOException {
352         ensureHeaderWritten();
353         output.writeBoolean(path.isAbsolute());
354
355         final Collection<QName> qnames = path.getPath();
356         output.writeInt(qnames.size());
357         for (QName qname : qnames) {
358             writeQName(qname);
359         }
360     }
361
362     @Override
363     public void writeYangInstanceIdentifier(final YangInstanceIdentifier identifier) throws IOException {
364         ensureHeaderWritten();
365         writeYangInstanceIdentifierInternal(identifier);
366     }
367
368     private void writeYangInstanceIdentifierInternal(final YangInstanceIdentifier identifier) throws IOException {
369         Collection<PathArgument> pathArguments = identifier.getPathArguments();
370         output.writeInt(pathArguments.size());
371
372         for (PathArgument pathArgument : pathArguments) {
373             writePathArgument(pathArgument);
374         }
375     }
376
377     @SuppressFBWarnings(value = "BC_UNCONFIRMED_CAST",
378             justification = "The casts in the switch clauses are indirectly confirmed via the determination of 'type'.")
379     @Override
380     public void writePathArgument(final PathArgument pathArgument) throws IOException {
381
382         byte type = PathArgumentTypes.getSerializablePathArgumentType(pathArgument);
383
384         output.writeByte(type);
385
386         switch (type) {
387             case PathArgumentTypes.NODE_IDENTIFIER:
388
389                 NodeIdentifier nodeIdentifier = (NodeIdentifier) pathArgument;
390
391                 writeQName(nodeIdentifier.getNodeType());
392                 break;
393
394             case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES:
395
396                 NodeIdentifierWithPredicates nodeIdentifierWithPredicates =
397                     (NodeIdentifierWithPredicates) pathArgument;
398                 writeQName(nodeIdentifierWithPredicates.getNodeType());
399
400                 writeKeyValueMap(nodeIdentifierWithPredicates.getKeyValues());
401                 break;
402
403             case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
404
405                 NodeWithValue<?> nodeWithValue = (NodeWithValue<?>) pathArgument;
406
407                 writeQName(nodeWithValue.getNodeType());
408                 writeObject(nodeWithValue.getValue());
409                 break;
410
411             case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
412
413                 AugmentationIdentifier augmentationIdentifier = (AugmentationIdentifier) pathArgument;
414
415                 // No Qname in augmentation identifier
416                 writeQNameSet(augmentationIdentifier.getPossibleChildNames());
417                 break;
418             default :
419                 throw new IllegalStateException("Unknown node identifier type is found : "
420                         + pathArgument.getClass().toString());
421         }
422     }
423
424     private void writeKeyValueMap(final Map<QName, Object> keyValueMap) throws IOException {
425         if (keyValueMap != null && !keyValueMap.isEmpty()) {
426             output.writeInt(keyValueMap.size());
427
428             for (Map.Entry<QName, Object> entry : keyValueMap.entrySet()) {
429                 writeQName(entry.getKey());
430                 writeObject(entry.getValue());
431             }
432         } else {
433             output.writeInt(0);
434         }
435     }
436
437     private void writeQNameSet(final Set<QName> children) throws IOException {
438         // Write each child's qname separately, if list is empty send count as 0
439         if (children != null && !children.isEmpty()) {
440             output.writeInt(children.size());
441             for (QName qname : children) {
442                 writeQName(qname);
443             }
444         } else {
445             LOG.debug("augmentation node does not have any child");
446             output.writeInt(0);
447         }
448     }
449
450     private void writeObject(final Object value) throws IOException {
451
452         byte type = ValueTypes.getSerializableType(value);
453         // Write object type first
454         output.writeByte(type);
455
456         switch (type) {
457             case ValueTypes.BOOL_TYPE:
458                 output.writeBoolean((Boolean) value);
459                 break;
460             case ValueTypes.QNAME_TYPE:
461                 writeQName((QName) value);
462                 break;
463             case ValueTypes.INT_TYPE:
464                 output.writeInt((Integer) value);
465                 break;
466             case ValueTypes.BYTE_TYPE:
467                 output.writeByte((Byte) value);
468                 break;
469             case ValueTypes.LONG_TYPE:
470                 output.writeLong((Long) value);
471                 break;
472             case ValueTypes.SHORT_TYPE:
473                 output.writeShort((Short) value);
474                 break;
475             case ValueTypes.BITS_TYPE:
476                 writeObjSet((Set<?>) value);
477                 break;
478             case ValueTypes.BINARY_TYPE:
479                 byte[] bytes = (byte[]) value;
480                 output.writeInt(bytes.length);
481                 output.write(bytes);
482                 break;
483             case ValueTypes.YANG_IDENTIFIER_TYPE:
484                 writeYangInstanceIdentifierInternal((YangInstanceIdentifier) value);
485                 break;
486             case ValueTypes.EMPTY_TYPE:
487                 break;
488             case ValueTypes.STRING_BYTES_TYPE:
489                 final byte[] valueBytes = value.toString().getBytes(StandardCharsets.UTF_8);
490                 output.writeInt(valueBytes.length);
491                 output.write(valueBytes);
492                 break;
493             default:
494                 output.writeUTF(value.toString());
495                 break;
496         }
497     }
498 }