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