Fix CS warnings in sal-clustering-commons and enable enforcement
[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.IOException;
15 import java.io.StringReader;
16 import java.math.BigDecimal;
17 import java.math.BigInteger;
18 import java.nio.charset.StandardCharsets;
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.parsers.DocumentBuilderFactory;
26 import javax.xml.parsers.ParserConfigurationException;
27 import javax.xml.transform.dom.DOMSource;
28 import org.opendaylight.controller.cluster.datastore.node.utils.QNameFactory;
29 import org.opendaylight.yangtools.yang.common.QName;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
35 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
38 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
39 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
40 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
41 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.w3c.dom.Element;
45 import org.xml.sax.InputSource;
46 import org.xml.sax.SAXException;
47
48 /**
49  * NormalizedNodeInputStreamReader reads the byte stream and constructs the normalized node including its children
50  * nodes. This process goes in recursive manner, where each NodeTypes object signifies the start of the object, except
51  * END_NODE. If a node can have children, then that node's end is calculated based on appearance of END_NODE.
52  */
53 public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput {
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     @SuppressWarnings("rawtypes")
69     private NormalizedNodeAttrBuilder<NodeWithValue, Object, LeafSetEntryNode<Object>> leafSetEntryBuilder;
70
71     private final StringBuilder reusableStringBuilder = new StringBuilder(50);
72
73     private boolean readSignatureMarker = true;
74
75     /**
76      * Constructs an instance.
77      *
78      * @deprecated Use {@link NormalizedNodeInputOutput#newDataInput(DataInput)} instead.
79      */
80     @Deprecated
81     public NormalizedNodeInputStreamReader(final DataInput input) {
82         this(input, false);
83     }
84
85     NormalizedNodeInputStreamReader(final DataInput input, final boolean versionChecked) {
86         this.input = Preconditions.checkNotNull(input);
87         readSignatureMarker = !versionChecked;
88     }
89
90     @Override
91     public NormalizedNode<?, ?> readNormalizedNode() throws IOException {
92         readSignatureMarkerAndVersionIfNeeded();
93         return readNormalizedNodeInternal();
94     }
95
96     private void readSignatureMarkerAndVersionIfNeeded() throws IOException {
97         if (readSignatureMarker) {
98             readSignatureMarker = false;
99
100             final byte marker = input.readByte();
101             if (marker != TokenTypes.SIGNATURE_MARKER) {
102                 throw new InvalidNormalizedNodeStreamException(String.format(
103                         "Invalid signature marker: %d", marker));
104             }
105
106             final short version = input.readShort();
107             if (version != TokenTypes.LITHIUM_VERSION) {
108                 throw new InvalidNormalizedNodeStreamException(String.format("Unhandled stream version %s", version));
109             }
110         }
111     }
112
113     private NormalizedNode<?, ?> readNormalizedNodeInternal() throws IOException {
114         // each node should start with a byte
115         byte nodeType = input.readByte();
116
117         if (nodeType == NodeTypes.END_NODE) {
118             LOG.debug("End node reached. return");
119             return null;
120         }
121
122         switch (nodeType) {
123             case NodeTypes.AUGMENTATION_NODE :
124                 YangInstanceIdentifier.AugmentationIdentifier augIdentifier =
125                     new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
126
127                 LOG.debug("Reading augmentation node {} ", augIdentifier);
128
129                 return addDataContainerChildren(Builders.augmentationBuilder()
130                         .withNodeIdentifier(augIdentifier)).build();
131
132             case NodeTypes.LEAF_SET_ENTRY_NODE :
133                 QName name = lastLeafSetQName;
134                 if (name == null) {
135                     name = readQName();
136                 }
137
138                 Object value = readObject();
139                 NodeWithValue<Object> leafIdentifier = new NodeWithValue<>(name, value);
140
141                 LOG.debug("Reading leaf set entry node {}, value {}", leafIdentifier, value);
142
143                 return leafSetEntryBuilder().withNodeIdentifier(leafIdentifier).withValue(value).build();
144
145             case NodeTypes.MAP_ENTRY_NODE :
146                 NodeIdentifierWithPredicates entryIdentifier = new NodeIdentifierWithPredicates(
147                         readQName(), readKeyValueMap());
148
149                 LOG.debug("Reading map entry node {} ", entryIdentifier);
150
151                 return addDataContainerChildren(Builders.mapEntryBuilder()
152                         .withNodeIdentifier(entryIdentifier)).build();
153
154             default :
155                 return readNodeIdentifierDependentNode(nodeType, new NodeIdentifier(readQName()));
156         }
157     }
158
159     private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
160                                       Object, LeafNode<Object>> leafBuilder() {
161         if (leafBuilder == null) {
162             leafBuilder = Builders.leafBuilder();
163         }
164
165         return leafBuilder;
166     }
167
168     @SuppressWarnings("rawtypes")
169     private NormalizedNodeAttrBuilder<NodeWithValue, Object,
170                                       LeafSetEntryNode<Object>> leafSetEntryBuilder() {
171         if (leafSetEntryBuilder == null) {
172             leafSetEntryBuilder = Builders.leafSetEntryBuilder();
173         }
174
175         return leafSetEntryBuilder;
176     }
177
178     private NormalizedNode<?, ?> readNodeIdentifierDependentNode(final byte nodeType, final NodeIdentifier identifier)
179         throws IOException {
180
181         switch (nodeType) {
182             case NodeTypes.LEAF_NODE :
183                 LOG.debug("Read leaf node {}", identifier);
184                 // Read the object value
185                 return leafBuilder().withNodeIdentifier(identifier).withValue(readObject()).build();
186
187             case NodeTypes.ANY_XML_NODE :
188                 LOG.debug("Read xml node");
189                 return Builders.anyXmlBuilder().withNodeIdentifier(identifier).withValue(readDOMSource()).build();
190
191             case NodeTypes.MAP_NODE :
192                 LOG.debug("Read map node {}", identifier);
193                 return addDataContainerChildren(Builders.mapBuilder().withNodeIdentifier(identifier)).build();
194
195             case NodeTypes.CHOICE_NODE:
196                 LOG.debug("Read choice node {}", identifier);
197                 return addDataContainerChildren(Builders.choiceBuilder().withNodeIdentifier(identifier)).build();
198
199             case NodeTypes.ORDERED_MAP_NODE:
200                 LOG.debug("Reading ordered map node {}", identifier);
201                 return addDataContainerChildren(Builders.orderedMapBuilder().withNodeIdentifier(identifier)).build();
202
203             case NodeTypes.UNKEYED_LIST:
204                 LOG.debug("Read unkeyed list node {}", identifier);
205                 return addDataContainerChildren(Builders.unkeyedListBuilder().withNodeIdentifier(identifier)).build();
206
207             case NodeTypes.UNKEYED_LIST_ITEM:
208                 LOG.debug("Read unkeyed list item node {}", identifier);
209                 return addDataContainerChildren(Builders.unkeyedListEntryBuilder()
210                         .withNodeIdentifier(identifier)).build();
211
212             case NodeTypes.CONTAINER_NODE:
213                 LOG.debug("Read container node {}", identifier);
214                 return addDataContainerChildren(Builders.containerBuilder().withNodeIdentifier(identifier)).build();
215
216             case NodeTypes.LEAF_SET :
217                 LOG.debug("Read leaf set node {}", identifier);
218                 return addLeafSetChildren(identifier.getNodeType(),
219                         Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
220
221             case NodeTypes.ORDERED_LEAF_SET:
222                 LOG.debug("Read ordered leaf set node {}", identifier);
223                 ListNodeBuilder<Object, LeafSetEntryNode<Object>> orderedLeafSetBuilder =
224                         Builders.orderedLeafSetBuilder().withNodeIdentifier(identifier);
225                 orderedLeafSetBuilder = addLeafSetChildren(identifier.getNodeType(), orderedLeafSetBuilder);
226                 return orderedLeafSetBuilder.build();
227
228             default :
229                 return null;
230         }
231     }
232
233     private DOMSource readDOMSource() throws IOException {
234         String xml = readObject().toString();
235         try {
236             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
237             factory.setNamespaceAware(true);
238             Element node = factory.newDocumentBuilder().parse(
239                     new InputSource(new StringReader(xml))).getDocumentElement();
240             return new DOMSource(node);
241         } catch (SAXException | ParserConfigurationException e) {
242             throw new IOException("Error parsing XML: " + xml, e);
243         }
244     }
245
246     private QName readQName() throws IOException {
247         // Read in the same sequence of writing
248         String localName = readCodedString();
249         String namespace = readCodedString();
250         String revision = readCodedString();
251
252         String qname;
253         if (!Strings.isNullOrEmpty(revision)) {
254             qname = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG).append(revision)
255                     .append(')').append(localName).toString();
256         } else {
257             qname = reusableStringBuilder.append('(').append(namespace).append(')').append(localName).toString();
258         }
259
260         reusableStringBuilder.delete(0, reusableStringBuilder.length());
261         return QNameFactory.create(qname);
262     }
263
264
265     private String readCodedString() throws IOException {
266         byte valueType = input.readByte();
267         if (valueType == TokenTypes.IS_CODE_VALUE) {
268             return codedStringMap.get(input.readInt());
269         } else if (valueType == TokenTypes.IS_STRING_VALUE) {
270             String value = input.readUTF().intern();
271             codedStringMap.put(Integer.valueOf(codedStringMap.size()), value);
272             return value;
273         }
274
275         return null;
276     }
277
278     private Set<QName> readQNameSet() throws IOException {
279         // Read the children count
280         int count = input.readInt();
281         Set<QName> children = new HashSet<>(count);
282         for (int i = 0; i < count; i++) {
283             children.add(readQName());
284         }
285         return children;
286     }
287
288     private Map<QName, Object> readKeyValueMap() throws IOException {
289         int count = input.readInt();
290         Map<QName, Object> keyValueMap = new HashMap<>(count);
291
292         for (int i = 0; i < count; i++) {
293             keyValueMap.put(readQName(), readObject());
294         }
295
296         return keyValueMap;
297     }
298
299     private Object readObject() throws IOException {
300         byte objectType = input.readByte();
301         switch (objectType) {
302             case ValueTypes.BITS_TYPE:
303                 return readObjSet();
304
305             case ValueTypes.BOOL_TYPE :
306                 return Boolean.valueOf(input.readBoolean());
307
308             case ValueTypes.BYTE_TYPE :
309                 return Byte.valueOf(input.readByte());
310
311             case ValueTypes.INT_TYPE :
312                 return Integer.valueOf(input.readInt());
313
314             case ValueTypes.LONG_TYPE :
315                 return Long.valueOf(input.readLong());
316
317             case ValueTypes.QNAME_TYPE :
318                 return readQName();
319
320             case ValueTypes.SHORT_TYPE :
321                 return Short.valueOf(input.readShort());
322
323             case ValueTypes.STRING_TYPE :
324                 return input.readUTF();
325
326             case ValueTypes.STRING_BYTES_TYPE:
327                 return readStringBytes();
328
329             case ValueTypes.BIG_DECIMAL_TYPE :
330                 return new BigDecimal(input.readUTF());
331
332             case ValueTypes.BIG_INTEGER_TYPE :
333                 return new BigInteger(input.readUTF());
334
335             case ValueTypes.BINARY_TYPE :
336                 byte[] bytes = new byte[input.readInt()];
337                 input.readFully(bytes);
338                 return bytes;
339
340             case ValueTypes.YANG_IDENTIFIER_TYPE :
341                 return readYangInstanceIdentifierInternal();
342
343             default :
344                 return null;
345         }
346     }
347
348     private String readStringBytes() throws IOException {
349         byte[] bytes = new byte[input.readInt()];
350         input.readFully(bytes);
351         return new String(bytes, StandardCharsets.UTF_8);
352     }
353
354     @Override
355     public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
356         readSignatureMarkerAndVersionIfNeeded();
357         return readYangInstanceIdentifierInternal();
358     }
359
360     private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
361         int size = input.readInt();
362
363         List<PathArgument> pathArguments = new ArrayList<>(size);
364
365         for (int i = 0; i < size; i++) {
366             pathArguments.add(readPathArgument());
367         }
368         return YangInstanceIdentifier.create(pathArguments);
369     }
370
371     private Set<String> readObjSet() throws IOException {
372         int count = input.readInt();
373         Set<String> children = new HashSet<>(count);
374         for (int i = 0; i < count; i++) {
375             children.add(readCodedString());
376         }
377         return children;
378     }
379
380     @Override
381     public PathArgument readPathArgument() throws IOException {
382         // read Type
383         int type = input.readByte();
384
385         switch (type) {
386
387             case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
388                 return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
389
390             case PathArgumentTypes.NODE_IDENTIFIER :
391                 return new NodeIdentifier(readQName());
392
393             case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES :
394                 return new NodeIdentifierWithPredicates(readQName(), readKeyValueMap());
395
396             case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
397                 return new NodeWithValue<>(readQName(), readObject());
398
399             default :
400                 return null;
401         }
402     }
403
404     @SuppressWarnings("unchecked")
405     private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(final QName nodeType,
406             final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
407
408         LOG.debug("Reading children of leaf set");
409
410         lastLeafSetQName = nodeType;
411
412         LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
413
414         while (child != null) {
415             builder.withChild(child);
416             child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
417         }
418         return builder;
419     }
420
421     @SuppressWarnings({ "unchecked", "rawtypes" })
422     private NormalizedNodeContainerBuilder addDataContainerChildren(
423             final NormalizedNodeContainerBuilder builder) throws IOException {
424         LOG.debug("Reading data container (leaf nodes) nodes");
425
426         NormalizedNode<?, ?> child = readNormalizedNodeInternal();
427
428         while (child != null) {
429             builder.addChild(child);
430             child = readNormalizedNodeInternal();
431         }
432         return builder;
433     }
434
435     @Override
436     public void readFully(final byte[] value) throws IOException {
437         readSignatureMarkerAndVersionIfNeeded();
438         input.readFully(value);
439     }
440
441     @Override
442     public void readFully(final byte[] str, final int off, final int len) throws IOException {
443         readSignatureMarkerAndVersionIfNeeded();
444         input.readFully(str, off, len);
445     }
446
447     @Override
448     public int skipBytes(final int num) throws IOException {
449         readSignatureMarkerAndVersionIfNeeded();
450         return input.skipBytes(num);
451     }
452
453     @Override
454     public boolean readBoolean() throws IOException {
455         readSignatureMarkerAndVersionIfNeeded();
456         return input.readBoolean();
457     }
458
459     @Override
460     public byte readByte() throws IOException {
461         readSignatureMarkerAndVersionIfNeeded();
462         return input.readByte();
463     }
464
465     @Override
466     public int readUnsignedByte() throws IOException {
467         readSignatureMarkerAndVersionIfNeeded();
468         return input.readUnsignedByte();
469     }
470
471     @Override
472     public short readShort() throws IOException {
473         readSignatureMarkerAndVersionIfNeeded();
474         return input.readShort();
475     }
476
477     @Override
478     public int readUnsignedShort() throws IOException {
479         readSignatureMarkerAndVersionIfNeeded();
480         return input.readUnsignedShort();
481     }
482
483     @Override
484     public char readChar() throws IOException {
485         readSignatureMarkerAndVersionIfNeeded();
486         return input.readChar();
487     }
488
489     @Override
490     public int readInt() throws IOException {
491         readSignatureMarkerAndVersionIfNeeded();
492         return input.readInt();
493     }
494
495     @Override
496     public long readLong() throws IOException {
497         readSignatureMarkerAndVersionIfNeeded();
498         return input.readLong();
499     }
500
501     @Override
502     public float readFloat() throws IOException {
503         readSignatureMarkerAndVersionIfNeeded();
504         return input.readFloat();
505     }
506
507     @Override
508     public double readDouble() throws IOException {
509         readSignatureMarkerAndVersionIfNeeded();
510         return input.readDouble();
511     }
512
513     @Override
514     public String readLine() throws IOException {
515         readSignatureMarkerAndVersionIfNeeded();
516         return input.readLine();
517     }
518
519     @Override
520     public String readUTF() throws IOException {
521         readSignatureMarkerAndVersionIfNeeded();
522         return input.readUTF();
523     }
524 }