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