Merge "very basic tests for yang-binding-util"
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / codec / xml / XmlStreamUtils.java
index 64913914de515ad53f3d347c93ffc9b5def38149..aa379dc963f11606150fe370339eb21895d7edb8 100644 (file)
@@ -1,19 +1,21 @@
 package org.opendaylight.yangtools.yang.data.impl.codec.xml;
 
+import com.google.common.annotations.Beta;
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Preconditions;
-
 import java.net.URI;
+import java.util.Map;
 import java.util.Map.Entry;
-
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
 import javax.xml.stream.XMLStreamException;
 import javax.xml.stream.XMLStreamWriter;
-
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.Node;
 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
@@ -27,24 +29,61 @@ import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefi
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+/**
+ * Utility class for bridging JAXP Stream and YANG Data APIs. Note that the definition of this class
+ * by no means final and subject to change as more functionality is centralized here.
+ */
+@Beta
 public class XmlStreamUtils {
     private static final Logger LOG = LoggerFactory.getLogger(XmlStreamUtils.class);
+    private final XmlCodecProvider codecProvider;
 
-    public static void writeDataDocument(final XMLStreamWriter writer, final CompositeNode data, final SchemaNode schema, final XmlCodecProvider codecProvider) throws XMLStreamException {
-        //        final Boolean repairing = (Boolean) writer.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
-        //        Preconditions.checkArgument(repairing == true, "XML Stream Writer has to be repairing namespaces");
+    protected XmlStreamUtils(final XmlCodecProvider codecProvider) {
+        this.codecProvider = Preconditions.checkNotNull(codecProvider);
+    }
 
-        writer.writeStartDocument();
-        writeData(writer, data, schema, codecProvider);
-        writer.writeEndDocument();
-        writer.flush();
+    /**
+     * Create a new instance encapsulating a particular codec provider.
+     *
+     * @param codecProvider XML codec provider
+     * @return A new instance
+     */
+    public static XmlStreamUtils create(final XmlCodecProvider codecProvider) {
+        return new XmlStreamUtils(codecProvider);
     }
 
-    public static void writeDataDocument(final XMLStreamWriter writer, final CompositeNode data, final XmlCodecProvider codecProvider) throws XMLStreamException {
-        writeDataDocument(writer, data, null, codecProvider);
+    /**
+     * Check if a particular data element can be emitted as an empty element, bypassing value encoding. This
+     * functionality is optional, as valid XML stream is produced even if start/end element is produced unconditionally.
+     *
+     * @param data Data node
+     * @return True if the data node will result in empty element body.
+     */
+    public static boolean isEmptyElement(final Node<?> data) {
+        if (data == null) {
+            return true;
+        }
+
+        if (data instanceof CompositeNode) {
+            return ((CompositeNode) data).getValue().isEmpty();
+        }
+        if (data instanceof SimpleNode) {
+            return data.getValue() == null;
+        }
+
+        // Safe default
+        return false;
     }
 
-    public static void write(final XMLStreamWriter writer, final InstanceIdentifier id) throws XMLStreamException {
+    /**
+     * Write an InstanceIdentifier into the output stream. Calling corresponding {@link XMLStreamWriter#writeStartElement(String)}
+     * and {@link XMLStreamWriter#writeEndElement()} is the responsibility of the caller.
+     *
+     * @param writer XML Stream writer
+     * @param id InstanceIdentifier
+     * @throws XMLStreamException
+     */
+    public static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull YangInstanceIdentifier id) throws XMLStreamException {
         Preconditions.checkNotNull(writer, "Writer may not be null");
         Preconditions.checkNotNull(id, "Variable should contain instance of instance identifier and can't be null");
 
@@ -52,34 +91,97 @@ public class XmlStreamUtils {
         final String str = XmlUtils.encodeIdentifier(prefixes, id);
 
         for (Entry<URI, String> e: prefixes.getPrefixes()) {
-            writer.writeNamespace(e.getValue(), e.getKey().toString());
+            final String ns = e.getKey().toString();
+            final String p = e.getValue();
+
+            writer.writeNamespace(p, ns);
         }
         writer.writeCharacters(str);
     }
 
-    public static void writeData(final XMLStreamWriter writer, final Node<?> data, final SchemaNode schema, final XmlCodecProvider codecProvider) throws XMLStreamException {
+    /**
+     * Write a full XML document corresponding to a CompositeNode into an XML stream writer.
+     *
+     * @param writer XML Stream writer
+     * @param data data node
+     * @param schema corresponding schema node, may be null
+     * @throws XMLStreamException if an encoding problem occurs
+     */
+    public void writeDocument(final @Nonnull XMLStreamWriter writer, final @Nonnull CompositeNode data, final @Nullable SchemaNode schema) throws XMLStreamException {
+        // final Boolean repairing = (Boolean) writer.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
+        // Preconditions.checkArgument(repairing == true, "XML Stream Writer has to be repairing namespaces");
+
+        writer.writeStartDocument();
+        writeElement(writer, data, schema);
+        writer.writeEndDocument();
+        writer.flush();
+    }
+
+    /**
+     * Short-hand for {@link #writeDataDocument(XMLStreamWriter, CompositeNode, SchemaNode, XmlCodecProvider)} with
+     * null SchemaNode.
+     *
+     * @param writer XML Stream writer
+     * @param data data node
+     * @param schema corresponding schema node, may be null
+     * @throws XMLStreamException if an encoding problem occurs
+     */
+    public void writeDocument(final XMLStreamWriter writer, final CompositeNode data) throws XMLStreamException {
+        writeDocument(writer, data, null);
+    }
+
+    /**
+     * Write an element into a XML stream writer. This includes the element start/end tags and
+     * the value of the element.
+     *
+     * @param writer XML Stream writer
+     * @param data data node
+     * @param schema Schema node
+     * @throws XMLStreamException if an encoding problem occurs
+     */
+    public void writeElement(final XMLStreamWriter writer, final @Nonnull Node<?> data, final SchemaNode schema) throws XMLStreamException {
         final QName qname = data.getNodeType();
         final String pfx = qname.getPrefix() != null ? qname.getPrefix() : "";
-        final String ns;
-        if (qname.getNamespace() != null) {
-            ns = qname.getNamespace().toString();
-        } else {
-            ns = "";
+        final String ns = qname.getNamespace() != null ? qname.getNamespace().toString() : "";
+
+        if (isEmptyElement(data)) {
+            if (hasAttributes(data)) {
+                writer.writeStartElement(pfx, qname.getLocalName(), ns);
+                final RandomPrefix randomPrefix = new RandomPrefix();
+                writeAttributes(writer, (AttributesContainer) data, randomPrefix);
+                writer.writeEndElement();
+            } else {
+                writer.writeEmptyElement(pfx, qname.getLocalName(), ns);
+            }
+            return;
         }
 
         writer.writeStartElement(pfx, qname.getLocalName(), ns);
-        if (data instanceof AttributesContainer && ((AttributesContainer) data).getAttributes() != null) {
-            for (Entry<QName, String> attribute : ((AttributesContainer) data).getAttributes().entrySet()) {
-                writer.writeAttribute(attribute.getKey().getNamespace().toString(), attribute.getKey().getLocalName(), attribute.getValue());
-            }
+        writeValue(writer, data, schema);
+        writer.writeEndElement();
+    }
+
+    /**
+     * Write a value into a XML stream writer. This method assumes the start and end of element is
+     * emitted by the caller.
+     *
+     * @param writer XML Stream writer
+     * @param data data node
+     * @param schema Schema node
+     * @throws XMLStreamException if an encoding problem occurs
+     */
+    public void writeValue(final XMLStreamWriter writer, final @Nonnull Node<?> data, final SchemaNode schema) throws XMLStreamException {
+        if (hasAttributes(data)) {
+            RandomPrefix randomPrefix = new RandomPrefix();
+            writeAttributes(writer, (AttributesContainer) data, randomPrefix);
         }
 
         if (data instanceof SimpleNode<?>) {
             // Simple node
             if (schema instanceof LeafListSchemaNode) {
-                writeValue(writer, ((LeafListSchemaNode) schema).getType(), codecProvider, data.getValue());
+                writeValue(writer, ((LeafListSchemaNode) schema).getType(), data.getValue());
             } else if (schema instanceof LeafSchemaNode) {
-                writeValue(writer, ((LeafSchemaNode) schema).getType(), codecProvider, data.getValue());
+                writeValue(writer, ((LeafSchemaNode) schema).getType(), data.getValue());
             } else {
                 Object value = data.getValue();
                 if (value != null) {
@@ -99,62 +201,99 @@ public class XmlStreamUtils {
                     }
                 }
 
-                writeData(writer, child, childSchema, codecProvider);
+                writeElement(writer, child, childSchema);
             }
         }
+    }
 
-        writer.writeEndElement();
+    private static void writeAttributes(final XMLStreamWriter writer, final AttributesContainer data, final RandomPrefix randomPrefix) throws XMLStreamException {
+        for (Entry<QName, String> attribute : data.getAttributes().entrySet()) {
+            writeAttribute(writer, attribute, randomPrefix);
+        }
+    }
+
+    private static boolean hasAttributes(final Node<?> data) {
+        if (data instanceof AttributesContainer) {
+            final Map<QName, String> c = ((AttributesContainer) data).getAttributes();
+            return c != null && !c.isEmpty();
+        } else {
+            return false;
+        }
+    }
+
+    @VisibleForTesting
+    static void writeAttribute(final XMLStreamWriter writer, final Entry<QName, String> attribute, final RandomPrefix randomPrefix)
+            throws XMLStreamException {
+        final QName key = attribute.getKey();
+        final String prefix = randomPrefix.encodePrefix(key.getNamespace());
+        writer.writeAttribute("xmlns:" + prefix, key.getNamespace().toString());
+        writer.writeAttribute(prefix, key.getNamespace().toString(), key.getLocalName(), attribute.getValue());
     }
 
-    public static void writeValue(final XMLStreamWriter writer, final TypeDefinition<?> type, final XmlCodecProvider codecProvider, final Object nodeValue) throws XMLStreamException {
-        TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
+    /**
+     * Write a value into a XML stream writer. This method assumes the start and end of element is
+     * emitted by the caller.
+     *
+     * @param writer XML Stream writer
+     * @param type data type
+     * @param value data value
+     * @throws XMLStreamException if an encoding problem occurs
+     */
+    public void writeValue(final @Nonnull XMLStreamWriter writer, final @Nonnull TypeDefinition<?> type, final Object value) throws XMLStreamException {
+        if (value == null) {
+            LOG.debug("Value of {}:{} is null, not encoding it", type.getQName().getNamespace(), type.getQName().getLocalName());
+            return;
+        }
+
+        final TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
         if (baseType instanceof IdentityrefTypeDefinition) {
-            if (nodeValue instanceof QName) {
-                QName value = (QName) nodeValue;
-                String prefix = "x";
-                if (value.getPrefix() != null && !value.getPrefix().isEmpty()) {
-                    prefix = value.getPrefix();
+            write(writer, (IdentityrefTypeDefinition) baseType, value);
+        } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
+            write(writer, (InstanceIdentifierTypeDefinition) baseType, value);
+        } else {
+            final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
+            String text;
+            if (codec != null) {
+                try {
+                    text = codec.serialize(value);
+                } catch (ClassCastException e) {
+                    LOG.error("Provided node value {} did not have type {} required by mapping. Using stream instead.", value, baseType, e);
+                    text = String.valueOf(value);
                 }
-
-                writer.writeNamespace(prefix, value.getNamespace().toString());
-                writer.writeCharacters(prefix + ':' + value.getLocalName());
             } else {
-                Object value = nodeValue;
-                LOG.debug("Value of {}:{} is not instance of QName but is {}", baseType.getQName().getNamespace(),
-                        baseType.getQName().getLocalName(), value != null ? value.getClass() : "null");
-                if (value != null) {
-                    writer.writeCharacters(String.valueOf(value));
-                }
+                LOG.error("Failed to find codec for {}, falling back to using stream", baseType);
+                text = String.valueOf(value);
             }
-        } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
-            if (nodeValue instanceof InstanceIdentifier) {
-                write(writer, (InstanceIdentifier)nodeValue);
+            writer.writeCharacters(text);
+        }
+    }
+
+    @SuppressWarnings("deprecation")
+    private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull IdentityrefTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
+        if (value instanceof QName) {
+            final QName qname = (QName) value;
+            final String prefix;
+            if (qname.getPrefix() != null && !qname.getPrefix().isEmpty()) {
+                prefix = qname.getPrefix();
             } else {
-                Object value = nodeValue;
-                LOG.debug("Value of {}:{} is not instance of InstanceIdentifier but is {}", baseType.getQName()
-                        .getNamespace(), //
-                        baseType.getQName().getLocalName(), value != null ? value.getClass() : "null");
-                if (value != null) {
-                    writer.writeCharacters(String.valueOf(value));
-                }
+                prefix = "x";
             }
+
+            final String ns = qname.getNamespace().toString();
+            writer.writeNamespace(prefix, ns);
+            writer.writeCharacters(prefix + ':' + qname.getLocalName());
         } else {
-            if (nodeValue != null) {
-                final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
-                String text;
-                if (codec != null) {
-                    try {
-                        text = codec.serialize(nodeValue);
-                    } catch (ClassCastException e) {
-                        LOG.error("Provided node value {} did not have type {} required by mapping. Using stream instead.", nodeValue, baseType, e);
-                        text = String.valueOf(nodeValue);
-                    }
-                } else {
-                    LOG.error("Failed to find codec for {}, falling back to using stream", baseType);
-                    text = String.valueOf(nodeValue);
-                }
-                writer.writeCharacters(text);
-            }
+            LOG.debug("Value of {}:{} is not a QName but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
+            writer.writeCharacters(String.valueOf(value));
+        }
+    }
+
+    private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull InstanceIdentifierTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
+        if (value instanceof YangInstanceIdentifier) {
+            write(writer, (YangInstanceIdentifier)value);
+        } else {
+            LOG.warn("Value of {}:{} is not an InstanceIdentifier but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
+            writer.writeCharacters(String.valueOf(value));
         }
     }
 }