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