1 package org.opendaylight.yangtools.yang.data.impl.codec.xml;
3 import com.google.common.annotations.Beta;
4 import com.google.common.base.Preconditions;
7 import java.util.Map.Entry;
9 import javax.annotation.Nonnull;
10 import javax.annotation.Nullable;
11 import javax.xml.stream.XMLStreamException;
12 import javax.xml.stream.XMLStreamWriter;
14 import org.opendaylight.yangtools.yang.common.QName;
15 import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
16 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
17 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
18 import org.opendaylight.yangtools.yang.data.api.Node;
19 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
20 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
21 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
22 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
23 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
24 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
25 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
26 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
27 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
28 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
29 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
34 * Utility class for bridging JAXP Stream and YANG Data APIs. Note that the definition of this class
35 * by no means final and subject to change as more functionality is centralized here.
38 public class XmlStreamUtils {
39 private static final Logger LOG = LoggerFactory.getLogger(XmlStreamUtils.class);
40 private final XmlCodecProvider codecProvider;
42 protected XmlStreamUtils(final XmlCodecProvider codecProvider) {
43 this.codecProvider = Preconditions.checkNotNull(codecProvider);
47 * Create a new instance encapsulating a particular codec provider.
49 * @param codecProvider XML codec provider
50 * @return A new instance
52 public static XmlStreamUtils create(final XmlCodecProvider codecProvider) {
53 return new XmlStreamUtils(codecProvider);
57 * Check if a particular data element can be emitted as an empty element, bypassing value encoding. This
58 * functionality is optional, as valid XML stream is produced even if start/end element is produced unconditionally.
60 * @param data Data node
61 * @return True if the data node will result in empty element body.
63 public static boolean isEmptyElement(final Node<?> data) {
68 if (data instanceof CompositeNode) {
69 return ((CompositeNode) data).getValue().isEmpty();
71 if (data instanceof SimpleNode) {
72 return data.getValue() == null;
80 * Write an InstanceIdentifier into the output stream. Calling corresponding {@link XMLStreamWriter#writeStartElement(String)}
81 * and {@link XMLStreamWriter#writeEndElement()} is the responsibility of the caller.
83 * @param writer XML Stream writer
84 * @param id InstanceIdentifier
85 * @throws XMLStreamException
87 public static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull InstanceIdentifier id) throws XMLStreamException {
88 Preconditions.checkNotNull(writer, "Writer may not be null");
89 Preconditions.checkNotNull(id, "Variable should contain instance of instance identifier and can't be null");
91 final RandomPrefix prefixes = new RandomPrefix();
92 final String str = XmlUtils.encodeIdentifier(prefixes, id);
94 for (Entry<URI, String> e: prefixes.getPrefixes()) {
95 writer.writeNamespace(e.getValue(), e.getKey().toString());
97 writer.writeCharacters(str);
101 * Write a full XML document corresponding to a CompositeNode into an XML stream writer.
103 * @param writer XML Stream writer
104 * @param data data node
105 * @param schema corresponding schema node, may be null
106 * @throws XMLStreamException if an encoding problem occurs
108 public void writeDocument(final @Nonnull XMLStreamWriter writer, final @Nonnull CompositeNode data, final @Nullable SchemaNode schema) throws XMLStreamException {
109 // final Boolean repairing = (Boolean) writer.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
110 // Preconditions.checkArgument(repairing == true, "XML Stream Writer has to be repairing namespaces");
112 writer.writeStartDocument();
113 writeElement(writer, data, schema);
114 writer.writeEndDocument();
119 * Short-hand for {@link #writeDataDocument(XMLStreamWriter, CompositeNode, SchemaNode, XmlCodecProvider)} with
122 * @param writer XML Stream writer
123 * @param data data node
124 * @param schema corresponding schema node, may be null
125 * @throws XMLStreamException if an encoding problem occurs
127 public void writeDocument(final XMLStreamWriter writer, final CompositeNode data) throws XMLStreamException {
128 writeDocument(writer, data, null);
132 * Write an element into a XML stream writer. This includes the element start/end tags and
133 * the value of the element.
135 * @param writer XML Stream writer
136 * @param data data node
137 * @param schema Schema node
138 * @throws XMLStreamException if an encoding problem occurs
140 public void writeElement(final XMLStreamWriter writer, final @Nonnull Node<?> data, final SchemaNode schema) throws XMLStreamException {
141 final QName qname = data.getNodeType();
142 final String pfx = qname.getPrefix() != null ? qname.getPrefix() : "";
143 final String ns = qname.getNamespace() != null ? qname.getNamespace().toString() : "";
145 if (isEmptyElement(data)) {
146 writer.writeEmptyElement(pfx, qname.getLocalName(), ns);
150 writer.writeStartElement(pfx, qname.getLocalName(), ns);
151 if (data instanceof AttributesContainer && ((AttributesContainer) data).getAttributes() != null) {
152 for (Entry<QName, String> attribute : ((AttributesContainer) data).getAttributes().entrySet()) {
153 writer.writeAttribute(attribute.getKey().getNamespace().toString(), attribute.getKey().getLocalName(), attribute.getValue());
157 if (data instanceof SimpleNode<?>) {
159 if (schema instanceof LeafListSchemaNode) {
160 writeValue(writer, ((LeafListSchemaNode) schema).getType(), data.getValue());
161 } else if (schema instanceof LeafSchemaNode) {
162 writeValue(writer, ((LeafSchemaNode) schema).getType(), data.getValue());
164 Object value = data.getValue();
166 writer.writeCharacters(String.valueOf(value));
171 for (Node<?> child : ((CompositeNode) data).getValue()) {
172 DataSchemaNode childSchema = null;
173 if (schema instanceof DataNodeContainer) {
174 childSchema = SchemaUtils.findFirstSchema(child.getNodeType(), ((DataNodeContainer) schema).getChildNodes()).orNull();
175 if (LOG.isDebugEnabled()) {
176 if (childSchema == null) {
177 LOG.debug("Probably the data node \"{}\" does not conform to schema", child == null ? "" : child.getNodeType().getLocalName());
182 writeElement(writer, child, childSchema);
186 writer.writeEndElement();
190 * Write a value into a XML stream writer. This method assumes the start and end of element is
191 * emitted by the caller.
193 * @param writer XML Stream writer
194 * @param data data node
195 * @param schema Schema node
196 * @throws XMLStreamException if an encoding problem occurs
198 public void writeValue(final @Nonnull XMLStreamWriter writer, final @Nonnull TypeDefinition<?> type, final Object value) throws XMLStreamException {
200 LOG.debug("Value of {}:{} is null, not encoding it", type.getQName().getNamespace(), type.getQName().getLocalName());
204 final TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
205 if (baseType instanceof IdentityrefTypeDefinition) {
206 write(writer, (IdentityrefTypeDefinition) baseType, value);
207 } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
208 write(writer, (InstanceIdentifierTypeDefinition) baseType, value);
210 final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
214 text = codec.serialize(value);
215 } catch (ClassCastException e) {
216 LOG.error("Provided node value {} did not have type {} required by mapping. Using stream instead.", value, baseType, e);
217 text = String.valueOf(value);
220 LOG.error("Failed to find codec for {}, falling back to using stream", baseType);
221 text = String.valueOf(value);
223 writer.writeCharacters(text);
227 private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull IdentityrefTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
228 if (value instanceof QName) {
229 final QName qname = (QName) value;
231 if (qname.getPrefix() != null && !qname.getPrefix().isEmpty()) {
232 prefix = qname.getPrefix();
237 writer.writeNamespace(prefix, qname.getNamespace().toString());
238 writer.writeCharacters(prefix + ':' + qname.getLocalName());
240 LOG.debug("Value of {}:{} is not a QName but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
241 writer.writeCharacters(String.valueOf(value));
245 private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull InstanceIdentifierTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
246 if (value instanceof InstanceIdentifier) {
247 write(writer, (InstanceIdentifier)value);
249 LOG.debug("Value of {}:{} is not an InstanceIdentifier but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
250 writer.writeCharacters(String.valueOf(value));