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