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