BUG-4626: Introduce NormalizedNodeData{Input,Output}
[controller.git] / opendaylight / md-sal / sal-clustering-commons / src / main / java / org / opendaylight / controller / cluster / datastore / node / utils / stream / NormalizedNodeOutputStreamWriter.java
1 /*
2  * Copyright (c) 2014, 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
9 package org.opendaylight.controller.cluster.datastore.node.utils.stream;
10
11 import com.google.common.base.Preconditions;
12 import java.io.DataOutput;
13 import java.io.DataOutputStream;
14 import java.io.IOException;
15 import java.io.OutputStream;
16 import java.nio.charset.StandardCharsets;
17 import java.util.Collection;
18 import java.util.HashMap;
19 import java.util.Map;
20 import java.util.Set;
21 import org.opendaylight.yangtools.yang.common.QName;
22 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
23 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
24 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
25 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 /**
30  * NormalizedNodeOutputStreamWriter will be used by distributed datastore to send normalized node in
31  * a stream.
32  * A stream writer wrapper around this class will write node objects to stream in recursive manner.
33  * for example - If you have a ContainerNode which has a two LeafNode as children, then
34  * you will first call {@link #startContainerNode(YangInstanceIdentifier.NodeIdentifier, int)}, then will call
35  * {@link #leafNode(YangInstanceIdentifier.NodeIdentifier, Object)} twice and then, {@link #endNode()} to end
36  * container node.
37  *
38  * Based on the each node, the node type is also written to the stream, that helps in reconstructing the object,
39  * while reading.
40  *
41  *
42  */
43
44 public class NormalizedNodeOutputStreamWriter implements NormalizedNodeDataOutput, NormalizedNodeStreamWriter {
45
46     private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeOutputStreamWriter.class);
47
48     private final DataOutput output;
49
50     private final Map<String, Integer> stringCodeMap = new HashMap<>();
51
52     private NormalizedNodeWriter normalizedNodeWriter;
53
54     private boolean wroteSignatureMarker;
55
56     /**
57      * @deprecated Use {@link #NormalizedNodeOutputStreamWriter(DataOutput)} instead.
58      */
59     @Deprecated
60     public NormalizedNodeOutputStreamWriter(final OutputStream stream) throws IOException {
61         this((DataOutput) new DataOutputStream(Preconditions.checkNotNull(stream)));
62     }
63
64     /**
65      * @deprecated Use {@link NormalizedNodeInputOutput#newDataOutput(DataOutput)} instead.
66      */
67     @Deprecated
68     public NormalizedNodeOutputStreamWriter(final DataOutput output) {
69         this.output = Preconditions.checkNotNull(output);
70     }
71
72     private NormalizedNodeWriter normalizedNodeWriter() {
73         if(normalizedNodeWriter == null) {
74             normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(this);
75         }
76
77         return normalizedNodeWriter;
78     }
79
80     @Override
81     public void writeNormalizedNode(NormalizedNode<?, ?> node) throws IOException {
82         writeSignatureMarkerAndVersionIfNeeded();
83         normalizedNodeWriter().write(node);
84     }
85
86     private void writeSignatureMarkerAndVersionIfNeeded() throws IOException {
87         if(!wroteSignatureMarker) {
88             output.writeByte(TokenTypes.SIGNATURE_MARKER);
89             output.writeShort(TokenTypes.LITHIUM_VERSION);
90             wroteSignatureMarker = true;
91         }
92     }
93
94     @Override
95     public void leafNode(YangInstanceIdentifier.NodeIdentifier name, Object value) throws IOException, IllegalArgumentException {
96         Preconditions.checkNotNull(name, "Node identifier should not be null");
97         LOG.debug("Writing a new leaf node");
98         startNode(name.getNodeType(), NodeTypes.LEAF_NODE);
99
100         writeObject(value);
101     }
102
103     @Override
104     public void startLeafSet(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException {
105         Preconditions.checkNotNull(name, "Node identifier should not be null");
106         LOG.debug("Starting a new leaf set");
107
108         startNode(name.getNodeType(), NodeTypes.LEAF_SET);
109     }
110
111     @Override
112     public void leafSetEntryNode(Object value) throws IOException, IllegalArgumentException {
113         LOG.debug("Writing a new leaf set entry node");
114
115         output.writeByte(NodeTypes.LEAF_SET_ENTRY_NODE);
116         writeObject(value);
117     }
118
119     @Override
120     public void startContainerNode(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException {
121         Preconditions.checkNotNull(name, "Node identifier should not be null");
122
123         LOG.debug("Starting a new container node");
124
125         startNode(name.getNodeType(), NodeTypes.CONTAINER_NODE);
126     }
127
128     @Override
129     public void startYangModeledAnyXmlNode(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException {
130         Preconditions.checkNotNull(name, "Node identifier should not be null");
131
132         LOG.debug("Starting a new yang modeled anyXml node");
133
134         startNode(name.getNodeType(), NodeTypes.YANG_MODELED_ANY_XML_NODE);
135     }
136
137     @Override
138     public void startUnkeyedList(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException {
139         Preconditions.checkNotNull(name, "Node identifier should not be null");
140         LOG.debug("Starting a new unkeyed list");
141
142         startNode(name.getNodeType(), NodeTypes.UNKEYED_LIST);
143     }
144
145     @Override
146     public void startUnkeyedListItem(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalStateException {
147         Preconditions.checkNotNull(name, "Node identifier should not be null");
148         LOG.debug("Starting a new unkeyed list item");
149
150         startNode(name.getNodeType(), NodeTypes.UNKEYED_LIST_ITEM);
151     }
152
153     @Override
154     public void startMapNode(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException {
155         Preconditions.checkNotNull(name, "Node identifier should not be null");
156         LOG.debug("Starting a new map node");
157
158         startNode(name.getNodeType(), NodeTypes.MAP_NODE);
159     }
160
161     @Override
162     public void startMapEntryNode(YangInstanceIdentifier.NodeIdentifierWithPredicates identifier, int childSizeHint) throws IOException, IllegalArgumentException {
163         Preconditions.checkNotNull(identifier, "Node identifier should not be null");
164         LOG.debug("Starting a new map entry node");
165         startNode(identifier.getNodeType(), NodeTypes.MAP_ENTRY_NODE);
166
167         writeKeyValueMap(identifier.getKeyValues());
168
169     }
170
171     @Override
172     public void startOrderedMapNode(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException {
173         Preconditions.checkNotNull(name, "Node identifier should not be null");
174         LOG.debug("Starting a new ordered map node");
175
176         startNode(name.getNodeType(), NodeTypes.ORDERED_MAP_NODE);
177     }
178
179     @Override
180     public void startChoiceNode(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException {
181         Preconditions.checkNotNull(name, "Node identifier should not be null");
182         LOG.debug("Starting a new choice node");
183
184         startNode(name.getNodeType(), NodeTypes.CHOICE_NODE);
185     }
186
187     @Override
188     public void startAugmentationNode(YangInstanceIdentifier.AugmentationIdentifier identifier) throws IOException, IllegalArgumentException {
189         Preconditions.checkNotNull(identifier, "Node identifier should not be null");
190         LOG.debug("Starting a new augmentation node");
191
192         output.writeByte(NodeTypes.AUGMENTATION_NODE);
193         writeQNameSet(identifier.getPossibleChildNames());
194     }
195
196     @Override
197     public void anyxmlNode(YangInstanceIdentifier.NodeIdentifier name, Object value) throws IOException, IllegalArgumentException {
198         Preconditions.checkNotNull(name, "Node identifier should not be null");
199         LOG.debug("Writing a new xml node");
200
201         startNode(name.getNodeType(), NodeTypes.ANY_XML_NODE);
202
203         writeObject(value);
204     }
205
206     @Override
207     public void endNode() throws IOException, IllegalStateException {
208         LOG.debug("Ending the node");
209
210         output.writeByte(NodeTypes.END_NODE);
211     }
212
213     @Override
214     public void close() throws IOException {
215         flush();
216     }
217
218     @Override
219     public void flush() throws IOException {
220         if (output instanceof OutputStream) {
221             ((OutputStream)output).flush();
222         }
223     }
224
225     private void startNode(final QName qName, byte nodeType) throws IOException {
226
227         Preconditions.checkNotNull(qName, "QName of node identifier should not be null.");
228
229         writeSignatureMarkerAndVersionIfNeeded();
230
231         // First write the type of node
232         output.writeByte(nodeType);
233         // Write Start Tag
234         writeQName(qName);
235     }
236
237     private void writeQName(QName qName) throws IOException {
238
239         writeCodedString(qName.getLocalName());
240         writeCodedString(qName.getNamespace().toString());
241         writeCodedString(qName.getFormattedRevision());
242     }
243
244     private void writeCodedString(String key) throws IOException {
245         Integer value = stringCodeMap.get(key);
246         if(value != null) {
247             output.writeByte(TokenTypes.IS_CODE_VALUE);
248             output.writeInt(value);
249         } else {
250             if(key != null) {
251                 output.writeByte(TokenTypes.IS_STRING_VALUE);
252                 stringCodeMap.put(key, Integer.valueOf(stringCodeMap.size()));
253                 output.writeUTF(key);
254             } else {
255                 output.writeByte(TokenTypes.IS_NULL_VALUE);
256             }
257         }
258     }
259
260     private void writeObjSet(Set<?> set) throws IOException {
261         if(!set.isEmpty()){
262             output.writeInt(set.size());
263             for(Object o : set){
264                 if(o instanceof String){
265                     writeCodedString(o.toString());
266                 } else {
267                     throw new IllegalArgumentException("Expected value type to be String but was : " +
268                         o.toString());
269                 }
270             }
271         } else {
272             output.writeInt(0);
273         }
274     }
275
276     @Override
277     public void writeYangInstanceIdentifier(YangInstanceIdentifier identifier) throws IOException {
278         writeSignatureMarkerAndVersionIfNeeded();
279         writeYangInstanceIdentifierInternal(identifier);
280     }
281
282     private void writeYangInstanceIdentifierInternal(YangInstanceIdentifier identifier) throws IOException {
283         Collection<YangInstanceIdentifier.PathArgument> pathArguments = identifier.getPathArguments();
284         output.writeInt(pathArguments.size());
285
286         for(YangInstanceIdentifier.PathArgument pathArgument : pathArguments) {
287             writePathArgument(pathArgument);
288         }
289     }
290
291     @Override
292     public void writePathArgument(YangInstanceIdentifier.PathArgument pathArgument) throws IOException {
293
294         byte type = PathArgumentTypes.getSerializablePathArgumentType(pathArgument);
295
296         output.writeByte(type);
297
298         switch(type) {
299             case PathArgumentTypes.NODE_IDENTIFIER:
300
301                 YangInstanceIdentifier.NodeIdentifier nodeIdentifier =
302                     (YangInstanceIdentifier.NodeIdentifier) pathArgument;
303
304                 writeQName(nodeIdentifier.getNodeType());
305                 break;
306
307             case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES:
308
309                 YangInstanceIdentifier.NodeIdentifierWithPredicates nodeIdentifierWithPredicates =
310                     (YangInstanceIdentifier.NodeIdentifierWithPredicates) pathArgument;
311                 writeQName(nodeIdentifierWithPredicates.getNodeType());
312
313                 writeKeyValueMap(nodeIdentifierWithPredicates.getKeyValues());
314                 break;
315
316             case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
317
318                 YangInstanceIdentifier.NodeWithValue nodeWithValue =
319                     (YangInstanceIdentifier.NodeWithValue) pathArgument;
320
321                 writeQName(nodeWithValue.getNodeType());
322                 writeObject(nodeWithValue.getValue());
323                 break;
324
325             case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
326
327                 YangInstanceIdentifier.AugmentationIdentifier augmentationIdentifier =
328                     (YangInstanceIdentifier.AugmentationIdentifier) pathArgument;
329
330                 // No Qname in augmentation identifier
331                 writeQNameSet(augmentationIdentifier.getPossibleChildNames());
332                 break;
333             default :
334                 throw new IllegalStateException("Unknown node identifier type is found : " + pathArgument.getClass().toString() );
335         }
336     }
337
338     private void writeKeyValueMap(Map<QName, Object> keyValueMap) throws IOException {
339         if(keyValueMap != null && !keyValueMap.isEmpty()) {
340             output.writeInt(keyValueMap.size());
341             Set<QName> qNameSet = keyValueMap.keySet();
342
343             for(QName qName : qNameSet) {
344                 writeQName(qName);
345                 writeObject(keyValueMap.get(qName));
346             }
347         } else {
348             output.writeInt(0);
349         }
350     }
351
352     private void writeQNameSet(Set<QName> children) throws IOException {
353         // Write each child's qname separately, if list is empty send count as 0
354         if(children != null && !children.isEmpty()) {
355             output.writeInt(children.size());
356             for(QName qName : children) {
357                 writeQName(qName);
358             }
359         } else {
360             LOG.debug("augmentation node does not have any child");
361             output.writeInt(0);
362         }
363     }
364
365     private void writeObject(Object value) throws IOException {
366
367         byte type = ValueTypes.getSerializableType(value);
368         // Write object type first
369         output.writeByte(type);
370
371         switch(type) {
372             case ValueTypes.BOOL_TYPE:
373                 output.writeBoolean((Boolean) value);
374                 break;
375             case ValueTypes.QNAME_TYPE:
376                 writeQName((QName) value);
377                 break;
378             case ValueTypes.INT_TYPE:
379                 output.writeInt((Integer) value);
380                 break;
381             case ValueTypes.BYTE_TYPE:
382                 output.writeByte((Byte) value);
383                 break;
384             case ValueTypes.LONG_TYPE:
385                 output.writeLong((Long) value);
386                 break;
387             case ValueTypes.SHORT_TYPE:
388                 output.writeShort((Short) value);
389                 break;
390             case ValueTypes.BITS_TYPE:
391                 writeObjSet((Set<?>) value);
392                 break;
393             case ValueTypes.BINARY_TYPE:
394                 byte[] bytes = (byte[]) value;
395                 output.writeInt(bytes.length);
396                 output.write(bytes);
397                 break;
398             case ValueTypes.YANG_IDENTIFIER_TYPE:
399                 writeYangInstanceIdentifierInternal((YangInstanceIdentifier) value);
400                 break;
401             case ValueTypes.NULL_TYPE :
402                 break;
403             case ValueTypes.STRING_BYTES_TYPE:
404                 final byte[] valueBytes = value.toString().getBytes(StandardCharsets.UTF_8);
405                 output.writeInt(valueBytes.length);
406                 output.write(valueBytes);
407                 break;
408             default:
409                 output.writeUTF(value.toString());
410                 break;
411         }
412     }
413
414     @Override
415     public void write(int b) throws IOException {
416         writeSignatureMarkerAndVersionIfNeeded();
417         output.write(b);
418     }
419
420     @Override
421     public void write(byte[] b) throws IOException {
422         writeSignatureMarkerAndVersionIfNeeded();
423         output.write(b);
424     }
425
426     @Override
427     public void write(byte[] b, int off, int len) throws IOException {
428         writeSignatureMarkerAndVersionIfNeeded();
429         output.write(b, off, len);
430     }
431
432     @Override
433     public void writeBoolean(boolean v) throws IOException {
434         writeSignatureMarkerAndVersionIfNeeded();
435         output.writeBoolean(v);
436     }
437
438     @Override
439     public void writeByte(int v) throws IOException {
440         writeSignatureMarkerAndVersionIfNeeded();
441         output.writeByte(v);
442     }
443
444     @Override
445     public void writeShort(int v) throws IOException {
446         writeSignatureMarkerAndVersionIfNeeded();
447         output.writeShort(v);
448     }
449
450     @Override
451     public void writeChar(int v) throws IOException {
452         writeSignatureMarkerAndVersionIfNeeded();
453         output.writeChar(v);
454     }
455
456     @Override
457     public void writeInt(int v) throws IOException {
458         writeSignatureMarkerAndVersionIfNeeded();
459         output.writeInt(v);
460     }
461
462     @Override
463     public void writeLong(long v) throws IOException {
464         writeSignatureMarkerAndVersionIfNeeded();
465         output.writeLong(v);
466     }
467
468     @Override
469     public void writeFloat(float v) throws IOException {
470         writeSignatureMarkerAndVersionIfNeeded();
471         output.writeFloat(v);
472     }
473
474     @Override
475     public void writeDouble(double v) throws IOException {
476         writeSignatureMarkerAndVersionIfNeeded();
477         output.writeDouble(v);
478     }
479
480     @Override
481     public void writeBytes(String s) throws IOException {
482         writeSignatureMarkerAndVersionIfNeeded();
483         output.writeBytes(s);
484     }
485
486     @Override
487     public void writeChars(String s) throws IOException {
488         writeSignatureMarkerAndVersionIfNeeded();
489         output.writeChars(s);
490     }
491
492     @Override
493     public void writeUTF(String s) throws IOException {
494         writeSignatureMarkerAndVersionIfNeeded();
495         output.writeUTF(s);
496     }
497 }