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