Abstract infrastructure for normalized nodes translation.
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / codec / xml / XmlDocumentUtils.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.data.impl.codec.xml;
9
10 import static com.google.common.base.Preconditions.checkState;
11
12 import java.net.URI;
13 import java.util.Collection;
14 import java.util.HashMap;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.Map.Entry;
18 import java.util.Random;
19 import java.util.Set;
20
21 import javax.activation.UnsupportedDataTypeException;
22 import javax.xml.parsers.DocumentBuilder;
23 import javax.xml.parsers.DocumentBuilderFactory;
24 import javax.xml.parsers.ParserConfigurationException;
25
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
28 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
29 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
31 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeWithValue;
32 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
33 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
34 import org.opendaylight.yangtools.yang.data.api.Node;
35 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
36 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
37 import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
38 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
39 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
40 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
41 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
42 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
44 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
49 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
51 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
52 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.w3c.dom.Attr;
56 import org.w3c.dom.Document;
57 import org.w3c.dom.Element;
58 import org.w3c.dom.NodeList;
59
60 import com.google.common.base.Function;
61 import com.google.common.base.Objects;
62 import com.google.common.base.Optional;
63 import com.google.common.base.Preconditions;
64 import com.google.common.base.Strings;
65 import com.google.common.collect.ImmutableList;
66
67 public class XmlDocumentUtils {
68
69     private static final XmlCodecProvider DEFAULT_XML_VALUE_CODEC_PROVIDER = new XmlCodecProvider() {
70
71         @Override
72         public TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codecFor(TypeDefinition<?> baseType) {
73             return TypeDefinitionAwareCodec.from(baseType);
74         }
75     };
76
77     private static final Logger logger = LoggerFactory.getLogger(XmlDocumentUtils.class);
78
79     /**
80      * Converts Data DOM structure to XML Document for specified XML Codec Provider and corresponding
81      * Data Node Container schema. The CompositeNode data parameter enters as root of Data DOM tree and will
82      * be transformed to root in XML Document. Each element of Data DOM tree is compared against specified Data
83      * Node Container Schema and transformed accordingly.
84      *
85      * @param data Data DOM root element
86      * @param schema Data Node Container Schema
87      * @param codecProvider XML Codec Provider
88      * @return new instance of XML Document
89      * @throws UnsupportedDataTypeException
90      */
91     public static Document toDocument(CompositeNode data, DataNodeContainer schema, XmlCodecProvider codecProvider)
92             throws UnsupportedDataTypeException {
93         Preconditions.checkNotNull(data);
94         Preconditions.checkNotNull(schema);
95
96         Document doc = getDocument();
97
98         if (schema instanceof ContainerSchemaNode || schema instanceof ListSchemaNode) {
99             doc.appendChild(createXmlRootElement(doc, data, (SchemaNode) schema, codecProvider));
100             return doc;
101         } else {
102             throw new UnsupportedDataTypeException(
103                     "Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
104         }
105     }
106
107     public static Document getDocument() {
108         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
109         Document doc = null;
110         try {
111             DocumentBuilder bob = dbf.newDocumentBuilder();
112             doc = bob.newDocument();
113         } catch (ParserConfigurationException e) {
114             throw new RuntimeException(e);
115         }
116         return doc;
117     }
118
119     /**
120      * Converts Data DOM structure to XML Document for specified XML Codec Provider. The CompositeNode
121      * data parameter enters as root of Data DOM tree and will be transformed to root in XML Document. The child
122      * nodes of Data Tree are transformed accordingly.
123      *
124      * @param data Data DOM root element
125      * @param codecProvider XML Codec Provider
126      * @return new instance of XML Document
127      * @throws UnsupportedDataTypeException
128      */
129     public static Document toDocument(CompositeNode data, XmlCodecProvider codecProvider)
130             throws UnsupportedDataTypeException {
131         Preconditions.checkNotNull(data);
132
133         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
134         dbf.setNamespaceAware(true);
135         Document doc = null;
136         try {
137             DocumentBuilder bob = dbf.newDocumentBuilder();
138             doc = bob.newDocument();
139         } catch (ParserConfigurationException e) {
140             return null;
141         }
142
143         doc.appendChild(createXmlRootElement(doc, data, null, codecProvider));
144         return doc;
145     }
146
147     private static Element createXmlRootElement(Document doc, Node<?> data, SchemaNode schema,
148             XmlCodecProvider codecProvider) throws UnsupportedDataTypeException {
149         Element itemEl = createElementFor(doc, data);
150         if (data instanceof SimpleNode<?>) {
151             if (schema instanceof LeafListSchemaNode) {
152                 writeValueByType(itemEl, (SimpleNode<?>) data, ((LeafListSchemaNode) schema).getType(),
153                         (DataSchemaNode) schema, codecProvider);
154             } else if (schema instanceof LeafSchemaNode) {
155                 writeValueByType(itemEl, (SimpleNode<?>) data, ((LeafSchemaNode) schema).getType(),
156                         (DataSchemaNode) schema, codecProvider);
157             } else {
158                 Object value = data.getValue();
159                 if (value != null) {
160                     itemEl.setTextContent(String.valueOf(value));
161                 }
162             }
163         } else { // CompositeNode
164             for (Node<?> child : ((CompositeNode) data).getChildren()) {
165                 DataSchemaNode childSchema = null;
166                 if (schema != null) {
167                     childSchema = findFirstSchemaForNode(child, ((DataNodeContainer) schema).getChildNodes());
168                     if (logger.isDebugEnabled()) {
169                         if (childSchema == null) {
170                             logger.debug("Probably the data node \""
171                                     + ((child == null) ? "" : child.getNodeType().getLocalName())
172                                     + "\" is not conform to schema");
173                         }
174                     }
175                 }
176                 itemEl.appendChild(createXmlRootElement(doc, child, childSchema, codecProvider));
177             }
178         }
179         return itemEl;
180     }
181
182     public static Element createElementFor(Document doc, Node<?> data) {
183         QName dataType = data.getNodeType();
184         Element ret;
185         if (dataType.getNamespace() != null) {
186             ret = doc.createElementNS(dataType.getNamespace().toString(), dataType.getLocalName());
187         } else {
188             ret = doc.createElementNS(null, dataType.getLocalName());
189         }
190         if (data instanceof AttributesContainer && ((AttributesContainer) data).getAttributes() != null) {
191             for (Entry<QName, String> attribute : ((AttributesContainer) data).getAttributes().entrySet()) {
192                 ret.setAttributeNS(attribute.getKey().getNamespace().toString(), attribute.getKey().getLocalName(),
193                         attribute.getValue());
194             }
195
196         }
197         return ret;
198     }
199
200     public static void writeValueByType(Element element, SimpleNode<?> node, TypeDefinition<?> type,
201             DataSchemaNode schema, XmlCodecProvider codecProvider) {
202
203         Object nodeValue = node.getValue();
204
205         writeValueByType(element, type, codecProvider, nodeValue);
206     }
207
208     public static void writeValueByType(Element element, TypeDefinition<?> type, XmlCodecProvider codecProvider, Object nodeValue) {
209         TypeDefinition<?> baseType = resolveBaseTypeFrom(type);
210         if (baseType instanceof IdentityrefTypeDefinition) {
211             if (nodeValue instanceof QName) {
212                 QName value = (QName) nodeValue;
213                 String prefix = "x";
214                 if (value.getPrefix() != null && !value.getPrefix().isEmpty()) {
215                     prefix = value.getPrefix();
216                 }
217                 element.setAttribute("xmlns:" + prefix, value.getNamespace().toString());
218                 element.setTextContent(prefix + ":" + value.getLocalName());
219             } else {
220                 Object value = nodeValue;
221                 logger.debug("Value of {}:{} is not instance of QName but is {}", baseType.getQName().getNamespace(),
222                         baseType.getQName().getLocalName(), value != null ? value.getClass() : "null");
223                 if (value != null) {
224                     element.setTextContent(String.valueOf(value));
225                 }
226             }
227         } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
228             if (nodeValue instanceof InstanceIdentifier) {
229                 // Map< key = namespace, value = prefix>
230                 Map<String, String> prefixes = new HashMap<>();
231                 InstanceIdentifier instanceIdentifier = (InstanceIdentifier) nodeValue;
232                 StringBuilder textContent = new StringBuilder();
233                 for (PathArgument pathArgument : instanceIdentifier.getPath()) {
234                     textContent.append("/");
235                     writeIdentifierWithNamespacePrefix(element, textContent, pathArgument.getNodeType(), prefixes);
236                     if (pathArgument instanceof NodeIdentifierWithPredicates) {
237                         Map<QName, Object> predicates = ((NodeIdentifierWithPredicates) pathArgument).getKeyValues();
238
239                         for (QName keyValue : predicates.keySet()) {
240                             String predicateValue = String.valueOf(predicates.get(keyValue));
241                             textContent.append("[");
242                             writeIdentifierWithNamespacePrefix(element, textContent, keyValue, prefixes);
243                             textContent.append("='");
244                             textContent.append(predicateValue);
245                             textContent.append("'");
246                             textContent.append("]");
247                         }
248                     } else if (pathArgument instanceof NodeWithValue) {
249                         textContent.append("[.='");
250                         textContent.append(((NodeWithValue)pathArgument).getValue());
251                         textContent.append("'");
252                         textContent.append("]");
253                     }
254                 }
255                 element.setTextContent(textContent.toString());
256
257             } else {
258                 Object value = nodeValue;
259                 logger.debug("Value of {}:{} is not instance of InstanceIdentifier but is {}", baseType.getQName()
260                         .getNamespace(), //
261                         baseType.getQName().getLocalName(), value != null ? value.getClass() : "null");
262                 if (value != null) {
263                     element.setTextContent(String.valueOf(value));
264                 }
265             }
266         } else {
267             if (nodeValue != null) {
268                 final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
269                 if (codec != null) {
270                     try {
271                         final String text = codec.serialize(nodeValue);
272                         element.setTextContent(text);
273                     } catch (ClassCastException e) {
274                         logger.error("Provided node value {} did not have type {} required by mapping. Using stream instead.", nodeValue, baseType, e);
275                         element.setTextContent(String.valueOf(nodeValue));
276                     }
277                 } else {
278                     logger.error("Failed to find codec for {}, falling back to using stream", baseType);
279                     element.setTextContent(String.valueOf(nodeValue));
280                 }
281             }
282         }
283     }
284
285     private static void writeIdentifierWithNamespacePrefix(Element element, StringBuilder textContent, QName qName,
286             Map<String, String> prefixes) {
287         String namespace = qName.getNamespace().toString();
288         String prefix = prefixes.get(namespace);
289         if (prefix == null) {
290             prefix = qName.getPrefix();
291             if (prefix == null || prefix.isEmpty() || prefixes.containsValue(prefix)) {
292                 prefix = generateNewPrefix(prefixes.values());
293             }
294         }
295
296         element.setAttribute("xmlns:" + prefix, namespace.toString());
297         textContent.append(prefix);
298         prefixes.put(namespace, prefix);
299
300         textContent.append(":");
301         textContent.append(qName.getLocalName());
302     }
303
304     private static String generateNewPrefix(Collection<String> prefixes) {
305         StringBuilder result = null;
306         Random random = new Random();
307         do {
308             result = new StringBuilder();
309             for (int i = 0; i < 4; i++) {
310                 int randomNumber = 0x61 + (Math.abs(random.nextInt()) % 26);
311                 result.append(Character.toChars(randomNumber));
312             }
313         } while (prefixes.contains(result.toString()));
314
315         return result.toString();
316     }
317
318     public final static TypeDefinition<?> resolveBaseTypeFrom(TypeDefinition<?> type) {
319         TypeDefinition<?> superType = type;
320         while (superType.getBaseType() != null) {
321             superType = superType.getBaseType();
322         }
323         return superType;
324     }
325
326     private static final DataSchemaNode findFirstSchemaForNode(Node<?> node, Set<DataSchemaNode> dataSchemaNode) {
327         if (dataSchemaNode != null && node != null) {
328             for (DataSchemaNode dsn : dataSchemaNode) {
329                 if (node.getNodeType().getLocalName().equals(dsn.getQName().getLocalName())) {
330                     return dsn;
331                 } else if (dsn instanceof ChoiceNode) {
332                     for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
333                         DataSchemaNode foundDsn = findFirstSchemaForNode(node, choiceCase.getChildNodes());
334                         if (foundDsn != null) {
335                             return foundDsn;
336                         }
337                     }
338                 }
339             }
340         }
341         return null;
342     }
343
344     public static Node<?> toDomNode(Element xmlElement, Optional<DataSchemaNode> schema,
345             Optional<XmlCodecProvider> codecProvider) {
346         if (schema.isPresent()) {
347             return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(DEFAULT_XML_VALUE_CODEC_PROVIDER));
348         }
349         return toDomNode(xmlElement);
350     }
351
352     public static CompositeNode fromElement(Element xmlElement) {
353         CompositeNodeBuilder<ImmutableCompositeNode> node = ImmutableCompositeNode.builder();
354         node.setQName(qNameFromElement(xmlElement));
355
356         return node.toInstance();
357     }
358
359     public static QName qNameFromElement(Element xmlElement) {
360         String namespace = xmlElement.getNamespaceURI();
361         String localName = xmlElement.getLocalName();
362         return QName.create(namespace != null ? URI.create(namespace) : null, null, localName);
363     }
364
365     private static Node<?> toNodeWithSchema(Element xmlElement, DataSchemaNode schema, XmlCodecProvider codecProvider) {
366         checkQName(xmlElement, schema.getQName());
367         if (schema instanceof DataNodeContainer) {
368             return toCompositeNodeWithSchema(xmlElement, schema.getQName(), (DataNodeContainer) schema, codecProvider);
369         } else if (schema instanceof LeafSchemaNode) {
370             return toSimpleNodeWithType(xmlElement, (LeafSchemaNode) schema, codecProvider);
371         } else if (schema instanceof LeafListSchemaNode) {
372             return toSimpleNodeWithType(xmlElement, (LeafListSchemaNode) schema, codecProvider);
373
374         }
375         return null;
376     }
377
378     private static Node<?> toSimpleNodeWithType(Element xmlElement, LeafSchemaNode schema,
379             XmlCodecProvider codecProvider) {
380         TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
381         String text = xmlElement.getTextContent();
382         Object value;
383         if (codec != null) {
384             value = codec.deserialize(text);
385
386         } else {
387             value = xmlElement.getTextContent();
388         }
389
390         Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
391         return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
392     }
393
394     private static Node<?> toSimpleNodeWithType(Element xmlElement, LeafListSchemaNode schema,
395             XmlCodecProvider codecProvider) {
396         TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
397         String text = xmlElement.getTextContent();
398         Object value;
399         if (codec != null) {
400             value = codec.deserialize(text);
401
402         } else {
403             value = xmlElement.getTextContent();
404         }
405
406         Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
407         return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
408     }
409
410     private static Node<?> toCompositeNodeWithSchema(Element xmlElement, QName qName, DataNodeContainer schema,
411             XmlCodecProvider codecProvider) {
412         List<Node<?>> values = toDomNodes(xmlElement, Optional.fromNullable(schema.getChildNodes()));
413         Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
414         return ImmutableCompositeNode.create(qName, values, modifyAction.orNull());
415     }
416
417     public static final QName OPERATION_ATTRIBUTE_QNAME = QName.create(URI.create("urn:ietf:params:xml:ns:netconf:base:1.0"), null, "operation");
418
419     public static Optional<ModifyAction> getModifyOperationFromAttributes(Element xmlElement) {
420         Attr attributeNodeNS = xmlElement.getAttributeNodeNS(OPERATION_ATTRIBUTE_QNAME.getNamespace().toString(), OPERATION_ATTRIBUTE_QNAME.getLocalName());
421         if(attributeNodeNS == null)
422             return Optional.absent();
423
424         ModifyAction action = ModifyAction.fromXmlValue(attributeNodeNS.getValue());
425         Preconditions.checkArgument(action.isOnElementPermitted(), "Unexpected operation %s on %s", action, xmlElement);
426
427         return Optional.of(action);
428     }
429
430     private static void checkQName(Element xmlElement, QName qName) {
431         checkState(Objects.equal(xmlElement.getNamespaceURI(), qName.getNamespace().toString()));
432         checkState(qName.getLocalName().equals(xmlElement.getLocalName()));
433     }
434
435     public static final Optional<DataSchemaNode> findFirstSchema(QName qname, Set<DataSchemaNode> dataSchemaNode) {
436         if (dataSchemaNode != null && !dataSchemaNode.isEmpty() && qname != null) {
437             for (DataSchemaNode dsn : dataSchemaNode) {
438                 if (qname.isEqualWithoutRevision(dsn.getQName())) {
439                     return Optional.<DataSchemaNode> of(dsn);
440                 } else if (dsn instanceof ChoiceNode) {
441                     for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
442                         Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
443                         if (foundDsn != null && foundDsn.isPresent()) {
444                             return foundDsn;
445                         }
446                     }
447                 }
448             }
449         }
450         return Optional.absent();
451     }
452
453     public static Node<?> toDomNode(Document doc) {
454         return toDomNode(doc.getDocumentElement());
455     }
456
457     private static Node<?> toDomNode(Element element) {
458         QName qname = qNameFromElement(element);
459
460         ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
461         NodeList nodes = element.getChildNodes();
462         boolean isSimpleObject = true;
463         String value = null;
464         for (int i = 0; i < nodes.getLength(); i++) {
465             org.w3c.dom.Node child = nodes.item(i);
466             if (child instanceof Element) {
467                 isSimpleObject = false;
468                 values.add(toDomNode((Element) child));
469             }
470             if (isSimpleObject && child instanceof org.w3c.dom.Text) {
471                 value = element.getTextContent();
472                 if (!Strings.isNullOrEmpty(value)) {
473                     isSimpleObject = true;
474                 }
475             }
476         }
477         if (isSimpleObject) {
478             return new SimpleNodeTOImpl<>(qname, null, value);
479         }
480         return ImmutableCompositeNode.create(qname, values.build());
481     }
482
483     public static List<Node<?>> toDomNodes(final Element element, final Optional<Set<DataSchemaNode>> context) {
484         return forEachChild(element.getChildNodes(), new Function<Element, Optional<Node<?>>>() {
485
486             @Override
487             public Optional<Node<?>> apply(Element input) {
488                 if (context.isPresent()) {
489                     QName partialQName = qNameFromElement(input);
490                     Optional<DataSchemaNode> schemaNode = findFirstSchema(partialQName, context.get());
491                     if (schemaNode.isPresent()) {
492                         return Optional.<Node<?>> fromNullable(//
493                                 toNodeWithSchema(input, schemaNode.get(), DEFAULT_XML_VALUE_CODEC_PROVIDER));
494                     }
495                 }
496                 return Optional.<Node<?>> fromNullable(toDomNode(input));
497             }
498
499         });
500
501     }
502
503     /**
504      * Converts XML Document containing notification data from Netconf device to
505      * Data DOM Nodes. <br>
506      * By specification defined in <a
507      * href="http://tools.ietf.org/search/rfc6020#section-7.14">RFC 6020</a>
508      * there are xml elements containing notifications metadata, like eventTime
509      * or root notification element which specifies namespace for which is
510      * notification defined in yang model. Those elements MUST be stripped off
511      * notifications body. This method returns pure notification body which
512      * begins in element which is equal to notifications name defined in
513      * corresponding yang model. Rest of notification metadata are obfuscated,
514      * thus Data DOM contains only pure notification body.
515      *
516      * @param document
517      *            XML Document containing notification body
518      * @param notifications
519      *            Notifications Definition Schema
520      * @return Data DOM Nodes containing xml notification body definition or
521      *         <code>null</code> if there is no NotificationDefinition with
522      *         Element with equal notification QName defined in XML Document.
523      */
524     public static CompositeNode notificationToDomNodes(final Document document,
525             final Optional<Set<NotificationDefinition>> notifications) {
526         if (notifications.isPresent() && (document != null) && (document.getDocumentElement() != null)) {
527             final NodeList originChildNodes = document.getDocumentElement().getChildNodes();
528
529             for (int i = 0; i < originChildNodes.getLength(); i++) {
530                 org.w3c.dom.Node child = originChildNodes.item(i);
531                 if (child instanceof Element) {
532                     final Element childElement = (Element) child;
533                     final QName partialQName = qNameFromElement(childElement);
534                     final Optional<NotificationDefinition> notificationDef = findNotification(partialQName,
535                             notifications.get());
536                     if (notificationDef.isPresent()) {
537                         final Set<DataSchemaNode> dataNodes = notificationDef.get().getChildNodes();
538                         final List<Node<?>> domNodes = toDomNodes(childElement,
539                                 Optional.<Set<DataSchemaNode>> fromNullable(dataNodes));
540                         return ImmutableCompositeNode.create(notificationDef.get().getQName(), domNodes);
541                     }
542                 }
543             }
544         }
545         return null;
546     }
547
548     private static Optional<NotificationDefinition> findNotification(final QName notifName,
549             final Set<NotificationDefinition> notifications) {
550         if ((notifName != null) && (notifications != null)) {
551             for (final NotificationDefinition notification : notifications) {
552                 if ((notification != null) && notifName.isEqualWithoutRevision(notification.getQName())) {
553                     return Optional.<NotificationDefinition>fromNullable(notification);
554                 }
555             }
556         }
557         return Optional.<NotificationDefinition>absent();
558     }
559
560     private static final <T> List<T> forEachChild(NodeList nodes, Function<Element, Optional<T>> forBody) {
561         ImmutableList.Builder<T> ret = ImmutableList.<T> builder();
562         for (int i = 0; i < nodes.getLength(); i++) {
563             org.w3c.dom.Node child = nodes.item(i);
564             if (child instanceof Element) {
565                 Optional<T> result = forBody.apply((Element) child);
566                 if (result.isPresent()) {
567                     ret.add(result.get());
568                 }
569             }
570         }
571         return ret.build();
572     }
573
574     public static final XmlCodecProvider defaultValueCodecProvider() {
575         return DEFAULT_XML_VALUE_CODEC_PROVIDER;
576     }
577
578 }