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