BUG 4589 : Handle writing and reading large strings
[controller.git] / opendaylight / md-sal / sal-clustering-commons / src / main / java / org / opendaylight / controller / cluster / datastore / node / utils / stream / NormalizedNodeInputStreamReader.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.base.Strings;
15 import java.io.DataInput;
16 import java.io.DataInputStream;
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.math.BigDecimal;
20 import java.math.BigInteger;
21 import java.nio.charset.StandardCharsets;
22 import java.util.ArrayList;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Set;
28 import javax.xml.transform.dom.DOMSource;
29 import org.opendaylight.controller.cluster.datastore.node.utils.QNameFactory;
30 import org.opendaylight.yangtools.yang.common.QName;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
36 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
39 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
40 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
41 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
42 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 /**
47  * NormalizedNodeInputStreamReader reads the byte stream and constructs the normalized node including its children nodes.
48  * This process goes in recursive manner, where each NodeTypes object signifies the start of the object, except END_NODE.
49  * If a node can have children, then that node's end is calculated based on appearance of END_NODE.
50  *
51  */
52
53 public class NormalizedNodeInputStreamReader implements NormalizedNodeStreamReader {
54
55     private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeInputStreamReader.class);
56
57     private static final String REVISION_ARG = "?revision=";
58
59     private final DataInput input;
60
61     private final Map<Integer, String> codedStringMap = new HashMap<>();
62
63     private QName lastLeafSetQName;
64
65     private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
66                                       Object, LeafNode<Object>> leafBuilder;
67
68     private NormalizedNodeAttrBuilder<NodeWithValue, Object,
69                                       LeafSetEntryNode<Object>> leafSetEntryBuilder;
70
71     private final StringBuilder reusableStringBuilder = new StringBuilder(50);
72
73     private boolean readSignatureMarker = true;
74
75     public NormalizedNodeInputStreamReader(InputStream stream) throws IOException {
76         Preconditions.checkNotNull(stream);
77         input = new DataInputStream(stream);
78     }
79
80     public NormalizedNodeInputStreamReader(DataInput input) {
81         this.input = Preconditions.checkNotNull(input);
82     }
83
84     @Override
85     public NormalizedNode<?, ?> readNormalizedNode() throws IOException {
86         readSignatureMarkerAndVersionIfNeeded();
87         return readNormalizedNodeInternal();
88     }
89
90     private void readSignatureMarkerAndVersionIfNeeded() throws IOException {
91         if(readSignatureMarker) {
92             readSignatureMarker = false;
93
94             byte marker = input.readByte();
95             if(marker != NormalizedNodeOutputStreamWriter.SIGNATURE_MARKER) {
96                 throw new InvalidNormalizedNodeStreamException(String.format(
97                         "Invalid signature marker: %d", marker));
98             }
99
100             input.readShort(); // read the version - not currently used/needed.
101         }
102     }
103
104     private NormalizedNode<?, ?> readNormalizedNodeInternal() throws IOException {
105         // each node should start with a byte
106         byte nodeType = input.readByte();
107
108         if(nodeType == NodeTypes.END_NODE) {
109             LOG.debug("End node reached. return");
110             return null;
111         }
112
113         switch(nodeType) {
114             case NodeTypes.AUGMENTATION_NODE :
115                 YangInstanceIdentifier.AugmentationIdentifier augIdentifier =
116                     new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
117
118                 LOG.debug("Reading augmentation node {} ", augIdentifier);
119
120                 return addDataContainerChildren(Builders.augmentationBuilder().
121                         withNodeIdentifier(augIdentifier)).build();
122
123             case NodeTypes.LEAF_SET_ENTRY_NODE :
124                 Object value = readObject();
125                 NodeWithValue leafIdentifier = new NodeWithValue(lastLeafSetQName, value);
126
127                 LOG.debug("Reading leaf set entry node {}, value {}", leafIdentifier, value);
128
129                 return leafSetEntryBuilder().withNodeIdentifier(leafIdentifier).withValue(value).build();
130
131             case NodeTypes.MAP_ENTRY_NODE :
132                 NodeIdentifierWithPredicates entryIdentifier = new NodeIdentifierWithPredicates(
133                         readQName(), readKeyValueMap());
134
135                 LOG.debug("Reading map entry node {} ", entryIdentifier);
136
137                 return addDataContainerChildren(Builders.mapEntryBuilder().
138                         withNodeIdentifier(entryIdentifier)).build();
139
140             default :
141                 return readNodeIdentifierDependentNode(nodeType, new NodeIdentifier(readQName()));
142         }
143     }
144
145     private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
146                                       Object, LeafNode<Object>> leafBuilder() {
147         if(leafBuilder == null) {
148             leafBuilder = Builders.leafBuilder();
149         }
150
151         return leafBuilder;
152     }
153
154     private NormalizedNodeAttrBuilder<NodeWithValue, Object,
155                                       LeafSetEntryNode<Object>> leafSetEntryBuilder() {
156         if(leafSetEntryBuilder == null) {
157             leafSetEntryBuilder = Builders.leafSetEntryBuilder();
158         }
159
160         return leafSetEntryBuilder;
161     }
162
163     private NormalizedNode<?, ?> readNodeIdentifierDependentNode(byte nodeType, NodeIdentifier identifier)
164         throws IOException {
165
166         switch(nodeType) {
167             case NodeTypes.LEAF_NODE :
168                 LOG.debug("Read leaf node {}", identifier);
169                 // Read the object value
170                 return leafBuilder().withNodeIdentifier(identifier).withValue(readObject()).build();
171
172             case NodeTypes.ANY_XML_NODE :
173                 LOG.debug("Read xml node");
174                 return Builders.anyXmlBuilder().withValue((DOMSource) readObject()).build();
175
176             case NodeTypes.MAP_NODE :
177                 LOG.debug("Read map node {}", identifier);
178                 return addDataContainerChildren(Builders.mapBuilder().
179                         withNodeIdentifier(identifier)).build();
180
181             case NodeTypes.CHOICE_NODE :
182                 LOG.debug("Read choice node {}", identifier);
183                 return addDataContainerChildren(Builders.choiceBuilder().
184                         withNodeIdentifier(identifier)).build();
185
186             case NodeTypes.ORDERED_MAP_NODE :
187                 LOG.debug("Reading ordered map node {}", identifier);
188                 return addDataContainerChildren(Builders.orderedMapBuilder().
189                         withNodeIdentifier(identifier)).build();
190
191             case NodeTypes.UNKEYED_LIST :
192                 LOG.debug("Read unkeyed list node {}", identifier);
193                 return addDataContainerChildren(Builders.unkeyedListBuilder().
194                         withNodeIdentifier(identifier)).build();
195
196             case NodeTypes.UNKEYED_LIST_ITEM :
197                 LOG.debug("Read unkeyed list item node {}", identifier);
198                 return addDataContainerChildren(Builders.unkeyedListEntryBuilder().
199                         withNodeIdentifier(identifier)).build();
200
201             case NodeTypes.CONTAINER_NODE :
202                 LOG.debug("Read container node {}", identifier);
203                 return addDataContainerChildren(Builders.containerBuilder().
204                         withNodeIdentifier(identifier)).build();
205
206             case NodeTypes.LEAF_SET :
207                 LOG.debug("Read leaf set node {}", identifier);
208                 return addLeafSetChildren(identifier.getNodeType(),
209                         Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
210
211             default :
212                 return null;
213         }
214     }
215
216     private QName readQName() throws IOException {
217         // Read in the same sequence of writing
218         String localName = readCodedString();
219         String namespace = readCodedString();
220         String revision = readCodedString();
221
222         String qName;
223         if(!Strings.isNullOrEmpty(revision)) {
224             qName = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG).
225                         append(revision).append(')').append(localName).toString();
226         } else {
227             qName = reusableStringBuilder.append('(').append(namespace).append(')').
228                         append(localName).toString();
229         }
230
231         reusableStringBuilder.delete(0, reusableStringBuilder.length());
232         return QNameFactory.create(qName);
233     }
234
235
236     private String readCodedString() throws IOException {
237         byte valueType = input.readByte();
238         if(valueType == NormalizedNodeOutputStreamWriter.IS_CODE_VALUE) {
239             return codedStringMap.get(input.readInt());
240         } else if(valueType == NormalizedNodeOutputStreamWriter.IS_STRING_VALUE) {
241             String value = input.readUTF().intern();
242             codedStringMap.put(Integer.valueOf(codedStringMap.size()), value);
243             return value;
244         }
245
246         return null;
247     }
248
249     private Set<QName> readQNameSet() throws IOException{
250         // Read the children count
251         int count = input.readInt();
252         Set<QName> children = new HashSet<>(count);
253         for(int i = 0; i < count; i++) {
254             children.add(readQName());
255         }
256         return children;
257     }
258
259     private Map<QName, Object> readKeyValueMap() throws IOException {
260         int count = input.readInt();
261         Map<QName, Object> keyValueMap = new HashMap<>(count);
262
263         for(int i = 0; i < count; i++) {
264             keyValueMap.put(readQName(), readObject());
265         }
266
267         return keyValueMap;
268     }
269
270     private Object readObject() throws IOException {
271         byte objectType = input.readByte();
272         switch(objectType) {
273             case ValueTypes.BITS_TYPE:
274                 return readObjSet();
275
276             case ValueTypes.BOOL_TYPE :
277                 return Boolean.valueOf(input.readBoolean());
278
279             case ValueTypes.BYTE_TYPE :
280                 return Byte.valueOf(input.readByte());
281
282             case ValueTypes.INT_TYPE :
283                 return Integer.valueOf(input.readInt());
284
285             case ValueTypes.LONG_TYPE :
286                 return Long.valueOf(input.readLong());
287
288             case ValueTypes.QNAME_TYPE :
289                 return readQName();
290
291             case ValueTypes.SHORT_TYPE :
292                 return Short.valueOf(input.readShort());
293
294             case ValueTypes.STRING_TYPE :
295                 return input.readUTF();
296
297             case ValueTypes.STRING_BYTES_TYPE:
298                 return readStringBytes();
299
300             case ValueTypes.BIG_DECIMAL_TYPE :
301                 return new BigDecimal(input.readUTF());
302
303             case ValueTypes.BIG_INTEGER_TYPE :
304                 return new BigInteger(input.readUTF());
305
306             case ValueTypes.BINARY_TYPE :
307                 byte[] bytes = new byte[input.readInt()];
308                 input.readFully(bytes);
309                 return bytes;
310
311             case ValueTypes.YANG_IDENTIFIER_TYPE :
312                 return readYangInstanceIdentifierInternal();
313
314             default :
315                 return null;
316         }
317     }
318
319     private String readStringBytes() throws IOException {
320         byte[] bytes = new byte[input.readInt()];
321         input.readFully(bytes);
322         return new String(bytes, StandardCharsets.UTF_8);
323     }
324
325     public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
326         readSignatureMarkerAndVersionIfNeeded();
327         return readYangInstanceIdentifierInternal();
328     }
329
330     private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
331         int size = input.readInt();
332
333         List<PathArgument> pathArguments = new ArrayList<>(size);
334
335         for(int i = 0; i < size; i++) {
336             pathArguments.add(readPathArgument());
337         }
338         return YangInstanceIdentifier.create(pathArguments);
339     }
340
341     private Set<String> readObjSet() throws IOException {
342         int count = input.readInt();
343         Set<String> children = new HashSet<>(count);
344         for(int i = 0; i < count; i++) {
345             children.add(readCodedString());
346         }
347         return children;
348     }
349
350     public PathArgument readPathArgument() throws IOException {
351         // read Type
352         int type = input.readByte();
353
354         switch(type) {
355
356             case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
357                 return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
358
359             case PathArgumentTypes.NODE_IDENTIFIER :
360                 return new NodeIdentifier(readQName());
361
362             case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES :
363                 return new NodeIdentifierWithPredicates(readQName(), readKeyValueMap());
364
365             case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
366                 return new NodeWithValue(readQName(), readObject());
367
368             default :
369                 return null;
370         }
371     }
372
373     @SuppressWarnings("unchecked")
374     private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(QName nodeType,
375             ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
376
377         LOG.debug("Reading children of leaf set");
378
379         lastLeafSetQName = nodeType;
380
381         LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
382
383         while(child != null) {
384             builder.withChild(child);
385             child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
386         }
387         return builder;
388     }
389
390     @SuppressWarnings({ "unchecked", "rawtypes" })
391     private NormalizedNodeContainerBuilder addDataContainerChildren(
392             NormalizedNodeContainerBuilder builder) throws IOException {
393         LOG.debug("Reading data container (leaf nodes) nodes");
394
395         NormalizedNode<?, ?> child = readNormalizedNodeInternal();
396
397         while(child != null) {
398             builder.addChild(child);
399             child = readNormalizedNodeInternal();
400         }
401         return builder;
402     }
403 }