Clean up XMLStreamWriterUtils
[yangtools.git] / yang / yang-data-codec-xml / src / main / java / org / opendaylight / yangtools / yang / data / codec / xml / XMLStreamWriterUtils.java
1 /*
2  * Copyright (c) 2015 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.xml;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11
12 import com.google.common.annotations.VisibleForTesting;
13 import javax.xml.stream.XMLStreamException;
14 import org.eclipse.jdt.annotation.NonNull;
15 import org.opendaylight.yangtools.yang.common.QName;
16 import org.opendaylight.yangtools.yang.common.QNameModule;
17 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
18 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
19 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
20 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
21 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
22 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
23 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
24 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28 /**
29  * Utility class for bridging JAXP Stream and YANG Data APIs. Note that the definition of this class
30  * by no means final and subject to change as more functionality is centralized here.
31  */
32 abstract class XMLStreamWriterUtils {
33     private static final Logger LOG = LoggerFactory.getLogger(XMLStreamWriterUtils.class);
34
35     /**
36      * Write a value into a XML stream writer. This method assumes the start and end of element is
37      * emitted by the caller.
38      *
39      * @param writer XML Stream writer
40      * @param schemaNode Schema node that describes the value
41      * @param value data value
42      * @param parent module QName owning the leaf definition
43      * @throws XMLStreamException if an encoding problem occurs
44      */
45     void writeValue(final @NonNull ValueWriter writer, final @NonNull SchemaNode schemaNode,
46             final @NonNull Object value, final QNameModule parent) throws XMLStreamException {
47         checkArgument(schemaNode instanceof TypedDataSchemaNode,
48             "Unable to write value for node %s, only nodes of type: leaf and leaf-list can be written at this point",
49             schemaNode.getQName());
50
51         TypeDefinition<?> type = ((TypedDataSchemaNode) schemaNode).getType();
52         if (type instanceof LeafrefTypeDefinition) {
53             type = getBaseTypeForLeafRef(schemaNode, (LeafrefTypeDefinition) type);
54         }
55
56         writeValue(writer, type, value, parent);
57     }
58
59     /**
60      * Write a value into a XML stream writer. This method assumes the start and end of element is
61      * emitted by the caller.
62      *
63      * @param writer XML Stream writer
64      * @param type data type. In case of leaf ref this should be the type of leaf being referenced
65      * @param value data value
66      * @param parent optional parameter of a module QName owning the leaf definition
67      * @throws XMLStreamException if an encoding problem occurs
68      */
69     private void writeValue(final @NonNull ValueWriter writer, final @NonNull TypeDefinition<?> type,
70             final @NonNull Object value, final QNameModule parent) throws XMLStreamException {
71         if (type instanceof IdentityrefTypeDefinition) {
72             write(writer, (IdentityrefTypeDefinition) type, value, parent);
73         } else if (type instanceof InstanceIdentifierTypeDefinition) {
74             write(writer, (InstanceIdentifierTypeDefinition) type, value);
75         } else {
76             writer.writeCharacters(serialize(type, value));
77         }
78     }
79
80     private static String serialize(final @NonNull TypeDefinition<?> type, final @NonNull Object value) {
81         final TypeDefinitionAwareCodec<Object, ?> codec = TypeDefinitionAwareCodec.from(type);
82         if (codec == null) {
83             LOG.warn("Failed to find codec for {}, falling back to using stream", type);
84             return value.toString();
85         }
86
87         try {
88             return codec.serialize(value);
89         } catch (ClassCastException e) {
90             LOG.warn("Provided node value {} did not have type {} required by mapping. Using stream instead.",
91                 value, type, e);
92             return value.toString();
93         }
94     }
95
96     @VisibleForTesting
97     static void write(final @NonNull ValueWriter writer, final @NonNull IdentityrefTypeDefinition type,
98             final @NonNull Object value, final QNameModule parent) throws XMLStreamException {
99         if (value instanceof QName) {
100             final QName qname = (QName) value;
101
102             //in case parent is present and same as element namespace write value without namespace
103             if (qname.getNamespace().equals(parent.getNamespace())) {
104                 writer.writeCharacters(qname.getLocalName());
105             } else {
106                 final String ns = qname.getNamespace().toString();
107                 final String prefix = "x";
108                 writer.writeNamespace(prefix, ns);
109                 writer.writeCharacters(prefix + ':' + qname.getLocalName());
110             }
111         } else {
112             final QName qname = type.getQName();
113             LOG.debug("Value of {}:{} is not a QName but {}", qname.getNamespace(), qname.getLocalName(),
114                 value.getClass());
115             writer.writeToStringCharacters(value);
116         }
117     }
118
119     private void write(final @NonNull ValueWriter writer, final @NonNull InstanceIdentifierTypeDefinition type,
120             final @NonNull Object value) throws XMLStreamException {
121         if (value instanceof YangInstanceIdentifier) {
122             writeInstanceIdentifier(writer, (YangInstanceIdentifier)value);
123         } else {
124             final QName qname = type.getQName();
125             LOG.warn("Value of {}:{} is not an InstanceIdentifier but {}", qname.getNamespace(), qname.getLocalName(),
126                 value.getClass());
127             writer.writeToStringCharacters(value);
128         }
129     }
130
131     abstract @NonNull TypeDefinition<?> getBaseTypeForLeafRef(SchemaNode schemaNode,
132             @NonNull LeafrefTypeDefinition type);
133
134     abstract void writeInstanceIdentifier(@NonNull ValueWriter writer, YangInstanceIdentifier value)
135             throws XMLStreamException;
136 }