Bug 2062 - StreamWriter APIs loses information about leaf-set ordering
[controller.git] / opendaylight / md-sal / sal-clustering-commons / src / main / java / org / opendaylight / controller / cluster / datastore / node / utils / stream / NormalizedNodeOutputStreamWriter.java
1 /*
2  *
3  *  Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
4  *
5  *  This program and the accompanying materials are made available under the
6  *  terms of the Eclipse Public License v1.0 which accompanies this distribution,
7  *  and is available at http://www.eclipse.org/legal/epl-v10.html
8  *
9  */
10
11 package org.opendaylight.controller.cluster.datastore.node.utils.stream;
12
13 import com.google.common.base.Preconditions;
14 import java.io.DataOutput;
15 import java.io.DataOutputStream;
16 import java.io.IOException;
17 import java.io.OutputStream;
18 import java.nio.charset.StandardCharsets;
19 import java.util.Collection;
20 import java.util.HashMap;
21 import java.util.Map;
22 import java.util.Set;
23 import org.opendaylight.yangtools.yang.common.QName;
24 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
25 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
26 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
27 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 /**
32  * NormalizedNodeOutputStreamWriter will be used by distributed datastore to send normalized node in
33  * a stream.
34  * A stream writer wrapper around this class will write node objects to stream in recursive manner.
35  * for example - If you have a ContainerNode which has a two LeafNode as children, then
36  * you will first call {@link #startContainerNode(YangInstanceIdentifier.NodeIdentifier, int)}, then will call
37  * {@link #leafNode(YangInstanceIdentifier.NodeIdentifier, Object)} twice and then, {@link #endNode()} to end
38  * container node.
39  *
40  * Based on the each node, the node type is also written to the stream, that helps in reconstructing the object,
41  * while reading.
42  *
43  *
44  */
45
46 public class NormalizedNodeOutputStreamWriter implements NormalizedNodeStreamWriter {
47
48     private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeOutputStreamWriter.class);
49
50     static final byte SIGNATURE_MARKER = (byte) 0xab;
51     static final short CURRENT_VERSION = (short) 1;
52
53     static final byte IS_CODE_VALUE = 1;
54     static final byte IS_STRING_VALUE = 2;
55     static final byte IS_NULL_VALUE = 3;
56
57     private final DataOutput output;
58
59     private final Map<String, Integer> stringCodeMap = new HashMap<>();
60
61     private NormalizedNodeWriter normalizedNodeWriter;
62
63     private boolean wroteSignatureMarker;
64
65     public NormalizedNodeOutputStreamWriter(OutputStream stream) throws IOException {
66         Preconditions.checkNotNull(stream);
67         output = new DataOutputStream(stream);
68     }
69
70     public NormalizedNodeOutputStreamWriter(DataOutput output) {
71         this.output = Preconditions.checkNotNull(output);
72     }
73
74     private NormalizedNodeWriter normalizedNodeWriter() {
75         if(normalizedNodeWriter == null) {
76             normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(this);
77         }
78
79         return normalizedNodeWriter;
80     }
81
82     public void writeNormalizedNode(NormalizedNode<?, ?> node) throws IOException {
83         writeSignatureMarkerAndVersionIfNeeded();
84         normalizedNodeWriter().write(node);
85     }
86
87     private void writeSignatureMarkerAndVersionIfNeeded() throws IOException {
88         if(!wroteSignatureMarker) {
89             output.writeByte(SIGNATURE_MARKER);
90             output.writeShort(CURRENT_VERSION);
91             wroteSignatureMarker = true;
92         }
93     }
94
95     @Override
96     public void leafNode(YangInstanceIdentifier.NodeIdentifier name, Object value) throws IOException, IllegalArgumentException {
97         Preconditions.checkNotNull(name, "Node identifier should not be null");
98         LOG.debug("Writing a new leaf node");
99         startNode(name.getNodeType(), NodeTypes.LEAF_NODE);
100
101         writeObject(value);
102     }
103
104     @Override
105     public void startLeafSet(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException {
106         Preconditions.checkNotNull(name, "Node identifier should not be null");
107         LOG.debug("Starting a new leaf set");
108
109         startNode(name.getNodeType(), NodeTypes.LEAF_SET);
110     }
111
112     @Override
113     public void startOrderedLeafSet(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException {
114         Preconditions.checkNotNull(name, "Node identifier should not be null");
115         LOG.debug("Starting a new ordered leaf set");
116
117         startNode(name.getNodeType(), NodeTypes.ORDERED_LEAF_SET);
118     }
119
120     @Override
121     public void leafSetEntryNode(Object value) throws IOException, IllegalArgumentException {
122         LOG.debug("Writing a new leaf set entry node");
123
124         output.writeByte(NodeTypes.LEAF_SET_ENTRY_NODE);
125         writeObject(value);
126     }
127
128     @Override
129     public void startContainerNode(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 container node");
133
134         startNode(name.getNodeType(), NodeTypes.CONTAINER_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(IS_CODE_VALUE);
248             output.writeInt(value);
249         } else {
250             if(key != null) {
251                 output.writeByte(IS_STRING_VALUE);
252                 stringCodeMap.put(key, Integer.valueOf(stringCodeMap.size()));
253                 output.writeUTF(key);
254             } else {
255                 output.writeByte(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     public void writeYangInstanceIdentifier(YangInstanceIdentifier identifier) throws IOException {
277         writeSignatureMarkerAndVersionIfNeeded();
278         writeYangInstanceIdentifierInternal(identifier);
279     }
280
281     private void writeYangInstanceIdentifierInternal(YangInstanceIdentifier identifier) throws IOException {
282         Collection<YangInstanceIdentifier.PathArgument> pathArguments = identifier.getPathArguments();
283         output.writeInt(pathArguments.size());
284
285         for(YangInstanceIdentifier.PathArgument pathArgument : pathArguments) {
286             writePathArgument(pathArgument);
287         }
288     }
289
290     public void writePathArgument(YangInstanceIdentifier.PathArgument pathArgument) throws IOException {
291
292         byte type = PathArgumentTypes.getSerializablePathArgumentType(pathArgument);
293
294         output.writeByte(type);
295
296         switch(type) {
297             case PathArgumentTypes.NODE_IDENTIFIER :
298
299                 YangInstanceIdentifier.NodeIdentifier nodeIdentifier =
300                     (YangInstanceIdentifier.NodeIdentifier) pathArgument;
301
302                 writeQName(nodeIdentifier.getNodeType());
303                 break;
304
305             case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES:
306
307                 YangInstanceIdentifier.NodeIdentifierWithPredicates nodeIdentifierWithPredicates =
308                     (YangInstanceIdentifier.NodeIdentifierWithPredicates) pathArgument;
309                 writeQName(nodeIdentifierWithPredicates.getNodeType());
310
311                 writeKeyValueMap(nodeIdentifierWithPredicates.getKeyValues());
312                 break;
313
314             case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
315
316                 YangInstanceIdentifier.NodeWithValue nodeWithValue =
317                     (YangInstanceIdentifier.NodeWithValue) pathArgument;
318
319                 writeQName(nodeWithValue.getNodeType());
320                 writeObject(nodeWithValue.getValue());
321                 break;
322
323             case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
324
325                 YangInstanceIdentifier.AugmentationIdentifier augmentationIdentifier =
326                     (YangInstanceIdentifier.AugmentationIdentifier) pathArgument;
327
328                 // No Qname in augmentation identifier
329                 writeQNameSet(augmentationIdentifier.getPossibleChildNames());
330                 break;
331             default :
332                 throw new IllegalStateException("Unknown node identifier type is found : " + pathArgument.getClass().toString() );
333         }
334     }
335
336     private void writeKeyValueMap(Map<QName, Object> keyValueMap) throws IOException {
337         if(keyValueMap != null && !keyValueMap.isEmpty()) {
338             output.writeInt(keyValueMap.size());
339             Set<QName> qNameSet = keyValueMap.keySet();
340
341             for(QName qName : qNameSet) {
342                 writeQName(qName);
343                 writeObject(keyValueMap.get(qName));
344             }
345         } else {
346             output.writeInt(0);
347         }
348     }
349
350     private void writeQNameSet(Set<QName> children) throws IOException {
351         // Write each child's qname separately, if list is empty send count as 0
352         if(children != null && !children.isEmpty()) {
353             output.writeInt(children.size());
354             for(QName qName : children) {
355                 writeQName(qName);
356             }
357         } else {
358             LOG.debug("augmentation node does not have any child");
359             output.writeInt(0);
360         }
361     }
362
363     private void writeObject(Object value) throws IOException {
364
365         byte type = ValueTypes.getSerializableType(value);
366         // Write object type first
367         output.writeByte(type);
368
369         switch(type) {
370             case ValueTypes.BOOL_TYPE:
371                 output.writeBoolean((Boolean) value);
372                 break;
373             case ValueTypes.QNAME_TYPE:
374                 writeQName((QName) value);
375                 break;
376             case ValueTypes.INT_TYPE:
377                 output.writeInt((Integer) value);
378                 break;
379             case ValueTypes.BYTE_TYPE:
380                 output.writeByte((Byte) value);
381                 break;
382             case ValueTypes.LONG_TYPE:
383                 output.writeLong((Long) value);
384                 break;
385             case ValueTypes.SHORT_TYPE:
386                 output.writeShort((Short) value);
387                 break;
388             case ValueTypes.BITS_TYPE:
389                 writeObjSet((Set<?>) value);
390                 break;
391             case ValueTypes.BINARY_TYPE:
392                 byte[] bytes = (byte[]) value;
393                 output.writeInt(bytes.length);
394                 output.write(bytes);
395                 break;
396             case ValueTypes.YANG_IDENTIFIER_TYPE:
397                 writeYangInstanceIdentifierInternal((YangInstanceIdentifier) value);
398                 break;
399             case ValueTypes.NULL_TYPE :
400                 break;
401             case ValueTypes.STRING_BYTES_TYPE:
402                 final byte[] valueBytes = value.toString().getBytes(StandardCharsets.UTF_8);
403                 output.writeInt(valueBytes.length);
404                 output.write(valueBytes);
405                 break;
406             default:
407                 output.writeUTF(value.toString());
408                 break;
409         }
410     }
411 }