Remove unneeded Java 9+ check
[controller.git] / opendaylight / md-sal / sal-clustering-commons / src / main / java / org / opendaylight / controller / cluster / datastore / node / utils / stream / AbstractLithiumDataOutput.java
1 /*
2  * Copyright (c) 2014 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 package org.opendaylight.controller.cluster.datastore.node.utils.stream;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verifyNotNull;
13 import static java.util.Objects.requireNonNull;
14
15 import com.google.common.annotations.VisibleForTesting;
16 import com.google.common.collect.ImmutableMap;
17 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
18 import java.io.DataOutput;
19 import java.io.IOException;
20 import java.io.StringWriter;
21 import java.math.BigDecimal;
22 import java.math.BigInteger;
23 import java.nio.charset.StandardCharsets;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Map.Entry;
28 import java.util.Optional;
29 import java.util.Set;
30 import javax.xml.transform.TransformerException;
31 import javax.xml.transform.TransformerFactory;
32 import javax.xml.transform.dom.DOMSource;
33 import javax.xml.transform.stream.StreamResult;
34 import org.eclipse.jdt.annotation.NonNull;
35 import org.opendaylight.yangtools.yang.common.Empty;
36 import org.opendaylight.yangtools.yang.common.QName;
37 import org.opendaylight.yangtools.yang.common.QNameModule;
38 import org.opendaylight.yangtools.yang.common.Revision;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 /**
49  * "original" type mapping. Baseline is Lithium but it really was introduced in Oxygen, where {@code type empty} was
50  * remapped from null.
51  *
52  * <p>
53  * {@code uint8}, {@code uint16}, {@code uint32} use java.lang types with widening, hence their value types overlap with
54  * mapping of {@code int16}, {@code int32} and {@code int64}, making that difference indiscernible without YANG schema
55  * knowledge.
56  */
57 abstract class AbstractLithiumDataOutput extends AbstractNormalizedNodeDataOutput {
58     private static final Logger LOG = LoggerFactory.getLogger(AbstractLithiumDataOutput.class);
59     private static final TransformerFactory TF = TransformerFactory.newInstance();
60     private static final ImmutableMap<Class<?>, Byte> KNOWN_TYPES = ImmutableMap.<Class<?>, Byte>builder()
61             .put(String.class, LithiumValue.STRING_TYPE)
62             .put(Byte.class, LithiumValue.BYTE_TYPE)
63             .put(Integer.class, LithiumValue.INT_TYPE)
64             .put(Long.class, LithiumValue.LONG_TYPE)
65             .put(Boolean.class, LithiumValue.BOOL_TYPE)
66             .put(QName.class, LithiumValue.QNAME_TYPE)
67             .put(Short.class, LithiumValue.SHORT_TYPE)
68             .put(BigInteger.class, LithiumValue.BIG_INTEGER_TYPE)
69             .put(BigDecimal.class, LithiumValue.BIG_DECIMAL_TYPE)
70             .put(byte[].class, LithiumValue.BINARY_TYPE)
71             .put(Empty.class, LithiumValue.EMPTY_TYPE)
72             .build();
73
74     private final Map<String, Integer> stringCodeMap = new HashMap<>();
75
76     private QName lastLeafSetQName;
77     private boolean inSimple;
78
79     AbstractLithiumDataOutput(final DataOutput output) {
80         super(output);
81     }
82
83     @Override
84     public final void startLeafNode(final NodeIdentifier name) throws IOException {
85         LOG.trace("Starting a new leaf node");
86         startNode(name, LithiumNode.LEAF_NODE);
87         inSimple = true;
88     }
89
90     @Override
91     public final void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
92         LOG.trace("Starting a new leaf set");
93         commonStartLeafSet(name, LithiumNode.LEAF_SET);
94     }
95
96     @Override
97     public final void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException {
98         LOG.trace("Starting a new ordered leaf set");
99         commonStartLeafSet(name, LithiumNode.ORDERED_LEAF_SET);
100     }
101
102     private void commonStartLeafSet(final NodeIdentifier name, final byte nodeType) throws IOException {
103         startNode(name, nodeType);
104         lastLeafSetQName = name.getNodeType();
105     }
106
107     @Override
108     public final void startLeafSetEntryNode(final NodeWithValue<?> name) throws IOException {
109         LOG.trace("Starting a new leaf set entry node");
110
111         output.writeByte(LithiumNode.LEAF_SET_ENTRY_NODE);
112
113         // lastLeafSetQName is set if the parent LeafSetNode was previously written. Otherwise this is a
114         // stand alone LeafSetEntryNode so write out it's name here.
115         if (lastLeafSetQName == null) {
116             writeQNameInternal(name.getNodeType());
117         }
118         inSimple = true;
119     }
120
121     @Override
122     public final void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
123         LOG.trace("Starting a new container node");
124         startNode(name, LithiumNode.CONTAINER_NODE);
125     }
126
127     @Override
128     public final void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint)
129             throws IOException {
130         LOG.trace("Starting a new yang modeled anyXml node");
131         startNode(name, LithiumNode.YANG_MODELED_ANY_XML_NODE);
132     }
133
134     @Override
135     public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
136         LOG.trace("Starting a new unkeyed list");
137         startNode(name, LithiumNode.UNKEYED_LIST);
138     }
139
140     @Override
141     public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
142         LOG.trace("Starting a new unkeyed list item");
143         startNode(name, LithiumNode.UNKEYED_LIST_ITEM);
144     }
145
146     @Override
147     public final void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
148         LOG.trace("Starting a new map node");
149         startNode(name, LithiumNode.MAP_NODE);
150     }
151
152     @Override
153     public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
154             throws IOException {
155         LOG.trace("Starting a new map entry node");
156         startNode(identifier, LithiumNode.MAP_ENTRY_NODE);
157         writeKeyValueMap(identifier.entrySet());
158     }
159
160     @Override
161     public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
162         LOG.trace("Starting a new ordered map node");
163         startNode(name, LithiumNode.ORDERED_MAP_NODE);
164     }
165
166     @Override
167     public final void startChoiceNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
168         LOG.trace("Starting a new choice node");
169         startNode(name, LithiumNode.CHOICE_NODE);
170     }
171
172     @Override
173     public final void startAugmentationNode(final AugmentationIdentifier identifier) throws IOException {
174         requireNonNull(identifier, "Node identifier should not be null");
175         LOG.trace("Starting a new augmentation node");
176
177         output.writeByte(LithiumNode.AUGMENTATION_NODE);
178         writeAugmentationIdentifier(identifier);
179     }
180
181     @Override
182     public final boolean startAnyxmlNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
183         if (DOMSource.class.isAssignableFrom(objectModel)) {
184             LOG.trace("Starting anyxml node");
185             startNode(name, LithiumNode.ANY_XML_NODE);
186             inSimple = true;
187             return true;
188         }
189         return false;
190     }
191
192     @Override
193     public final void scalarValue(final Object value) throws IOException {
194         writeObject(value);
195     }
196
197     @Override
198     public final void domSourceValue(final DOMSource value) throws IOException {
199         final StringWriter writer = new StringWriter();
200         try {
201             TF.newTransformer().transform(value, new StreamResult(writer));
202         } catch (TransformerException e) {
203             throw new IOException("Error writing anyXml", e);
204         }
205         writeObject(writer.toString());
206     }
207
208     @Override
209     public final void endNode() throws IOException {
210         LOG.trace("Ending the node");
211         if (!inSimple) {
212             lastLeafSetQName = null;
213             output.writeByte(LithiumNode.END_NODE);
214         }
215         inSimple = false;
216     }
217
218     @Override
219     @SuppressFBWarnings(value = "BC_UNCONFIRMED_CAST",
220             justification = "The casts in the switch clauses are indirectly confirmed via the determination of 'type'.")
221     final void writePathArgumentInternal(final PathArgument pathArgument) throws IOException {
222         final byte type = LithiumPathArgument.getSerializablePathArgumentType(pathArgument);
223         output.writeByte(type);
224
225         switch (type) {
226             case LithiumPathArgument.NODE_IDENTIFIER:
227                 NodeIdentifier nodeIdentifier = (NodeIdentifier) pathArgument;
228                 writeQNameInternal(nodeIdentifier.getNodeType());
229                 break;
230             case LithiumPathArgument.NODE_IDENTIFIER_WITH_PREDICATES:
231                 NodeIdentifierWithPredicates nodeIdentifierWithPredicates =
232                     (NodeIdentifierWithPredicates) pathArgument;
233                 writeQNameInternal(nodeIdentifierWithPredicates.getNodeType());
234                 writeKeyValueMap(nodeIdentifierWithPredicates.entrySet());
235                 break;
236             case LithiumPathArgument.NODE_IDENTIFIER_WITH_VALUE:
237                 NodeWithValue<?> nodeWithValue = (NodeWithValue<?>) pathArgument;
238                 writeQNameInternal(nodeWithValue.getNodeType());
239                 writeObject(nodeWithValue.getValue());
240                 break;
241             case LithiumPathArgument.AUGMENTATION_IDENTIFIER:
242                 // No Qname in augmentation identifier
243                 writeAugmentationIdentifier((AugmentationIdentifier) pathArgument);
244                 break;
245             default:
246                 throw new IllegalStateException("Unknown node identifier type is found : "
247                         + pathArgument.getClass().toString());
248         }
249     }
250
251     @Override
252     final void writeYangInstanceIdentifierInternal(final YangInstanceIdentifier identifier) throws IOException {
253         List<PathArgument> pathArguments = identifier.getPathArguments();
254         output.writeInt(pathArguments.size());
255
256         for (PathArgument pathArgument : pathArguments) {
257             writePathArgumentInternal(pathArgument);
258         }
259     }
260
261     final void defaultWriteAugmentationIdentifier(final @NonNull AugmentationIdentifier aid) throws IOException {
262         final Set<QName> qnames = aid.getPossibleChildNames();
263         // Write each child's qname separately, if list is empty send count as 0
264         if (!qnames.isEmpty()) {
265             output.writeInt(qnames.size());
266             for (QName qname : qnames) {
267                 writeQNameInternal(qname);
268             }
269         } else {
270             LOG.debug("augmentation node does not have any child");
271             output.writeInt(0);
272         }
273     }
274
275     final void defaultWriteQName(final QName qname) throws IOException {
276         writeString(qname.getLocalName());
277         writeModule(qname.getModule());
278     }
279
280     final void defaultWriteModule(final QNameModule module) throws IOException {
281         writeString(module.getNamespace().toString());
282         final Optional<Revision> revision = module.getRevision();
283         if (revision.isPresent()) {
284             writeString(revision.get().toString());
285         } else {
286             writeByte(LithiumTokens.IS_NULL_VALUE);
287         }
288     }
289
290     abstract void writeModule(QNameModule module) throws IOException;
291
292     abstract void writeAugmentationIdentifier(@NonNull AugmentationIdentifier aid) throws IOException;
293
294     private void startNode(final PathArgument arg, final byte nodeType) throws IOException {
295         requireNonNull(arg, "Node identifier should not be null");
296         checkState(!inSimple, "Attempted to start a child in a simple node");
297
298         // First write the type of node
299         output.writeByte(nodeType);
300         // Write Start Tag
301         writeQNameInternal(arg.getNodeType());
302     }
303
304     private void writeObjSet(final Set<?> set) throws IOException {
305         output.writeInt(set.size());
306         for (Object o : set) {
307             checkArgument(o instanceof String, "Expected value type to be String but was %s (%s)", o.getClass(), o);
308             writeString((String) o);
309         }
310     }
311
312     private void writeObject(final Object value) throws IOException {
313         byte type = getSerializableType(value);
314         // Write object type first
315         output.writeByte(type);
316
317         switch (type) {
318             case LithiumValue.BOOL_TYPE:
319                 output.writeBoolean((Boolean) value);
320                 break;
321             case LithiumValue.QNAME_TYPE:
322                 writeQNameInternal((QName) value);
323                 break;
324             case LithiumValue.INT_TYPE:
325                 output.writeInt((Integer) value);
326                 break;
327             case LithiumValue.BYTE_TYPE:
328                 output.writeByte((Byte) value);
329                 break;
330             case LithiumValue.LONG_TYPE:
331                 output.writeLong((Long) value);
332                 break;
333             case LithiumValue.SHORT_TYPE:
334                 output.writeShort((Short) value);
335                 break;
336             case LithiumValue.BITS_TYPE:
337                 writeObjSet((Set<?>) value);
338                 break;
339             case LithiumValue.BINARY_TYPE:
340                 byte[] bytes = (byte[]) value;
341                 output.writeInt(bytes.length);
342                 output.write(bytes);
343                 break;
344             case LithiumValue.YANG_IDENTIFIER_TYPE:
345                 writeYangInstanceIdentifierInternal((YangInstanceIdentifier) value);
346                 break;
347             case LithiumValue.EMPTY_TYPE:
348                 break;
349             case LithiumValue.STRING_BYTES_TYPE:
350                 final byte[] valueBytes = value.toString().getBytes(StandardCharsets.UTF_8);
351                 output.writeInt(valueBytes.length);
352                 output.write(valueBytes);
353                 break;
354             default:
355                 output.writeUTF(value.toString());
356                 break;
357         }
358     }
359
360     private void writeKeyValueMap(final Set<Entry<QName, Object>> entrySet) throws IOException {
361         if (!entrySet.isEmpty()) {
362             output.writeInt(entrySet.size());
363             for (Entry<QName, Object> entry : entrySet) {
364                 writeQNameInternal(entry.getKey());
365                 writeObject(entry.getValue());
366             }
367         } else {
368             output.writeInt(0);
369         }
370     }
371
372     private void writeString(final @NonNull String string) throws IOException {
373         final Integer value = stringCodeMap.get(verifyNotNull(string));
374         if (value == null) {
375             stringCodeMap.put(string, stringCodeMap.size());
376             writeByte(LithiumTokens.IS_STRING_VALUE);
377             writeUTF(string);
378         } else {
379             writeByte(LithiumTokens.IS_CODE_VALUE);
380             writeInt(value);
381         }
382     }
383
384     @VisibleForTesting
385     static final byte getSerializableType(final Object node) {
386         final Byte type = KNOWN_TYPES.get(requireNonNull(node).getClass());
387         if (type != null) {
388             if (type == LithiumValue.STRING_TYPE
389                     && ((String) node).length() >= LithiumValue.STRING_BYTES_LENGTH_THRESHOLD) {
390                 return LithiumValue.STRING_BYTES_TYPE;
391             }
392             return type;
393         }
394
395         if (node instanceof Set) {
396             return LithiumValue.BITS_TYPE;
397         }
398
399         if (node instanceof YangInstanceIdentifier) {
400             return LithiumValue.YANG_IDENTIFIER_TYPE;
401         }
402
403         throw new IllegalArgumentException("Unknown value type " + node.getClass().getSimpleName());
404     }
405 }