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