Degrade DataNodeContainer.getChildNodes() from Set to Collection
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / codec / xml / XmlDocumentUtils.java
index 688ecfe068a44bd44c689d2d32b758c4987a99d3..262a48a93385579c74061d497ea11c0abcdcb18a 100644 (file)
@@ -8,10 +8,18 @@
 package org.opendaylight.yangtools.yang.data.impl.codec.xml;
 
 import static com.google.common.base.Preconditions.checkState;
-import static org.opendaylight.yangtools.yang.data.impl.codec.InstanceIdentifierForXmlCodec.INSTANCE_IDENTIFIER_FOR_XML_CODEC;
+
+import com.google.common.base.Function;
+import com.google.common.base.Objects;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableList;
 
 import java.net.URI;
+import java.util.ArrayList;
 import java.util.List;
+import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Set;
 
@@ -19,18 +27,20 @@ import javax.activation.UnsupportedDataTypeException;
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.stream.XMLOutputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
+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;
@@ -44,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;
@@ -52,20 +61,12 @@ import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.NodeList;
 
-import com.google.common.base.Function;
-import com.google.common.base.Objects;
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Strings;
-import com.google.common.collect.ImmutableList;
-
 public class XmlDocumentUtils {
-
     private static class ElementWithSchemaContext {
         Element element;
         SchemaContext schemaContext;
 
-        ElementWithSchemaContext(Element element,SchemaContext schemaContext) {
+        ElementWithSchemaContext(final Element element,final SchemaContext schemaContext) {
             this.schemaContext = schemaContext;
             this.element = element;
         }
@@ -79,15 +80,9 @@ public class XmlDocumentUtils {
         }
     }
 
-    private static final XmlCodecProvider DEFAULT_XML_VALUE_CODEC_PROVIDER = new XmlCodecProvider() {
-
-        @Override
-        public TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codecFor(TypeDefinition<?> baseType) {
-            return TypeDefinitionAwareCodec.from(baseType);
-        }
-    };
-
+    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();
 
     /**
      * Converts Data DOM structure to XML Document for specified XML Codec Provider and corresponding
@@ -101,19 +96,24 @@ public class XmlDocumentUtils {
      * @return new instance of XML Document
      * @throws UnsupportedDataTypeException
      */
-    public static Document toDocument(CompositeNode data, DataNodeContainer schema, XmlCodecProvider codecProvider)
+    public static Document toDocument(final CompositeNode data, final DataNodeContainer schema, final XmlCodecProvider codecProvider)
             throws UnsupportedDataTypeException {
         Preconditions.checkNotNull(data);
         Preconditions.checkNotNull(schema);
 
-        Document doc = getDocument();
+        if (!(schema instanceof ContainerSchemaNode || schema instanceof ListSchemaNode)) {
+            throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
+        }
 
-        if (schema instanceof ContainerSchemaNode || schema instanceof ListSchemaNode) {
-            doc.appendChild(createXmlRootElement(doc, data, (SchemaNode) schema, codecProvider));
-            return doc;
-        } else {
-            throw new UnsupportedDataTypeException(
-                    "Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
+        final DOMResult result = new DOMResult(getDocument());
+        try {
+            final XMLStreamWriter writer = FACTORY.createXMLStreamWriter(result);
+            XmlStreamUtils.create(codecProvider).writeDocument(writer, data, (SchemaNode)schema);
+            writer.close();
+            return (Document)result.getNode();
+        } catch (XMLStreamException e) {
+            logger.error("Failed to serialize data {}", data, e);
+            return null;
         }
     }
 
@@ -139,184 +139,64 @@ public class XmlDocumentUtils {
      * @return new instance of XML Document
      * @throws UnsupportedDataTypeException
      */
-    public static Document toDocument(CompositeNode data, XmlCodecProvider codecProvider)
-            throws UnsupportedDataTypeException {
-        Preconditions.checkNotNull(data);
-
-        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
-        dbf.setNamespaceAware(true);
-        Document doc = null;
+    public static Document toDocument(final CompositeNode data, final XmlCodecProvider codecProvider) {
+        final DOMResult result = new DOMResult(getDocument());
         try {
-            DocumentBuilder bob = dbf.newDocumentBuilder();
-            doc = bob.newDocument();
-        } catch (ParserConfigurationException e) {
+            final XMLStreamWriter writer = FACTORY.createXMLStreamWriter(result);
+            XmlStreamUtils.create(codecProvider).writeDocument(writer, data);
+            writer.close();
+            return (Document)result.getNode();
+        } catch (XMLStreamException e) {
+            logger.error("Failed to serialize data {}", data, e);
             return null;
         }
-
-        doc.appendChild(createXmlRootElement(doc, data, null, codecProvider));
-        return doc;
-    }
-
-    private static Element createXmlRootElement(Document doc, Node<?> data, SchemaNode schema,
-            XmlCodecProvider codecProvider) throws UnsupportedDataTypeException {
-        Element itemEl = createElementFor(doc, data);
-        if (data instanceof SimpleNode<?>) {
-            if (schema instanceof LeafListSchemaNode) {
-                writeValueByType(itemEl, (SimpleNode<?>) data, ((LeafListSchemaNode) schema).getType(),
-                        (DataSchemaNode) schema, codecProvider);
-            } else if (schema instanceof LeafSchemaNode) {
-                writeValueByType(itemEl, (SimpleNode<?>) data, ((LeafSchemaNode) schema).getType(),
-                        (DataSchemaNode) schema, codecProvider);
-            } else {
-                Object value = data.getValue();
-                if (value != null) {
-                    itemEl.setTextContent(String.valueOf(value));
-                }
-            }
-        } else { // CompositeNode
-            for (Node<?> child : ((CompositeNode) data).getChildren()) {
-                DataSchemaNode childSchema = null;
-                if (schema != null) {
-                    childSchema = findFirstSchemaForNode(child, ((DataNodeContainer) schema).getChildNodes());
-                    if (logger.isDebugEnabled()) {
-                        if (childSchema == null) {
-                            logger.debug("Probably the data node \""
-                                    + ((child == null) ? "" : child.getNodeType().getLocalName())
-                                    + "\" is not conform to schema");
-                        }
-                    }
-                }
-                itemEl.appendChild(createXmlRootElement(doc, child, childSchema, codecProvider));
-            }
-        }
-        return itemEl;
     }
 
-    public static Element createElementFor(Document doc, Node<?> data) {
-        QName dataType = data.getNodeType();
-        Element ret;
-        if (dataType.getNamespace() != null) {
-            ret = doc.createElementNS(dataType.getNamespace().toString(), dataType.getLocalName());
+    private static final Element createElementFor(final Document doc, final QName qname, final Object obj) {
+        final Element ret;
+        if (qname.getNamespace() != null) {
+            ret = doc.createElementNS(qname.getNamespace().toString(), qname.getLocalName());
         } else {
-            ret = doc.createElementNS(null, dataType.getLocalName());
-        }
-        if (data instanceof AttributesContainer && ((AttributesContainer) data).getAttributes() != null) {
-            for (Entry<QName, String> attribute : ((AttributesContainer) data).getAttributes().entrySet()) {
-                ret.setAttributeNS(attribute.getKey().getNamespace().toString(), attribute.getKey().getLocalName(),
-                        attribute.getValue());
-            }
-
+            ret = doc.createElementNS(null, qname.getLocalName());
         }
-        return ret;
-    }
 
-    public static void writeValueByType(Element element, SimpleNode<?> node, TypeDefinition<?> type,
-            DataSchemaNode schema, XmlCodecProvider codecProvider) {
+        if (obj instanceof AttributesContainer) {
+            final Map<QName, String> attrs = ((AttributesContainer)obj).getAttributes();
 
-        Object nodeValue = node.getValue();
-
-        writeValueByType(element, type, codecProvider, nodeValue);
-    }
-
-    public static void writeValueByType(Element element, TypeDefinition<?> type, XmlCodecProvider codecProvider, 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) {
-                INSTANCE_IDENTIFIER_FOR_XML_CODEC.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));
+            if (attrs != null) {
+                for (Entry<QName, String> attribute : attrs.entrySet()) {
+                    ret.setAttributeNS(attribute.getKey().getNamespace().toString(), attribute.getKey().getLocalName(),
+                            attribute.getValue());
                 }
             }
         }
-    }
 
+        return ret;
+    }
 
-    public final static TypeDefinition<?> resolveBaseTypeFrom(TypeDefinition<?> type) {
-        TypeDefinition<?> superType = type;
-        while (superType.getBaseType() != null) {
-            superType = superType.getBaseType();
-        }
-        return superType;
+    public static Element createElementFor(final Document doc, final Node<?> data) {
+        return createElementFor(doc, data.getNodeType(), data);
     }
 
-    private static final DataSchemaNode findFirstSchemaForNode(Node<?> node, Set<DataSchemaNode> dataSchemaNode) {
-        if (dataSchemaNode != null && node != null) {
-            for (DataSchemaNode dsn : dataSchemaNode) {
-                if (node.getNodeType().getLocalName().equals(dsn.getQName().getLocalName())) {
-                    return dsn;
-                } else if (dsn instanceof ChoiceNode) {
-                    for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
-                        DataSchemaNode foundDsn = findFirstSchemaForNode(node, choiceCase.getChildNodes());
-                        if (foundDsn != null) {
-                            return foundDsn;
-                        }
-                    }
-                }
-            }
-        }
-        return null;
+    public static Element createElementFor(final Document doc, final NormalizedNode<?, ?> data) {
+        return createElementFor(doc, data.getNodeType(), data);
     }
 
-    public static Node<?> toDomNode(Element xmlElement, Optional<DataSchemaNode> schema,
-            Optional<XmlCodecProvider> codecProvider) {
+    public static Node<?> toDomNode(final Element xmlElement, final Optional<DataSchemaNode> schema,
+            final Optional<XmlCodecProvider> codecProvider) {
         if (schema.isPresent()) {
-            return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(DEFAULT_XML_VALUE_CODEC_PROVIDER));
+            return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(XmlUtils.DEFAULT_XML_CODEC_PROVIDER));
         }
         return toDomNode(xmlElement);
     }
 
-    public static CompositeNode fromElement(Element xmlElement) {
-        CompositeNodeBuilder<ImmutableCompositeNode> node = ImmutableCompositeNode.builder();
-        node.setQName(qNameFromElement(xmlElement));
-
-        return node.toInstance();
-    }
-
-    public static QName qNameFromElement(Element xmlElement) {
+    public static QName qNameFromElement(final Element xmlElement) {
         String namespace = xmlElement.getNamespaceURI();
         String localName = xmlElement.getLocalName();
         return QName.create(namespace != null ? URI.create(namespace) : null, null, localName);
     }
 
-    private static Node<?> toNodeWithSchema(Element xmlElement, DataSchemaNode schema, XmlCodecProvider codecProvider,SchemaContext schemaCtx) {
+    private static Node<?> toNodeWithSchema(final Element xmlElement, final DataSchemaNode schema, final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
         checkQName(xmlElement, schema.getQName());
         if (schema instanceof DataNodeContainer) {
             return toCompositeNodeWithSchema(xmlElement, schema.getQName(), (DataNodeContainer) schema, codecProvider,schemaCtx);
@@ -328,21 +208,25 @@ public class XmlDocumentUtils {
         return null;
     }
 
-    private static Node<?> toNodeWithSchema(Element xmlElement, DataSchemaNode schema, XmlCodecProvider codecProvider) {
+    private static Node<?> toNodeWithSchema(final Element xmlElement, final DataSchemaNode schema, final XmlCodecProvider codecProvider) {
         return toNodeWithSchema(xmlElement, schema, codecProvider, null);
     }
 
-    private static Node<?> toSimpleNodeWithType(Element xmlElement, LeafSchemaNode schema,
-            XmlCodecProvider codecProvider,SchemaContext schemaCtx) {
+    protected static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafSchemaNode schema,
+            final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
         TypeDefinitionAwareCodec<? extends Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
         String text = xmlElement.getTextContent();
         Object value = null;
         if (codec != null) {
             value = codec.deserialize(text);
         }
+
         if (schema.getType() instanceof org.opendaylight.yangtools.yang.model.util.InstanceIdentifier) {
-            value = INSTANCE_IDENTIFIER_FOR_XML_CODEC.deserialize(xmlElement,schemaCtx);
+            value = InstanceIdentifierForXmlCodec.deserialize(xmlElement,schemaCtx);
+        } else if(schema.getType() instanceof IdentityrefTypeDefinition){
+            value = InstanceIdentifierForXmlCodec.toIdentity(xmlElement.getTextContent(), xmlElement, schemaCtx);
         }
+
         if (value == null) {
             value = xmlElement.getTextContent();
         }
@@ -351,8 +235,8 @@ public class XmlDocumentUtils {
         return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
     }
 
-    private static Node<?> toSimpleNodeWithType(Element xmlElement, LeafListSchemaNode schema,
-            XmlCodecProvider codecProvider,SchemaContext schemaCtx) {
+    private static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafListSchemaNode schema,
+            final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
         TypeDefinitionAwareCodec<? extends Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
         String text = xmlElement.getTextContent();
         Object value = null;
@@ -360,7 +244,7 @@ public class XmlDocumentUtils {
             value = codec.deserialize(text);
         }
         if (schema.getType() instanceof org.opendaylight.yangtools.yang.model.util.InstanceIdentifier) {
-            value = INSTANCE_IDENTIFIER_FOR_XML_CODEC.deserialize(xmlElement,schemaCtx);
+            value = InstanceIdentifierForXmlCodec.deserialize(xmlElement,schemaCtx);
         }
         if (value == null) {
             value = xmlElement.getTextContent();
@@ -370,19 +254,18 @@ public class XmlDocumentUtils {
         return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
     }
 
-    private static Node<?> toCompositeNodeWithSchema(Element xmlElement, QName qName, DataNodeContainer schema,
-            XmlCodecProvider codecProvider,SchemaContext schemaCtx) {
+    private static Node<?> toCompositeNodeWithSchema(final Element xmlElement, final QName qName, final DataNodeContainer schema,
+            final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
         List<Node<?>> values = toDomNodes(xmlElement, Optional.fromNullable(schema.getChildNodes()),schemaCtx);
         Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
         return ImmutableCompositeNode.create(qName, values, modifyAction.orNull());
     }
 
-    public static final QName OPERATION_ATTRIBUTE_QNAME = QName.create(URI.create("urn:ietf:params:xml:ns:netconf:base:1.0"), null, "operation");
-
-    public static Optional<ModifyAction> getModifyOperationFromAttributes(Element xmlElement) {
+    public static Optional<ModifyAction> getModifyOperationFromAttributes(final Element xmlElement) {
         Attr attributeNodeNS = xmlElement.getAttributeNodeNS(OPERATION_ATTRIBUTE_QNAME.getNamespace().toString(), OPERATION_ATTRIBUTE_QNAME.getLocalName());
-        if(attributeNodeNS == null)
+        if(attributeNodeNS == null) {
             return Optional.absent();
+        }
 
         ModifyAction action = ModifyAction.fromXmlValue(attributeNodeNS.getValue());
         Preconditions.checkArgument(action.isOnElementPermitted(), "Unexpected operation %s on %s", action, xmlElement);
@@ -390,13 +273,13 @@ public class XmlDocumentUtils {
         return Optional.of(action);
     }
 
-    private static void checkQName(Element xmlElement, QName qName) {
+    private static void checkQName(final Element xmlElement, final QName qName) {
         checkState(Objects.equal(xmlElement.getNamespaceURI(), qName.getNamespace().toString()));
         checkState(qName.getLocalName().equals(xmlElement.getLocalName()));
     }
 
-    public static final Optional<DataSchemaNode> findFirstSchema(QName qname, 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);
@@ -413,11 +296,11 @@ public class XmlDocumentUtils {
         return Optional.absent();
     }
 
-    public static Node<?> toDomNode(Document doc) {
+    public static Node<?> toDomNode(final Document doc) {
         return toDomNode(doc.getDocumentElement());
     }
 
-    private static Node<?> toDomNode(Element element) {
+    private static Node<?> toDomNode(final Element element) {
         QName qname = qNameFromElement(element);
 
         ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
@@ -443,17 +326,17 @@ public class XmlDocumentUtils {
         return ImmutableCompositeNode.create(qname, values.build());
     }
 
-    public static List<Node<?>> toDomNodes(final Element element, final Optional<Set<DataSchemaNode>> context,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
-            public Optional<Node<?>> apply(ElementWithSchemaContext input) {
+            public Optional<Node<?>> apply(final ElementWithSchemaContext input) {
                 if (context.isPresent()) {
                     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()));
@@ -463,8 +346,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);
     }
 
     /**
@@ -489,7 +372,7 @@ public class XmlDocumentUtils {
      *         Element with equal notification QName defined in XML Document.
      */
     public static CompositeNode notificationToDomNodes(final Document document,
-            final Optional<Set<NotificationDefinition>> notifications, SchemaContext schemaCtx) {
+            final Optional<Set<NotificationDefinition>> notifications, final SchemaContext schemaCtx) {
         if (notifications.isPresent() && (document != null) && (document.getDocumentElement() != null)) {
             final NodeList originChildNodes = document.getDocumentElement().getChildNodes();
             for (int i = 0; i < originChildNodes.getLength(); i++) {
@@ -500,9 +383,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);
                     }
                 }
@@ -528,21 +411,26 @@ public class XmlDocumentUtils {
         return Optional.<NotificationDefinition>absent();
     }
 
-    private static final <T> List<T> forEachChild(NodeList nodes, SchemaContext schemaContext, Function<ElementWithSchemaContext, Optional<T>> forBody) {
-        ImmutableList.Builder<T> ret = ImmutableList.<T> builder();
-        for (int i = 0; i < nodes.getLength(); i++) {
+    private static final <T> List<T> forEachChild(final NodeList nodes, final SchemaContext schemaContext, final Function<ElementWithSchemaContext, Optional<T>> forBody) {
+        final int l = nodes.getLength();
+        if (l == 0) {
+            return ImmutableList.of();
+        }
+
+        final List<T> list = new ArrayList<>(l);
+        for (int i = 0; i < l; i++) {
             org.w3c.dom.Node child = nodes.item(i);
             if (child instanceof Element) {
                 Optional<T> result = forBody.apply(new ElementWithSchemaContext((Element) child,schemaContext));
                 if (result.isPresent()) {
-                    ret.add(result.get());
+                    list.add(result.get());
                 }
             }
         }
-        return ret.build();
+        return ImmutableList.copyOf(list);
     }
 
     public static final XmlCodecProvider defaultValueCodecProvider() {
-        return DEFAULT_XML_VALUE_CODEC_PROVIDER;
+        return XmlUtils.DEFAULT_XML_CODEC_PROVIDER;
     }
 }