a9f0979e5333ef72dcabaf96d6e91652e29af08c
[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.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 startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException {
129         LOG.trace("Starting a new unkeyed list");
130         startNode(name, LithiumNode.UNKEYED_LIST);
131     }
132
133     @Override
134     public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
135         LOG.trace("Starting a new unkeyed list item");
136         startNode(name, LithiumNode.UNKEYED_LIST_ITEM);
137     }
138
139     @Override
140     public final void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
141         LOG.trace("Starting a new map node");
142         startNode(name, LithiumNode.MAP_NODE);
143     }
144
145     @Override
146     public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
147             throws IOException {
148         LOG.trace("Starting a new map entry node");
149         startNode(identifier, LithiumNode.MAP_ENTRY_NODE);
150         writeKeyValueMap(identifier.entrySet());
151     }
152
153     @Override
154     public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
155         LOG.trace("Starting a new ordered map node");
156         startNode(name, LithiumNode.ORDERED_MAP_NODE);
157     }
158
159     @Override
160     public final void startChoiceNode(final NodeIdentifier name, final int childSizeHint) throws IOException {
161         LOG.trace("Starting a new choice node");
162         startNode(name, LithiumNode.CHOICE_NODE);
163     }
164
165     @Override
166     public final void startAugmentationNode(final AugmentationIdentifier identifier) throws IOException {
167         requireNonNull(identifier, "Node identifier should not be null");
168         LOG.trace("Starting a new augmentation node");
169
170         output.writeByte(LithiumNode.AUGMENTATION_NODE);
171         writeAugmentationIdentifier(identifier);
172     }
173
174     @Override
175     public final boolean startAnyxmlNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
176         if (DOMSource.class.isAssignableFrom(objectModel)) {
177             LOG.trace("Starting anyxml node");
178             startNode(name, LithiumNode.ANY_XML_NODE);
179             inSimple = true;
180             return true;
181         }
182         return false;
183     }
184
185     @Override
186     public final void scalarValue(final Object value) throws IOException {
187         writeObject(value);
188     }
189
190     @Override
191     public final void domSourceValue(final DOMSource value) throws IOException {
192         final StringWriter writer = new StringWriter();
193         try {
194             TF.newTransformer().transform(value, new StreamResult(writer));
195         } catch (TransformerException e) {
196             throw new IOException("Error writing anyXml", e);
197         }
198         writeObject(writer.toString());
199     }
200
201     @Override
202     public final void endNode() throws IOException {
203         LOG.trace("Ending the node");
204         if (!inSimple) {
205             lastLeafSetQName = null;
206             output.writeByte(LithiumNode.END_NODE);
207         }
208         inSimple = false;
209     }
210
211     @Override
212     @SuppressFBWarnings(value = "BC_UNCONFIRMED_CAST",
213             justification = "The casts in the switch clauses are indirectly confirmed via the determination of 'type'.")
214     final void writePathArgumentInternal(final PathArgument pathArgument) throws IOException {
215         final byte type = LithiumPathArgument.getSerializablePathArgumentType(pathArgument);
216         output.writeByte(type);
217
218         switch (type) {
219             case LithiumPathArgument.NODE_IDENTIFIER:
220                 NodeIdentifier nodeIdentifier = (NodeIdentifier) pathArgument;
221                 writeQNameInternal(nodeIdentifier.getNodeType());
222                 break;
223             case LithiumPathArgument.NODE_IDENTIFIER_WITH_PREDICATES:
224                 NodeIdentifierWithPredicates nodeIdentifierWithPredicates =
225                     (NodeIdentifierWithPredicates) pathArgument;
226                 writeQNameInternal(nodeIdentifierWithPredicates.getNodeType());
227                 writeKeyValueMap(nodeIdentifierWithPredicates.entrySet());
228                 break;
229             case LithiumPathArgument.NODE_IDENTIFIER_WITH_VALUE:
230                 NodeWithValue<?> nodeWithValue = (NodeWithValue<?>) pathArgument;
231                 writeQNameInternal(nodeWithValue.getNodeType());
232                 writeObject(nodeWithValue.getValue());
233                 break;
234             case LithiumPathArgument.AUGMENTATION_IDENTIFIER:
235                 // No Qname in augmentation identifier
236                 writeAugmentationIdentifier((AugmentationIdentifier) pathArgument);
237                 break;
238             default:
239                 throw new IllegalStateException("Unknown node identifier type is found : "
240                         + pathArgument.getClass().toString());
241         }
242     }
243
244     @Override
245     final void writeYangInstanceIdentifierInternal(final YangInstanceIdentifier identifier) throws IOException {
246         List<PathArgument> pathArguments = identifier.getPathArguments();
247         output.writeInt(pathArguments.size());
248
249         for (PathArgument pathArgument : pathArguments) {
250             writePathArgumentInternal(pathArgument);
251         }
252     }
253
254     final void defaultWriteAugmentationIdentifier(final @NonNull AugmentationIdentifier aid) throws IOException {
255         final Set<QName> qnames = aid.getPossibleChildNames();
256         // Write each child's qname separately, if list is empty send count as 0
257         if (!qnames.isEmpty()) {
258             output.writeInt(qnames.size());
259             for (QName qname : qnames) {
260                 writeQNameInternal(qname);
261             }
262         } else {
263             LOG.debug("augmentation node does not have any child");
264             output.writeInt(0);
265         }
266     }
267
268     final void defaultWriteQName(final QName qname) throws IOException {
269         writeString(qname.getLocalName());
270         writeModule(qname.getModule());
271     }
272
273     final void defaultWriteModule(final QNameModule module) throws IOException {
274         writeString(module.getNamespace().toString());
275         final Optional<Revision> revision = module.getRevision();
276         if (revision.isPresent()) {
277             writeString(revision.get().toString());
278         } else {
279             writeByte(LithiumTokens.IS_NULL_VALUE);
280         }
281     }
282
283     abstract void writeModule(QNameModule module) throws IOException;
284
285     abstract void writeAugmentationIdentifier(@NonNull AugmentationIdentifier aid) throws IOException;
286
287     private void startNode(final PathArgument arg, final byte nodeType) throws IOException {
288         requireNonNull(arg, "Node identifier should not be null");
289         checkState(!inSimple, "Attempted to start a child in a simple node");
290
291         // First write the type of node
292         output.writeByte(nodeType);
293         // Write Start Tag
294         writeQNameInternal(arg.getNodeType());
295     }
296
297     private void writeObjSet(final Set<?> set) throws IOException {
298         output.writeInt(set.size());
299         for (Object o : set) {
300             checkArgument(o instanceof String, "Expected value type to be String but was %s (%s)", o.getClass(), o);
301             writeString((String) o);
302         }
303     }
304
305     private void writeObject(final Object value) throws IOException {
306         byte type = getSerializableType(value);
307         // Write object type first
308         output.writeByte(type);
309
310         switch (type) {
311             case LithiumValue.BOOL_TYPE:
312                 output.writeBoolean((Boolean) value);
313                 break;
314             case LithiumValue.QNAME_TYPE:
315                 writeQNameInternal((QName) value);
316                 break;
317             case LithiumValue.INT_TYPE:
318                 output.writeInt((Integer) value);
319                 break;
320             case LithiumValue.BYTE_TYPE:
321                 output.writeByte((Byte) value);
322                 break;
323             case LithiumValue.LONG_TYPE:
324                 output.writeLong((Long) value);
325                 break;
326             case LithiumValue.SHORT_TYPE:
327                 output.writeShort((Short) value);
328                 break;
329             case LithiumValue.BITS_TYPE:
330                 writeObjSet((Set<?>) value);
331                 break;
332             case LithiumValue.BINARY_TYPE:
333                 byte[] bytes = (byte[]) value;
334                 output.writeInt(bytes.length);
335                 output.write(bytes);
336                 break;
337             case LithiumValue.YANG_IDENTIFIER_TYPE:
338                 writeYangInstanceIdentifierInternal((YangInstanceIdentifier) value);
339                 break;
340             case LithiumValue.EMPTY_TYPE:
341                 break;
342             case LithiumValue.STRING_BYTES_TYPE:
343                 final byte[] valueBytes = value.toString().getBytes(StandardCharsets.UTF_8);
344                 output.writeInt(valueBytes.length);
345                 output.write(valueBytes);
346                 break;
347             default:
348                 output.writeUTF(value.toString());
349                 break;
350         }
351     }
352
353     private void writeKeyValueMap(final Set<Entry<QName, Object>> entrySet) throws IOException {
354         if (!entrySet.isEmpty()) {
355             output.writeInt(entrySet.size());
356             for (Entry<QName, Object> entry : entrySet) {
357                 writeQNameInternal(entry.getKey());
358                 writeObject(entry.getValue());
359             }
360         } else {
361             output.writeInt(0);
362         }
363     }
364
365     private void writeString(final @NonNull String string) throws IOException {
366         final Integer value = stringCodeMap.get(verifyNotNull(string));
367         if (value == null) {
368             stringCodeMap.put(string, stringCodeMap.size());
369             writeByte(LithiumTokens.IS_STRING_VALUE);
370             writeUTF(string);
371         } else {
372             writeByte(LithiumTokens.IS_CODE_VALUE);
373             writeInt(value);
374         }
375     }
376
377     @VisibleForTesting
378     static final byte getSerializableType(final Object node) {
379         final Byte type = KNOWN_TYPES.get(requireNonNull(node).getClass());
380         if (type != null) {
381             if (type == LithiumValue.STRING_TYPE
382                     && ((String) node).length() >= LithiumValue.STRING_BYTES_LENGTH_THRESHOLD) {
383                 return LithiumValue.STRING_BYTES_TYPE;
384             }
385             return type;
386         }
387
388         if (node instanceof Set) {
389             return LithiumValue.BITS_TYPE;
390         }
391
392         if (node instanceof YangInstanceIdentifier) {
393             return LithiumValue.YANG_IDENTIFIER_TYPE;
394         }
395
396         throw new IllegalArgumentException("Unknown value type " + node.getClass().getSimpleName());
397     }
398 }