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