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