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