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.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;
49 * "original" type mapping. Baseline is Lithium but it really was introduced in Oxygen, where {@code type empty} was
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
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)
74 private final Map<String, Integer> stringCodeMap = new HashMap<>();
76 private QName lastLeafSetQName;
77 private boolean inSimple;
79 AbstractLithiumDataOutput(final DataOutput output) {
84 public final void startLeafNode(final NodeIdentifier name) throws IOException {
85 LOG.trace("Starting a new leaf node");
86 startNode(name, LithiumNode.LEAF_NODE);
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);
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);
102 private void commonStartLeafSet(final NodeIdentifier name, final byte nodeType) throws IOException {
103 startNode(name, nodeType);
104 lastLeafSetQName = name.getNodeType();
108 public final void startLeafSetEntryNode(final NodeWithValue<?> name) throws IOException {
109 LOG.trace("Starting a new leaf set entry node");
111 output.writeByte(LithiumNode.LEAF_SET_ENTRY_NODE);
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());
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);
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);
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);
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);
146 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
148 LOG.trace("Starting a new map entry node");
149 startNode(identifier, LithiumNode.MAP_ENTRY_NODE);
150 writeKeyValueMap(identifier.entrySet());
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);
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);
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");
170 output.writeByte(LithiumNode.AUGMENTATION_NODE);
171 writeAugmentationIdentifier(identifier);
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);
186 public final void scalarValue(final Object value) throws IOException {
191 public final void domSourceValue(final DOMSource value) throws IOException {
192 final StringWriter writer = new StringWriter();
194 TF.newTransformer().transform(value, new StreamResult(writer));
195 } catch (TransformerException e) {
196 throw new IOException("Error writing anyXml", e);
198 writeObject(writer.toString());
202 public final void endNode() throws IOException {
203 LOG.trace("Ending the node");
205 lastLeafSetQName = null;
206 output.writeByte(LithiumNode.END_NODE);
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);
219 case LithiumPathArgument.NODE_IDENTIFIER:
220 NodeIdentifier nodeIdentifier = (NodeIdentifier) pathArgument;
221 writeQNameInternal(nodeIdentifier.getNodeType());
223 case LithiumPathArgument.NODE_IDENTIFIER_WITH_PREDICATES:
224 NodeIdentifierWithPredicates nodeIdentifierWithPredicates =
225 (NodeIdentifierWithPredicates) pathArgument;
226 writeQNameInternal(nodeIdentifierWithPredicates.getNodeType());
227 writeKeyValueMap(nodeIdentifierWithPredicates.entrySet());
229 case LithiumPathArgument.NODE_IDENTIFIER_WITH_VALUE:
230 NodeWithValue<?> nodeWithValue = (NodeWithValue<?>) pathArgument;
231 writeQNameInternal(nodeWithValue.getNodeType());
232 writeObject(nodeWithValue.getValue());
234 case LithiumPathArgument.AUGMENTATION_IDENTIFIER:
235 // No Qname in augmentation identifier
236 writeAugmentationIdentifier((AugmentationIdentifier) pathArgument);
239 throw new IllegalStateException("Unknown node identifier type is found : "
240 + pathArgument.getClass().toString());
245 final void writeYangInstanceIdentifierInternal(final YangInstanceIdentifier identifier) throws IOException {
246 List<PathArgument> pathArguments = identifier.getPathArguments();
247 output.writeInt(pathArguments.size());
249 for (PathArgument pathArgument : pathArguments) {
250 writePathArgumentInternal(pathArgument);
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);
263 LOG.debug("augmentation node does not have any child");
268 final void defaultWriteQName(final QName qname) throws IOException {
269 writeString(qname.getLocalName());
270 writeModule(qname.getModule());
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());
279 writeByte(LithiumTokens.IS_NULL_VALUE);
283 abstract void writeModule(QNameModule module) throws IOException;
285 abstract void writeAugmentationIdentifier(@NonNull AugmentationIdentifier aid) throws IOException;
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");
291 // First write the type of node
292 output.writeByte(nodeType);
294 writeQNameInternal(arg.getNodeType());
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);
305 private void writeObject(final Object value) throws IOException {
306 byte type = getSerializableType(value);
307 // Write object type first
308 output.writeByte(type);
311 case LithiumValue.BOOL_TYPE:
312 output.writeBoolean((Boolean) value);
314 case LithiumValue.QNAME_TYPE:
315 writeQNameInternal((QName) value);
317 case LithiumValue.INT_TYPE:
318 output.writeInt((Integer) value);
320 case LithiumValue.BYTE_TYPE:
321 output.writeByte((Byte) value);
323 case LithiumValue.LONG_TYPE:
324 output.writeLong((Long) value);
326 case LithiumValue.SHORT_TYPE:
327 output.writeShort((Short) value);
329 case LithiumValue.BITS_TYPE:
330 writeObjSet((Set<?>) value);
332 case LithiumValue.BINARY_TYPE:
333 byte[] bytes = (byte[]) value;
334 output.writeInt(bytes.length);
337 case LithiumValue.YANG_IDENTIFIER_TYPE:
338 writeYangInstanceIdentifierInternal((YangInstanceIdentifier) value);
340 case LithiumValue.EMPTY_TYPE:
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);
348 output.writeUTF(value.toString());
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());
365 private void writeString(final @NonNull String string) throws IOException {
366 final Integer value = stringCodeMap.get(verifyNotNull(string));
368 stringCodeMap.put(string, stringCodeMap.size());
369 writeByte(LithiumTokens.IS_STRING_VALUE);
372 writeByte(LithiumTokens.IS_CODE_VALUE);
378 static final byte getSerializableType(final Object node) {
379 final Byte type = KNOWN_TYPES.get(requireNonNull(node).getClass());
381 if (type == LithiumValue.STRING_TYPE
382 && ((String) node).length() >= LithiumValue.STRING_BYTES_LENGTH_THRESHOLD) {
383 return LithiumValue.STRING_BYTES_TYPE;
388 if (node instanceof Set) {
389 return LithiumValue.BITS_TYPE;
392 if (node instanceof YangInstanceIdentifier) {
393 return LithiumValue.YANG_IDENTIFIER_TYPE;
396 throw new IllegalArgumentException("Unknown value type " + node.getClass().getSimpleName());