Bug 2268: Use streaming for Modification payload
[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 com.google.common.collect.Iterables;
15 import java.io.DataOutput;
16 import java.io.DataOutputStream;
17 import java.io.IOException;
18 import java.io.OutputStream;
19 import java.util.HashMap;
20 import java.util.Map;
21 import java.util.Set;
22 import org.opendaylight.yangtools.yang.common.QName;
23 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
24 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
25 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
26 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 /**
31  * NormalizedNodeOutputStreamWriter will be used by distributed datastore to send normalized node in
32  * a stream.
33  * A stream writer wrapper around this class will write node objects to stream in recursive manner.
34  * for example - If you have a ContainerNode which has a two LeafNode as children, then
35  * you will first call {@link #startContainerNode(YangInstanceIdentifier.NodeIdentifier, int)}, then will call
36  * {@link #leafNode(YangInstanceIdentifier.NodeIdentifier, Object)} twice and then, {@link #endNode()} to end
37  * container node.
38  *
39  * Based on the each node, the node type is also written to the stream, that helps in reconstructing the object,
40  * while reading.
41  *
42  *
43  */
44
45 public class NormalizedNodeOutputStreamWriter implements NormalizedNodeStreamWriter {
46
47     private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeOutputStreamWriter.class);
48
49     static final byte IS_CODE_VALUE = 1;
50     static final byte IS_STRING_VALUE = 2;
51     static final byte IS_NULL_VALUE = 3;
52
53     private final DataOutput output;
54
55     private final Map<String, Integer> stringCodeMap = new HashMap<>();
56
57     private NormalizedNodeWriter normalizedNodeWriter;
58
59     public NormalizedNodeOutputStreamWriter(OutputStream stream) throws IOException {
60         Preconditions.checkNotNull(stream);
61         output = new DataOutputStream(stream);
62     }
63
64     public NormalizedNodeOutputStreamWriter(DataOutput output) throws IOException {
65         this.output = Preconditions.checkNotNull(output);
66     }
67
68     private NormalizedNodeWriter normalizedNodeWriter() {
69         if(normalizedNodeWriter == null) {
70             normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(this);
71         }
72
73         return normalizedNodeWriter;
74     }
75
76     public void writeNormalizedNode(NormalizedNode<?, ?> node) throws IOException {
77         normalizedNodeWriter().write(node);
78     }
79
80     @Override
81     public void leafNode(YangInstanceIdentifier.NodeIdentifier name, Object value) throws IOException, IllegalArgumentException {
82         Preconditions.checkNotNull(name, "Node identifier should not be null");
83         LOG.debug("Writing a new leaf node");
84         startNode(name.getNodeType(), NodeTypes.LEAF_NODE);
85
86         writeObject(value);
87     }
88
89     @Override
90     public void startLeafSet(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException {
91         Preconditions.checkNotNull(name, "Node identifier should not be null");
92         LOG.debug("Starting a new leaf set");
93
94         startNode(name.getNodeType(), NodeTypes.LEAF_SET);
95     }
96
97     @Override
98     public void leafSetEntryNode(Object value) throws IOException, IllegalArgumentException {
99         LOG.debug("Writing a new leaf set entry node");
100
101         output.writeByte(NodeTypes.LEAF_SET_ENTRY_NODE);
102         writeObject(value);
103     }
104
105     @Override
106     public void startContainerNode(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException {
107         Preconditions.checkNotNull(name, "Node identifier should not be null");
108
109         LOG.debug("Starting a new container node");
110
111         startNode(name.getNodeType(), NodeTypes.CONTAINER_NODE);
112     }
113
114     @Override
115     public void startUnkeyedList(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException {
116         Preconditions.checkNotNull(name, "Node identifier should not be null");
117         LOG.debug("Starting a new unkeyed list");
118
119         startNode(name.getNodeType(), NodeTypes.UNKEYED_LIST);
120     }
121
122     @Override
123     public void startUnkeyedListItem(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalStateException {
124         Preconditions.checkNotNull(name, "Node identifier should not be null");
125         LOG.debug("Starting a new unkeyed list item");
126
127         startNode(name.getNodeType(), NodeTypes.UNKEYED_LIST_ITEM);
128     }
129
130     @Override
131     public void startMapNode(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException {
132         Preconditions.checkNotNull(name, "Node identifier should not be null");
133         LOG.debug("Starting a new map node");
134
135         startNode(name.getNodeType(), NodeTypes.MAP_NODE);
136     }
137
138     @Override
139     public void startMapEntryNode(YangInstanceIdentifier.NodeIdentifierWithPredicates identifier, int childSizeHint) throws IOException, IllegalArgumentException {
140         Preconditions.checkNotNull(identifier, "Node identifier should not be null");
141         LOG.debug("Starting a new map entry node");
142         startNode(identifier.getNodeType(), NodeTypes.MAP_ENTRY_NODE);
143
144         writeKeyValueMap(identifier.getKeyValues());
145
146     }
147
148     @Override
149     public void startOrderedMapNode(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException {
150         Preconditions.checkNotNull(name, "Node identifier should not be null");
151         LOG.debug("Starting a new ordered map node");
152
153         startNode(name.getNodeType(), NodeTypes.ORDERED_MAP_NODE);
154     }
155
156     @Override
157     public void startChoiceNode(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException {
158         Preconditions.checkNotNull(name, "Node identifier should not be null");
159         LOG.debug("Starting a new choice node");
160
161         startNode(name.getNodeType(), NodeTypes.CHOICE_NODE);
162     }
163
164     @Override
165     public void startAugmentationNode(YangInstanceIdentifier.AugmentationIdentifier identifier) throws IOException, IllegalArgumentException {
166         Preconditions.checkNotNull(identifier, "Node identifier should not be null");
167         LOG.debug("Starting a new augmentation node");
168
169         output.writeByte(NodeTypes.AUGMENTATION_NODE);
170         writeQNameSet(identifier.getPossibleChildNames());
171     }
172
173     @Override
174     public void anyxmlNode(YangInstanceIdentifier.NodeIdentifier name, Object value) throws IOException, IllegalArgumentException {
175         Preconditions.checkNotNull(name, "Node identifier should not be null");
176         LOG.debug("Writing a new xml node");
177
178         startNode(name.getNodeType(), NodeTypes.ANY_XML_NODE);
179
180         writeObject(value);
181     }
182
183     @Override
184     public void endNode() throws IOException, IllegalStateException {
185         LOG.debug("Ending the node");
186
187         output.writeByte(NodeTypes.END_NODE);
188     }
189
190     @Override
191     public void close() throws IOException {
192     }
193
194     @Override
195     public void flush() throws IOException {
196         if (output instanceof OutputStream) {
197             ((OutputStream)output).flush();
198         }
199     }
200
201     private void startNode(final QName qName, byte nodeType) throws IOException {
202
203         Preconditions.checkNotNull(qName, "QName of node identifier should not be null.");
204         // First write the type of node
205         output.writeByte(nodeType);
206         // Write Start Tag
207         writeQName(qName);
208     }
209
210     private void writeQName(QName qName) throws IOException {
211
212         writeCodedString(qName.getLocalName());
213         writeCodedString(qName.getNamespace().toString());
214         writeCodedString(qName.getFormattedRevision());
215     }
216
217     private void writeCodedString(String key) throws IOException {
218         Integer value = stringCodeMap.get(key);
219         if(value != null) {
220             output.writeByte(IS_CODE_VALUE);
221             output.writeInt(value);
222         } else {
223             if(key != null) {
224                 output.writeByte(IS_STRING_VALUE);
225                 stringCodeMap.put(key, Integer.valueOf(stringCodeMap.size()));
226                 output.writeUTF(key);
227             } else {
228                 output.writeByte(IS_NULL_VALUE);
229             }
230         }
231     }
232
233     private void writeObjSet(Set<?> set) throws IOException {
234         if(!set.isEmpty()){
235             output.writeInt(set.size());
236             for(Object o : set){
237                 if(o instanceof String){
238                     writeCodedString(o.toString());
239                 } else {
240                     throw new IllegalArgumentException("Expected value type to be String but was : " +
241                         o.toString());
242                 }
243             }
244         } else {
245             output.writeInt(0);
246         }
247     }
248
249     public void writeYangInstanceIdentifier(YangInstanceIdentifier identifier) throws IOException {
250         Iterable<YangInstanceIdentifier.PathArgument> pathArguments = identifier.getPathArguments();
251         int size = Iterables.size(pathArguments);
252         output.writeInt(size);
253
254         for(YangInstanceIdentifier.PathArgument pathArgument : pathArguments) {
255             writePathArgument(pathArgument);
256         }
257     }
258
259     private void writePathArgument(YangInstanceIdentifier.PathArgument pathArgument) throws IOException {
260
261         byte type = PathArgumentTypes.getSerializablePathArgumentType(pathArgument);
262
263         output.writeByte(type);
264
265         switch(type) {
266             case PathArgumentTypes.NODE_IDENTIFIER :
267
268                 YangInstanceIdentifier.NodeIdentifier nodeIdentifier =
269                     (YangInstanceIdentifier.NodeIdentifier) pathArgument;
270
271                 writeQName(nodeIdentifier.getNodeType());
272                 break;
273
274             case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES:
275
276                 YangInstanceIdentifier.NodeIdentifierWithPredicates nodeIdentifierWithPredicates =
277                     (YangInstanceIdentifier.NodeIdentifierWithPredicates) pathArgument;
278                 writeQName(nodeIdentifierWithPredicates.getNodeType());
279
280                 writeKeyValueMap(nodeIdentifierWithPredicates.getKeyValues());
281                 break;
282
283             case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
284
285                 YangInstanceIdentifier.NodeWithValue nodeWithValue =
286                     (YangInstanceIdentifier.NodeWithValue) pathArgument;
287
288                 writeQName(nodeWithValue.getNodeType());
289                 writeObject(nodeWithValue.getValue());
290                 break;
291
292             case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
293
294                 YangInstanceIdentifier.AugmentationIdentifier augmentationIdentifier =
295                     (YangInstanceIdentifier.AugmentationIdentifier) pathArgument;
296
297                 // No Qname in augmentation identifier
298                 writeQNameSet(augmentationIdentifier.getPossibleChildNames());
299                 break;
300             default :
301                 throw new IllegalStateException("Unknown node identifier type is found : " + pathArgument.getClass().toString() );
302         }
303     }
304
305     private void writeKeyValueMap(Map<QName, Object> keyValueMap) throws IOException {
306         if(keyValueMap != null && !keyValueMap.isEmpty()) {
307             output.writeInt(keyValueMap.size());
308             Set<QName> qNameSet = keyValueMap.keySet();
309
310             for(QName qName : qNameSet) {
311                 writeQName(qName);
312                 writeObject(keyValueMap.get(qName));
313             }
314         } else {
315             output.writeInt(0);
316         }
317     }
318
319     private void writeQNameSet(Set<QName> children) throws IOException {
320         // Write each child's qname separately, if list is empty send count as 0
321         if(children != null && !children.isEmpty()) {
322             output.writeInt(children.size());
323             for(QName qName : children) {
324                 writeQName(qName);
325             }
326         } else {
327             LOG.debug("augmentation node does not have any child");
328             output.writeInt(0);
329         }
330     }
331
332     private void writeObject(Object value) throws IOException {
333
334         byte type = ValueTypes.getSerializableType(value);
335         // Write object type first
336         output.writeByte(type);
337
338         switch(type) {
339             case ValueTypes.BOOL_TYPE:
340                 output.writeBoolean((Boolean) value);
341                 break;
342             case ValueTypes.QNAME_TYPE:
343                 writeQName((QName) value);
344                 break;
345             case ValueTypes.INT_TYPE:
346                 output.writeInt((Integer) value);
347                 break;
348             case ValueTypes.BYTE_TYPE:
349                 output.writeByte((Byte) value);
350                 break;
351             case ValueTypes.LONG_TYPE:
352                 output.writeLong((Long) value);
353                 break;
354             case ValueTypes.SHORT_TYPE:
355                 output.writeShort((Short) value);
356                 break;
357             case ValueTypes.BITS_TYPE:
358                 writeObjSet((Set<?>) value);
359                 break;
360             case ValueTypes.BINARY_TYPE:
361                 byte[] bytes = (byte[]) value;
362                 output.writeInt(bytes.length);
363                 output.write(bytes);
364                 break;
365             case ValueTypes.YANG_IDENTIFIER_TYPE:
366                 writeYangInstanceIdentifier((YangInstanceIdentifier) value);
367                 break;
368             default:
369                 output.writeUTF(value.toString());
370                 break;
371         }
372     }
373 }