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