Merge "BUG-461 Test transformation of rpc input using XmlDocumentUtils"
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / codec / xml / XmlDocumentUtils.java
index ce2f036f16153e3e5383e32467304a00c5555fe6..02f020c47fdc98307eb4ad2cf9aff0621cfb9529 100644 (file)
@@ -35,15 +35,12 @@ import javax.xml.transform.dom.DOMResult;
 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.ModifyAction;
 import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
 import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
-import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
@@ -57,7 +54,6 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 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;
-import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.w3c.dom.Attr;
@@ -87,12 +83,6 @@ public class XmlDocumentUtils {
     public static final QName OPERATION_ATTRIBUTE_QNAME = QName.create(URI.create("urn:ietf:params:xml:ns:netconf:base:1.0"), null, "operation");
     private static final Logger logger = LoggerFactory.getLogger(XmlDocumentUtils.class);
     private static final XMLOutputFactory FACTORY = XMLOutputFactory.newFactory();
-    private static final XmlCodecProvider DEFAULT_XML_VALUE_CODEC_PROVIDER = new XmlCodecProvider() {
-        @Override
-        public TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codecFor(final TypeDefinition<?> baseType) {
-            return TypeDefinitionAwareCodec.from(baseType);
-        }
-    };
 
     /**
      * Converts Data DOM structure to XML Document for specified XML Codec Provider and corresponding
@@ -115,7 +105,7 @@ public class XmlDocumentUtils {
             throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
         }
 
-        final DOMResult result = new DOMResult();
+        final DOMResult result = new DOMResult(getDocument());
         try {
             final XMLStreamWriter writer = FACTORY.createXMLStreamWriter(result);
             XmlStreamUtils.create(codecProvider).writeDocument(writer, data, (SchemaNode)schema);
@@ -150,7 +140,7 @@ public class XmlDocumentUtils {
      * @throws UnsupportedDataTypeException
      */
     public static Document toDocument(final CompositeNode data, final XmlCodecProvider codecProvider) {
-        final DOMResult result = new DOMResult();
+        final DOMResult result = new DOMResult(getDocument());
         try {
             final XMLStreamWriter writer = FACTORY.createXMLStreamWriter(result);
             XmlStreamUtils.create(codecProvider).writeDocument(writer, data);
@@ -192,87 +182,23 @@ public class XmlDocumentUtils {
         return createElementFor(doc, data.getNodeType(), data);
     }
 
-    public static void writeValueByType(final Element element, final SimpleNode<?> node, final TypeDefinition<?> type,
-            final DataSchemaNode schema, final XmlCodecProvider codecProvider) {
-
-        Object nodeValue = node.getValue();
-
-        writeValueByType(element, type, codecProvider, nodeValue);
-    }
-
-    public static void writeValueByType(final Element element, final TypeDefinition<?> type, final XmlCodecProvider codecProvider, final Object nodeValue) {
-        TypeDefinition<?> baseType = 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();
-                }
-                element.setAttribute("xmlns:" + prefix, value.getNamespace().toString());
-                element.setTextContent(prefix + ":" + value.getLocalName());
-            } else {
-                Object value = nodeValue;
-                logger.debug("Value of {}:{} is not instance of QName but is {}", baseType.getQName().getNamespace(),
-                        baseType.getQName().getLocalName(), value != null ? value.getClass() : "null");
-                if (value != null) {
-                    element.setTextContent(String.valueOf(value));
-                }
-            }
-        } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
-            if (nodeValue instanceof InstanceIdentifier) {
-                InstanceIdentifierForXmlCodec.serialize((InstanceIdentifier)nodeValue,element);
-            } else {
-                Object value = nodeValue;
-                logger.debug("Value of {}:{} is not instance of InstanceIdentifier but is {}", baseType.getQName()
-                        .getNamespace(), //
-                        baseType.getQName().getLocalName(), value != null ? value.getClass() : "null");
-                if (value != null) {
-                    element.setTextContent(String.valueOf(value));
-                }
-            }
-        } else {
-            if (nodeValue != null) {
-                final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
-                if (codec != null) {
-                    try {
-                        final String text = codec.serialize(nodeValue);
-                        element.setTextContent(text);
-                    } catch (ClassCastException e) {
-                        logger.error("Provided node value {} did not have type {} required by mapping. Using stream instead.", nodeValue, baseType, e);
-                        element.setTextContent(String.valueOf(nodeValue));
-                    }
-                } else {
-                    logger.error("Failed to find codec for {}, falling back to using stream", baseType);
-                    element.setTextContent(String.valueOf(nodeValue));
-                }
-            }
-        }
-    }
-
-    public final static TypeDefinition<?> resolveBaseTypeFrom(final TypeDefinition<?> type) {
-        TypeDefinition<?> superType = type;
-        while (superType.getBaseType() != null) {
-            superType = superType.getBaseType();
-        }
-        return superType;
+    public static Node<?> toDomNode(final Element xmlElement, final Optional<DataSchemaNode> schema,
+            final Optional<XmlCodecProvider> codecProvider) {
+        return toDomNode(xmlElement, schema, codecProvider, Optional.<SchemaContext>absent());
     }
 
     public static Node<?> toDomNode(final Element xmlElement, final Optional<DataSchemaNode> schema,
-            final Optional<XmlCodecProvider> codecProvider) {
+            final Optional<XmlCodecProvider> codecProvider, final Optional<SchemaContext> schemaContext) {
         if (schema.isPresent()) {
-            return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(DEFAULT_XML_VALUE_CODEC_PROVIDER));
+            if(schemaContext.isPresent()) {
+                return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(XmlUtils.DEFAULT_XML_CODEC_PROVIDER), schemaContext.get());
+            } else {
+                return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(XmlUtils.DEFAULT_XML_CODEC_PROVIDER));
+            }
         }
         return toDomNode(xmlElement);
     }
 
