BUG-4626: Split out stream token types
[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 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     public NormalizedNodeOutputStreamWriter(DataOutput output) {
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         writeSignatureMarkerAndVersionIfNeeded();
78         normalizedNodeWriter().write(node);
79     }
80
81     private void writeSignatureMarkerAndVersionIfNeeded() throws IOException {
82         if(!wroteSignatureMarker) {
83             output.writeByte(TokenTypes.SIGNATURE_MARKER);
84             output.writeShort(TokenTypes.LITHIUM_VERSION);
85             wroteSignatureMarker = true;
86         }
87     }
88
89     @Override
90     public void leafNode(YangInstanceIdentifier.NodeIdentifier name, Object value) throws IOException, IllegalArgumentException {
91         Preconditions.checkNotNull(name, "Node identifier should not be null");
92         LOG.debug("Writing a new leaf node");
93         startNode(name.getNodeType(), NodeTypes.LEAF_NODE);
94
95         writeObject(value);
96     }
97
98     @Override
99     public void startLeafSet(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException {
100         Preconditions.checkNotNull(name, "Node identifier should not be null");
101         LOG.debug("Starting a new leaf set");
102
103         startNode(name.getNodeType(), NodeTypes.LEAF_SET);
104     }
105
106     @Override
107     public void leafSetEntryNode(Object value) throws IOException, IllegalArgumentException {
108         LOG.debug("Writing a new leaf set entry node");
109
110         output.writeByte(NodeTypes.LEAF_SET_ENTRY_NODE);
111         writeObject(value);
112     }
113
114     @Override
115     public void startContainerNode(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException {
116         Preconditions.checkNotNull(name, "Node identifier should not be null");
117
118         LOG.debug("Starting a new container node");
119
120         startNode(name.getNodeType(), NodeTypes.CONTAINER_NODE);
121     }
122
123     @Override
124     public void startYangModeledAnyXmlNode(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException {
125         Preconditions.checkNotNull(name, "Node identifier should not be null");
126
127         LOG.debug("Starting a new yang modeled anyXml node");
128
129         startNode(name.getNodeType(), NodeTypes.YANG_MODELED_ANY_XML_NODE);
130     }
131
132     @Override
133     public void startUnkeyedList(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException {
134         Preconditions.checkNotNull(name, "Node identifier should not be null");
135         LOG.debug("Starting a new unkeyed list");
136
137         startNode(name.getNodeType(), NodeTypes.UNKEYED_LIST);
138     }
139
140     @Override
141     public void startUnkeyedListItem(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalStateException {
142         Preconditions.checkNotNull(name, "Node identifier should not be null");
143         LOG.debug("Starting a new unkeyed list item");
144
145         startNode(name.getNodeType(), NodeTypes.UNKEYED_LIST_ITEM);
146     }
147
148     @Override
149     public void startMapNode(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException {
150         Preconditions.checkNotNull(name, "Node identifier should not be null");
151         LOG.debug("Starting a new map node");
152
153         startNode(name.getNodeType(), NodeTypes.MAP_NODE);
154     }
155
156     @Override
157     public void startMapEntryNode(YangInstanceIdentifier.NodeIdentifierWithPredicates identifier, int childSizeHint) throws IOException, IllegalArgumentException {
158         Preconditions.checkNotNull(identifier, "Node identifier should not be null");
159         LOG.debug("Starting a new map entry node");
160         startNode(identifier.getNodeType(), NodeTypes.MAP_ENTRY_NODE);
161
162         writeKeyValueMap(identifier.getKeyValues());
163
164     }
165
166     @Override
167     public void startOrderedMapNode(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException {
168         Preconditions.checkNotNull(name, "Node identifier should not be null");
169         LOG.debug("Starting a new ordered map node");
170
171         startNode(name.getNodeType(), NodeTypes.ORDERED_MAP_NODE);
172     }
173
174     @Override
175     public void startChoiceNode(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint) throws IOException, IllegalArgumentException {
176         Preconditions.checkNotNull(name, "Node identifier should not be null");
177         LOG.debug("Starting a new choice node");
178
179         startNode(name.getNodeType(), NodeTypes.CHOICE_NODE);
180     }
181
182     @Override
183     public void startAugmentationNode(YangInstanceIdentifier.AugmentationIdentifier identifier) throws IOException, IllegalArgumentException {
184         Preconditions.checkNotNull(identifier, "Node identifier should not be null");
185         LOG.debug("Starting a new augmentation node");
186
187         output.writeByte(NodeTypes.AUGMENTATION_NODE);
188         writeQNameSet(identifier.getPossibleChildNames());
189     }
190
191     @Override
192     public void anyxmlNode(YangInstanceIdentifier.NodeIdentifier name, Object value) throws IOException, IllegalArgumentException {
193         Preconditions.checkNotNull(name, "Node identifier should not be null");
194         LOG.debug("Writing a new xml node");
195
196         startNode(name.getNodeType(), NodeTypes.ANY_XML_NODE);
197
198         writeObject(value);
199     }
200
201     @Override
202     public void endNode() throws IOException, IllegalStateException {
203         LOG.debug("Ending the node");
204
205         output.writeByte(NodeTypes.END_NODE);
206     }
207
208     @Override
209     public void close() throws IOException {
210         flush();
211     }
212
213     @Override
214     public void flush() throws IOException {
215         if (output instanceof OutputStream) {
216             ((OutputStream)output).flush();
217         }
218     }
219
220     private void startNode(final QName qName, byte nodeType) throws IOException {
221
222         Preconditions.checkNotNull(qName, "QName of node identifier should not be null.");
223
224         writeSignatureMarkerAndVersionIfNeeded();
225
226         // First write the type of node
227         output.writeByte(nodeType);
228         // Write Start Tag
229         writeQName(qName);
230     }
231
232     private void writeQName(QName qName) throws IOException {
233
234         writeCodedString(qName.getLocalName());
235         writeCodedString(qName.getNamespace().toString());
236         writeCodedString(qName.getFormattedRevision());
237     }
238
239     private void writeCodedString(String key) throws IOException {
240         Integer value = stringCodeMap.get(key);
241         if(value != null) {
242             output.writeByte(TokenTypes.IS_CODE_VALUE);
243             output.writeInt(value);
244         } else {
245             if(key != null) {
246                 output.writeByte(TokenTypes.IS_STRING_VALUE);
247                 stringCodeMap.put(key, Integer.valueOf(stringCodeMap.size()));
248                 output.writeUTF(key);
249             } else {
250                 output.writeByte(TokenTypes.IS_NULL_VALUE);
251             }
252         }
253     }
254
255     private void writeObjSet(Set<?> set) throws IOException {
256         if(!set.isEmpty()){
257             output.writeInt(set.size());
258             for(Object o : set){
259                 if(o instanceof String){
260                     writeCodedString(o.toString());
261                 } else {
262                     throw new IllegalArgumentException("Expected value type to be String but was : " +
263                         o.toString());
264                 }
265             }
266         } else {
267             output.writeInt(0);
268         }
269     }
270
271     public void writeYangInstanceIdentifier(YangInstanceIdentifier identifier) throws IOException {
272         writeSignatureMarkerAndVersionIfNeeded();
273         writeYangInstanceIdentifierInternal(identifier);
274     }
275
276     private void writeYangInstanceIdentifierInternal(YangInstanceIdentifier identifier) throws IOException {
277         Collection<YangInstanceIdentifier.PathArgument> pathArguments = identifier.getPathArguments();
278         output.writeInt(pathArguments.size());
279
280         for(YangInstanceIdentifier.PathArgument pathArgument : pathArguments) {
281             writePathArgument(pathArgument);
282         }
283     }
284
285     public void writePathArgument(YangInstanceIdentifier.PathArgument pathArgument) throws IOException {
286
287         byte type = PathArgumentTypes.getSerializablePathArgumentType(pathArgument);
288
289         output.writeByte(type);
290
291         switch(type) {
292             case PathArgumentTypes.NODE_IDENTIFIER :
293
294                 YangInstanceIdentifier.NodeIdentifier nodeIdentifier =
295                     (YangInstanceIdentifier.NodeIdentifier) pathArgument;
296
297                 writeQName(nodeIdentifier.getNodeType());
298                 break;
299
300             case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES:
301
302                 YangInstanceIdentifier.NodeIdentifierWithPredicates nodeIdentifierWithPredicates =
303                     (YangInstanceIdentifier.NodeIdentifierWithPredicates) pathArgument;
304                 writeQName(nodeIdentifierWithPredicates.getNodeType());
305
306                 writeKeyValueMap(nodeIdentifierWithPredicates.getKeyValues());
307                 break;
308
309             case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
310
311                 YangInstanceIdentifier.NodeWithValue nodeWithValue =
312                     (YangInstanceIdentifier.NodeWithValue) pathArgument;
313
314                 writeQName(nodeWithValue.getNodeType());
315                 writeObject(nodeWithValue.getValue());
316                 break;
317
318             case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
319
320                 YangInstanceIdentifier.AugmentationIdentifier augmentationIdentifier =
321                     (YangInstanceIdentifier.AugmentationIdentifier) pathArgument;
322
323                 // No Qname in augmentation identifier
324                 writeQNameSet(augmentationIdentifier.getPossibleChildNames());
325                 break;
326             default :
327                 throw new IllegalStateException("Unknown node identifier type is found : " + pathArgument.getClass().toString() );
328         }
329     }
330
331     private void writeKeyValueMap(Map<QName, Object> keyValueMap) throws IOException {
332         if(keyValueMap != null && !keyValueMap.isEmpty()) {
333             output.writeInt(keyValueMap.size());
334             Set<QName> qNameSet = keyValueMap.keySet();
335
336             for(QName qName : qNameSet) {
337                 writeQName(qName);
338                 writeObject(keyValueMap.get(qName));
339             }
340         } else {
341             output.writeInt(0);
342         }
343     }
344
345     private void writeQNameSet(Set<QName> children) throws IOException {
346         // Write each child's qname separately, if list is empty send count as 0
347         if(children != null && !children.isEmpty()) {
348             output.writeInt(children.size());
349             for(QName qName : children) {
350                 writeQName(qName);
351             }
352         } else {
353             LOG.debug("augmentation node does not have any child");
354             output.writeInt(0);
355         }
356     }
357
358     private void writeObject(Object value) throws IOException {
359
360         byte type = ValueTypes.getSerializableType(value);
361         // Write object type first
362         output.writeByte(type);
363
364         switch(type) {
365             case ValueTypes.BOOL_TYPE:
366                 output.writeBoolean((Boolean) value);
367                 break;
368             case ValueTypes.QNAME_TYPE:
369                 writeQName((QName) value);
370                 break;
371             case ValueTypes.INT_TYPE:
372                 output.writeInt((Integer) value);
373                 break;
374             case ValueTypes.BYTE_TYPE:
375                 output.writeByte((Byte) value);
376                 break;
377             case ValueTypes.LONG_TYPE:
378                 output.writeLong((Long) value);
379                 break;
380             case ValueTypes.SHORT_TYPE:
381                 output.writeShort((Short) value);
382                 break;
383             case ValueTypes.BITS_TYPE:
384                 writeObjSet((Set<?>) value);
385                 break;
386             case ValueTypes.BINARY_TYPE:
387                 byte[] bytes = (byte[]) value;
388                 output.writeInt(bytes.length);
389                 output.write(bytes);
390                 break;
391             case ValueTypes.YANG_IDENTIFIER_TYPE:
392                 writeYangInstanceIdentifierInternal((YangInstanceIdentifier) value);
393                 break;
394             case ValueTypes.NULL_TYPE :
395                 break;
396             case ValueTypes.STRING_BYTES_TYPE:
397                 final byte[] valueBytes = value.toString().getBytes(StandardCharsets.UTF_8);
398                 output.writeInt(valueBytes.length);
399                 output.write(valueBytes);
400                 break;
401             default:
402                 output.writeUTF(value.toString());
403                 break;
404         }
405     }
406 }