Bug 1848: Make sure that XmlStreamUtils preserve list key order.
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / codec / xml / XmlStreamUtils.java
index 14b5c8593f5d85b68533d95bd496929653a03cd6..d0292d1029ce9cde5181aefb6d82d0f28b307d44 100644 (file)
@@ -3,15 +3,15 @@ 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.Collection;
+import java.util.Collections;
+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;
@@ -24,6 +24,7 @@ import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
@@ -93,7 +94,10 @@ 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);
     }
@@ -117,12 +121,11 @@ public class XmlStreamUtils {
     }
 
     /**
-     * Short-hand for {@link #writeDataDocument(XMLStreamWriter, CompositeNode, SchemaNode, XmlCodecProvider)} with
+     * Short-hand for {@link #writeDocument(XMLStreamWriter, CompositeNode, SchemaNode)})} 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 {
@@ -144,7 +147,14 @@ public class XmlStreamUtils {
         final String ns = qname.getNamespace() != null ? qname.getNamespace().toString() : "";
 
         if (isEmptyElement(data)) {
-            writer.writeEmptyElement(pfx, qname.getLocalName(), ns);
+            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;
         }
 
@@ -163,11 +173,9 @@ public class XmlStreamUtils {
      * @throws XMLStreamException if an encoding problem occurs
      */
     public void writeValue(final XMLStreamWriter writer, final @Nonnull Node<?> data, final SchemaNode schema) throws XMLStreamException {
-        if (data instanceof AttributesContainer && ((AttributesContainer) data).getAttributes() != null) {
+        if (hasAttributes(data)) {
             RandomPrefix randomPrefix = new RandomPrefix();
-            for (Entry<QName, String> attribute : ((AttributesContainer) data).getAttributes().entrySet()) {
-                writeAttribute(writer, attribute, randomPrefix);
-            }
+            writeAttributes(writer, (AttributesContainer) data, randomPrefix);
         }
 
         if (data instanceof SimpleNode<?>) {
@@ -184,22 +192,64 @@ public class XmlStreamUtils {
             }
         } else {
             // CompositeNode
-            for (Node<?> child : ((CompositeNode) data).getValue()) {
-                DataSchemaNode childSchema = null;
-                if (schema instanceof DataNodeContainer) {
-                    childSchema = SchemaUtils.findFirstSchema(child.getNodeType(), ((DataNodeContainer) schema).getChildNodes()).orNull();
-                    if (LOG.isDebugEnabled()) {
-                        if (childSchema == null) {
-                            LOG.debug("Probably the data node \"{}\" does not conform to schema", child == null ? "" : child.getNodeType().getLocalName());
-                        }
-                    }
+            final CompositeNode castedData = ((CompositeNode) data);
+            final DataNodeContainer castedSchema;
+            if (schema instanceof DataNodeContainer) {
+                castedSchema = (DataNodeContainer) schema;
+            } else {
+                castedSchema = null;
+            }
+            final Collection<QName> keyLeaves;
+            if (schema instanceof ListSchemaNode) {
+                keyLeaves = ((ListSchemaNode) schema).getKeyDefinition();
+
+            } else {
+                keyLeaves = Collections.emptyList();
+
+            }
+            for (QName key : keyLeaves) {
+                SimpleNode<?> keyLeaf = castedData.getFirstSimpleByName(key);
+                if(keyLeaf != null) {
+                    writeChildElement(writer,keyLeaf,castedSchema);
                 }
+            }
 
-                writeElement(writer, child, childSchema);
+            for (Node<?> child : castedData.getValue()) {
+                if(keyLeaves.contains(child.getNodeType())) {
+                    // Skip key leaf which was written by previous for loop.
+                    continue;
+                }
+                writeChildElement(writer,child,castedSchema);
             }
         }
     }
 
+    private void writeChildElement(XMLStreamWriter writer, Node<?> child, DataNodeContainer parentSchema) throws XMLStreamException {
+        DataSchemaNode childSchema = null;
+        if (parentSchema != null) {
+            childSchema = SchemaUtils.findFirstSchema(child.getNodeType(), parentSchema.getChildNodes()).orNull();
+            if ((childSchema == null) && LOG.isDebugEnabled()) {
+                LOG.debug("Probably the data node \"{}\" does not conform to schema", child == null ? "" : child.getNodeType().getLocalName());
+            }
+        }
+        writeElement(writer, child, childSchema);
+    }
+
+    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 {
@@ -247,6 +297,7 @@ public class XmlStreamUtils {
         }
     }
 
+    @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;
@@ -257,7 +308,8 @@ public class XmlStreamUtils {
                 prefix = "x";
             }
 
-            writer.writeNamespace(prefix, qname.getNamespace().toString());
+            final String ns = qname.getNamespace().toString();
+            writer.writeNamespace(prefix, ns);
             writer.writeCharacters(prefix + ':' + qname.getLocalName());
         } else {
             LOG.debug("Value of {}:{} is not a QName but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
@@ -269,7 +321,7 @@ public class XmlStreamUtils {
         if (value instanceof YangInstanceIdentifier) {
             write(writer, (YangInstanceIdentifier)value);
         } else {
-            LOG.debug("Value of {}:{} is not an InstanceIdentifier but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
+            LOG.warn("Value of {}:{} is not an InstanceIdentifier but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
             writer.writeCharacters(String.valueOf(value));
         }
     }