-    public static CompositeNode fromElement(final Element xmlElement) {
-        CompositeNodeBuilder<ImmutableCompositeNode> node = ImmutableCompositeNode.builder();
-        node.setQName(qNameFromElement(xmlElement));
-
-        return node.toInstance();
-    }
-
     public static QName qNameFromElement(final Element xmlElement) {
         String namespace = xmlElement.getNamespaceURI();
         String localName = xmlElement.getLocalName();
@@ -303,10 +229,11 @@ public class XmlDocumentUtils {
         if (codec != null) {
             value = codec.deserialize(text);
         }
+        final TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(schema.getType());
 
-        if (schema.getType() instanceof org.opendaylight.yangtools.yang.model.util.InstanceIdentifier) {
+        if (baseType instanceof org.opendaylight.yangtools.yang.model.util.InstanceIdentifier) {
             value = InstanceIdentifierForXmlCodec.deserialize(xmlElement,schemaCtx);
-        } else if(schema.getType() instanceof IdentityrefTypeDefinition){
+        } else if(baseType instanceof IdentityrefTypeDefinition){
             value = InstanceIdentifierForXmlCodec.toIdentity(xmlElement.getTextContent(), xmlElement, schemaCtx);
         }
 
@@ -357,12 +284,12 @@ public class XmlDocumentUtils {
     }
 
     private static void checkQName(final Element xmlElement, final QName qName) {
-        checkState(Objects.equal(xmlElement.getNamespaceURI(), qName.getNamespace().toString()));
-        checkState(qName.getLocalName().equals(xmlElement.getLocalName()));
+        checkState(Objects.equal(xmlElement.getNamespaceURI(), qName.getNamespace().toString()),  "Not equal: %s to: %s for: %s and: %s", qName.getNamespace(), xmlElement.getNamespaceURI(), qName, xmlElement);
+        checkState(qName.getLocalName().equals(xmlElement.getLocalName()), "Not equal: %s to: %s for: %s and: %s", qName.getLocalName(), xmlElement.getLocalName(), qName, xmlElement);
     }
 
-    public static final Optional<DataSchemaNode> findFirstSchema(final QName qname, final Set<DataSchemaNode> dataSchemaNode) {
-        if (dataSchemaNode != null && !dataSchemaNode.isEmpty() && qname != null) {
+    public static final Optional<DataSchemaNode> findFirstSchema(final QName qname, final Iterable<DataSchemaNode> dataSchemaNode) {
+        if (dataSchemaNode != null && qname != null) {
             for (DataSchemaNode dsn : dataSchemaNode) {
                 if (qname.isEqualWithoutRevision(dsn.getQName())) {
                     return Optional.<DataSchemaNode> of(dsn);
@@ -409,7 +336,7 @@ public class XmlDocumentUtils {
         return ImmutableCompositeNode.create(qname, values.build());
     }
 
-    public static List<Node<?>> toDomNodes(final Element element, final Optional<Set<DataSchemaNode>> context,final SchemaContext schemaCtx) {
+    public static List<Node<?>> toDomNodes(final Element element, final Optional<? extends Iterable<DataSchemaNode>> context, final SchemaContext schemaCtx) {
         return forEachChild(element.getChildNodes(),schemaCtx, new Function<ElementWithSchemaContext, Optional<Node<?>>>() {
 
             @Override
@@ -418,8 +345,8 @@ public class XmlDocumentUtils {
                     QName partialQName = qNameFromElement(input.getElement());
                     Optional<DataSchemaNode> schemaNode = findFirstSchema(partialQName, context.get());
                     if (schemaNode.isPresent()) {
-                        return Optional.<Node<?>> fromNullable(//
-                                toNodeWithSchema(input.getElement(), schemaNode.get(), DEFAULT_XML_VALUE_CODEC_PROVIDER,input.getSchemaContext()));
+                        return Optional.<Node<?>> fromNullable(
+                                toNodeWithSchema(input.getElement(), schemaNode.get(), XmlUtils.DEFAULT_XML_CODEC_PROVIDER, input.getSchemaContext()));
                     }
                 }
                 return Optional.<Node<?>> fromNullable(toDomNode(input.getElement()));
@@ -429,8 +356,8 @@ public class XmlDocumentUtils {
 
     }
 
-    public static List<Node<?>> toDomNodes(final Element element, final Optional<Set<DataSchemaNode>> context) {
-        return toDomNodes(element,context,null);
+    public static List<Node<?>> toDomNodes(final Element element, final Optional<? extends Iterable<DataSchemaNode>> context) {
+        return toDomNodes(element, context, null);
     }
 
     /**
@@ -466,9 +393,9 @@ public class XmlDocumentUtils {
                     final Optional<NotificationDefinition> notificationDef = findNotification(partialQName,
                             notifications.get());
                     if (notificationDef.isPresent()) {
-                        final Set<DataSchemaNode> dataNodes = notificationDef.get().getChildNodes();
+                        final Iterable<DataSchemaNode> dataNodes = notificationDef.get().getChildNodes();
                         final List<Node<?>> domNodes = toDomNodes(childElement,
-                                Optional.<Set<DataSchemaNode>> fromNullable(dataNodes),schemaCtx);
+                                Optional.<Iterable<DataSchemaNode>> fromNullable(dataNodes),schemaCtx);
                         return ImmutableCompositeNode.create(notificationDef.get().getQName(), domNodes);
                     }
                 }
@@ -514,6 +441,6 @@ public class XmlDocumentUtils {
     }
 
     public static final XmlCodecProvider defaultValueCodecProvider() {
-        return DEFAULT_XML_VALUE_CODEC_PROVIDER;
+        return XmlUtils.DEFAULT_XML_CODEC_PROVIDER;
     }
 }