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