2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.data.codec.binfmt;
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;
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;
27 import java.util.Map.Entry;
28 import java.util.Optional;
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;
50 * "original" type mapping. Baseline is Lithium but it really was introduced in Oxygen, where {@code type empty} was
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
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)
76 private final Map<String, Integer> stringCodeMap = new HashMap<>();
78 private QName lastLeafSetQName;
79 private boolean inSimple;
81 AbstractLithiumDataOutput(final DataOutput output) {
86 public final void startLeafNode(final NodeIdentifier name) throws IOException {
87 LOG.trace("Starting a new leaf node");
88 startNode(name, LithiumNode.LEAF_NODE);
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);
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);
104 private void commonStartLeafSet(final NodeIdentifier name, final byte nodeType) throws IOException {
105 startNode(name, nodeType);
106 lastLeafSetQName = name.getNodeType();
110 public final void startLeafSetEntryNode(final NodeWithValue<?> name) throws IOException {
111 LOG.trace("Starting a new leaf set entry node");
113 output.writeByte(LithiumNode.LEAF_SET_ENTRY_NODE);
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());
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);
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);
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);
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);
148 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
150 LOG.trace("Starting a new map entry node");
151 startNode(identifier, LithiumNode.MAP_ENTRY_NODE);
152 writeKeyValueMap(identifier.entrySet());
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);
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);
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");
172 output.writeByte(LithiumNode.AUGMENTATION_NODE);
173 writeAugmentationIdentifier(identifier);
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);
188 public final void scalarValue(final Object value) throws IOException {
193 public final void domSourceValue(final DOMSource value) throws IOException {
194 final StringWriter writer = new StringWriter();
196 TF.newTransformer().transform(value, new StreamResult(writer));
197 } catch (TransformerException e) {
198 throw new IOException("Error writing anyXml", e);
200 writeObject(writer.toString());
204 public final void endNode() throws IOException {
205 LOG.trace("Ending the node");
207 lastLeafSetQName = null;
208 output.writeByte(LithiumNode.END_NODE);
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);
221 case LithiumPathArgument.NODE_IDENTIFIER:
222 NodeIdentifier nodeIdentifier = (NodeIdentifier) pathArgument;
223 writeQNameInternal(nodeIdentifier.getNodeType());
225 case LithiumPathArgument.NODE_IDENTIFIER_WITH_PREDICATES:
226 NodeIdentifierWithPredicates nodeIdentifierWithPredicates =
227 (NodeIdentifierWithPredicates) pathArgument;
228 writeQNameInternal(nodeIdentifierWithPredicates.getNodeType());
229 writeKeyValueMap(nodeIdentifierWithPredicates.entrySet());
231 case LithiumPathArgument.NODE_IDENTIFIER_WITH_VALUE:
232 NodeWithValue<?> nodeWithValue = (NodeWithValue<?>) pathArgument;
233 writeQNameInternal(nodeWithValue.getNodeType());
234 writeObject(nodeWithValue.getValue());
236 case LithiumPathArgument.AUGMENTATION_IDENTIFIER:
237 // No Qname in augmentation identifier
238 writeAugmentationIdentifier((AugmentationIdentifier) pathArgument);
241 throw new IllegalStateException("Unknown node identifier type is found : "
242 + pathArgument.getClass().toString());
247 final void writeYangInstanceIdentifierInternal(final YangInstanceIdentifier identifier) throws IOException {
248 List<PathArgument> pathArguments = identifier.getPathArguments();
249 output.writeInt(pathArguments.size());
251 for (PathArgument pathArgument : pathArguments) {
252 writePathArgumentInternal(pathArgument);
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);
265 LOG.debug("augmentation node does not have any child");
270 final void defaultWriteQName(final QName qname) throws IOException {
271 writeString(qname.getLocalName());
272 writeModule(qname.getModule());
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());
281 writeByte(LithiumTokens.IS_NULL_VALUE);
285 abstract void writeModule(QNameModule module) throws IOException;
287 abstract void writeAugmentationIdentifier(@NonNull AugmentationIdentifier aid) throws IOException;
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");
293 // First write the type of node
294 output.writeByte(nodeType);
296 writeQNameInternal(arg.getNodeType());
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);
307 private void writeObject(final Object value) throws IOException {
308 byte type = getSerializableType(value);
309 // Write object type first
310 output.writeByte(type);
313 case LithiumValue.BOOL_TYPE:
314 output.writeBoolean((Boolean) value);
316 case LithiumValue.QNAME_TYPE:
317 writeQNameInternal((QName) value);
319 case LithiumValue.INT_TYPE:
320 output.writeInt((Integer) value);
322 case LithiumValue.BYTE_TYPE:
323 output.writeByte((Byte) value);
325 case LithiumValue.LONG_TYPE:
326 output.writeLong((Long) value);
328 case LithiumValue.SHORT_TYPE:
329 output.writeShort((Short) value);
331 case LithiumValue.BITS_TYPE:
332 writeObjSet((Set<?>) value);
334 case LithiumValue.BINARY_TYPE:
335 byte[] bytes = (byte[]) value;
336 output.writeInt(bytes.length);
339 case LithiumValue.YANG_IDENTIFIER_TYPE:
340 writeYangInstanceIdentifierInternal((YangInstanceIdentifier) value);
342 case LithiumValue.EMPTY_TYPE:
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);
350 output.writeUTF(value.toString());
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());
367 private void writeString(final @NonNull String string) throws IOException {
368 final Integer value = stringCodeMap.get(verifyNotNull(string));
370 stringCodeMap.put(string, stringCodeMap.size());
371 writeByte(LithiumTokens.IS_STRING_VALUE);
374 writeByte(LithiumTokens.IS_CODE_VALUE);
380 static final byte getSerializableType(final Object node) {
381 final Byte type = KNOWN_TYPES.get(requireNonNull(node).getClass());
383 if (type == LithiumValue.STRING_TYPE
384 && ((String) node).length() >= LithiumValue.STRING_BYTES_LENGTH_THRESHOLD) {
385 return LithiumValue.STRING_BYTES_TYPE;
390 if (node instanceof Set) {
391 return LithiumValue.BITS_TYPE;
394 if (node instanceof YangInstanceIdentifier) {
395 return LithiumValue.YANG_IDENTIFIER_TYPE;
398 throw new IllegalArgumentException("Unknown value type " + node.getClass().getSimpleName());