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