Merge "Fixed bug in resolving config statement for nodes from uses."
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / codec / xml / XmlDocumentUtils.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.data.impl.codec.xml;
9
10 import static com.google.common.base.Preconditions.checkState;
11
12 import java.net.URI;
13 import java.util.Collection;
14 import java.util.HashMap;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.Map.Entry;
18 import java.util.Random;
19 import java.util.Set;
20
21 import javax.activation.UnsupportedDataTypeException;
22 import javax.xml.parsers.DocumentBuilder;
23 import javax.xml.parsers.DocumentBuilderFactory;
24 import javax.xml.parsers.ParserConfigurationException;
25
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
28 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
29 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
31 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
32 import org.opendaylight.yangtools.yang.data.api.Node;
33 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
34 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
35 import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
36 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
37 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
38 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
39 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
40 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
42 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
47 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
49 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
50 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.w3c.dom.Document;
54 import org.w3c.dom.Element;
55 import org.w3c.dom.NodeList;
56
57 import com.google.common.base.Function;
58 import com.google.common.base.Objects;
59 import com.google.common.base.Optional;
60 import com.google.common.base.Preconditions;
61 import com.google.common.base.Strings;
62 import com.google.common.collect.ImmutableList;
63
64 public class XmlDocumentUtils {
65
66     private static final XmlCodecProvider DEFAULT_XML_VALUE_CODEC_PROVIDER = new XmlCodecProvider() {
67
68         @Override
69         public TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codecFor(TypeDefinition<?> baseType) {
70             return TypeDefinitionAwareCodec.from(baseType);
71         }
72     };
73
74     private static final Logger logger = LoggerFactory.getLogger(XmlDocumentUtils.class);
75
76     public static Document toDocument(CompositeNode data, DataNodeContainer schema, XmlCodecProvider codecProvider)
77             throws UnsupportedDataTypeException {
78         Preconditions.checkNotNull(data);
79         Preconditions.checkNotNull(schema);
80
81         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
82         Document doc = null;
83         try {
84             DocumentBuilder bob = dbf.newDocumentBuilder();
85             doc = bob.newDocument();
86         } catch (ParserConfigurationException e) {
87             return null;
88         }
89
90         if (schema instanceof ContainerSchemaNode || schema instanceof ListSchemaNode) {
91             doc.appendChild(createXmlRootElement(doc, data, (SchemaNode) schema, codecProvider));
92             return doc;
93         } else {
94             throw new UnsupportedDataTypeException(
95                     "Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
96         }
97     }
98
99     private static Element createXmlRootElement(Document doc, Node<?> data, SchemaNode schema,
100             XmlCodecProvider codecProvider) throws UnsupportedDataTypeException {
101         Element itemEl = createElementFor(doc, data);
102         if (data instanceof SimpleNode<?>) {
103             if (schema instanceof LeafListSchemaNode) {
104                 writeValueByType(itemEl, (SimpleNode<?>) data, ((LeafListSchemaNode) schema).getType(),
105                         (DataSchemaNode) schema, codecProvider);
106             } else if (schema instanceof LeafSchemaNode) {
107                 writeValueByType(itemEl, (SimpleNode<?>) data, ((LeafSchemaNode) schema).getType(),
108                         (DataSchemaNode) schema, codecProvider);
109             } else {
110                 Object value = data.getValue();
111                 if (value != null) {
112                     itemEl.setTextContent(String.valueOf(value));
113                 }
114             }
115         } else { // CompositeNode
116             for (Node<?> child : ((CompositeNode) data).getChildren()) {
117                 DataSchemaNode childSchema = null;
118                 if (schema != null) {
119                     childSchema = findFirstSchemaForNode(child, ((DataNodeContainer) schema).getChildNodes());
120                     if (logger.isDebugEnabled()) {
121                         if (childSchema == null) {
122                             logger.debug("Probably the data node \""
123                                     + ((child == null) ? "" : child.getNodeType().getLocalName())
124                                     + "\" is not conform to schema");
125                         }
126                     }
127                 }
128                 itemEl.appendChild(createXmlRootElement(doc, child, childSchema, codecProvider));
129             }
130         }
131         return itemEl;
132     }
133
134     private static Element createElementFor(Document doc, Node<?> data) {
135         QName dataType = data.getNodeType();
136         Element ret;
137         if (dataType.getNamespace() != null) {
138             ret = doc.createElementNS(dataType.getNamespace().toString(), dataType.getLocalName());
139         } else {
140             ret = doc.createElementNS(null, dataType.getLocalName());
141         }
142         if (data instanceof AttributesContainer && ((AttributesContainer) data).getAttributes() != null) {
143             for (Entry<QName, String> attribute : ((AttributesContainer) data).getAttributes().entrySet()) {
144                 ret.setAttributeNS(attribute.getKey().getNamespace().toString(), attribute.getKey().getLocalName(),
145                         attribute.getValue());
146             }
147
148         }
149         return ret;
150     }
151
152     public static void writeValueByType(Element element, SimpleNode<?> node, TypeDefinition<?> type,
153             DataSchemaNode schema, XmlCodecProvider codecProvider) {
154         TypeDefinition<?> baseType = resolveBaseTypeFrom(type);
155
156         if (baseType instanceof IdentityrefTypeDefinition) {
157             if (node.getValue() instanceof QName) {
158                 QName value = (QName) node.getValue();
159                 String prefix = "x";
160                 if (value.getPrefix() != null && !value.getPrefix().isEmpty()) {
161                     prefix = value.getPrefix();
162                 }
163                 element.setAttribute("xmlns:" + prefix, value.getNamespace().toString());
164                 element.setTextContent(prefix + ":" + value.getLocalName());
165             } else {
166                 Object value = node.getValue();
167                 logger.debug("Value of {}:{} is not instance of QName but is {}", baseType.getQName().getNamespace(),
168                         baseType.getQName().getLocalName(), value != null ? value.getClass() : "null");
169                 if (value != null) {
170                     element.setTextContent(String.valueOf(value));
171                 }
172             }
173         } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
174             if (node.getValue() instanceof InstanceIdentifier) {
175                 // Map< key = namespace, value = prefix>
176                 Map<String, String> prefixes = new HashMap<>();
177                 InstanceIdentifier instanceIdentifier = (InstanceIdentifier) node.getValue();
178                 StringBuilder textContent = new StringBuilder();
179                 for (PathArgument pathArgument : instanceIdentifier.getPath()) {
180                     textContent.append("/");
181                     writeIdentifierWithNamespacePrefix(element, textContent, pathArgument.getNodeType(), prefixes);
182                     if (pathArgument instanceof NodeIdentifierWithPredicates) {
183                         Map<QName, Object> predicates = ((NodeIdentifierWithPredicates) pathArgument).getKeyValues();
184
185                         for (QName keyValue : predicates.keySet()) {
186                             String predicateValue = String.valueOf(predicates.get(keyValue));
187                             textContent.append("[");
188                             writeIdentifierWithNamespacePrefix(element, textContent, keyValue, prefixes);
189                             textContent.append("='");
190                             textContent.append(predicateValue);
191                             textContent.append("'");
192                             textContent.append("]");
193                         }
194                     }
195                 }
196                 element.setTextContent(textContent.toString());
197
198             } else {
199                 Object value = node.getValue();
200                 logger.debug("Value of {}:{} is not instance of InstanceIdentifier but is {}", baseType.getQName()
201                         .getNamespace(), //
202                         baseType.getQName().getLocalName(), value != null ? value.getClass() : "null");
203                 if (value != null) {
204                     element.setTextContent(String.valueOf(value));
205                 }
206             }
207         } else {
208             if (node.getValue() != null) {
209                 final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
210                 if (codec != null) {
211                     try {
212                         final String text = codec.serialize(node.getValue());
213                         element.setTextContent(text);
214                     } catch (ClassCastException e) {
215                         logger.error("Provided node did not have type required by mapping. Using stream instead.", e);
216                         element.setTextContent(String.valueOf(node.getValue()));
217                     }
218                 } else {
219                     logger.error("Failed to find codec for {}, falling back to using stream", baseType);
220                     element.setTextContent(String.valueOf(node.getValue()));
221                 }
222             }
223         }
224     }
225
226     private static void writeIdentifierWithNamespacePrefix(Element element, StringBuilder textContent, QName qName,
227             Map<String, String> prefixes) {
228         String namespace = qName.getNamespace().toString();
229         String prefix = prefixes.get(namespace);
230         if (prefix == null) {
231             prefix = qName.getPrefix();
232             if (prefix == null || prefix.isEmpty() || prefixes.containsValue(prefix)) {
233                 prefix = generateNewPrefix(prefixes.values());
234             }
235         }
236
237         element.setAttribute("xmlns:" + prefix, namespace.toString());
238         textContent.append(prefix);
239         prefixes.put(namespace, prefix);
240
241         textContent.append(":");
242         textContent.append(qName.getLocalName());
243     }
244
245     private static String generateNewPrefix(Collection<String> prefixes) {
246         StringBuilder result = null;
247         Random random = new Random();
248         do {
249             result = new StringBuilder();
250             for (int i = 0; i < 4; i++) {
251                 int randomNumber = 0x61 + (Math.abs(random.nextInt()) % 26);
252                 result.append(Character.toChars(randomNumber));
253             }
254         } while (prefixes.contains(result.toString()));
255
256         return result.toString();
257     }
258
259     public final static TypeDefinition<?> resolveBaseTypeFrom(TypeDefinition<?> type) {
260         TypeDefinition<?> superType = type;
261         while (superType.getBaseType() != null) {
262             superType = superType.getBaseType();
263         }
264         return superType;
265     }
266
267     private static final DataSchemaNode findFirstSchemaForNode(Node<?> node, Set<DataSchemaNode> dataSchemaNode) {
268         if (dataSchemaNode != null && node != null) {
269             for (DataSchemaNode dsn : dataSchemaNode) {
270                 if (node.getNodeType().getLocalName().equals(dsn.getQName().getLocalName())) {
271                     return dsn;
272                 } else if (dsn instanceof ChoiceNode) {
273                     for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
274                         DataSchemaNode foundDsn = findFirstSchemaForNode(node, choiceCase.getChildNodes());
275                         if (foundDsn != null) {
276                             return foundDsn;
277                         }
278                     }
279                 }
280             }
281         }
282         return null;
283     }
284
285     public static Node<?> toDomNode(Element xmlElement, Optional<DataSchemaNode> schema,
286             Optional<XmlCodecProvider> codecProvider) {
287         if (schema.isPresent()) {
288             return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(DEFAULT_XML_VALUE_CODEC_PROVIDER));
289         }
290         return toDomNode(xmlElement);
291     }
292
293     public static CompositeNode fromElement(Element xmlElement) {
294         CompositeNodeBuilder<ImmutableCompositeNode> node = ImmutableCompositeNode.builder();
295         node.setQName(qNameFromElement(xmlElement));
296
297         return node.toInstance();
298     }
299
300     private static QName qNameFromElement(Element xmlElement) {
301         String namespace = xmlElement.getNamespaceURI();
302         String localName = xmlElement.getLocalName();
303         return QName.create(namespace != null ? URI.create(namespace) : null, null, localName);
304     }
305
306     private static Node<?> toNodeWithSchema(Element xmlElement, DataSchemaNode schema, XmlCodecProvider codecProvider) {
307         checkQName(xmlElement, schema.getQName());
308         if (schema instanceof DataNodeContainer) {
309             return toCompositeNodeWithSchema(xmlElement, schema.getQName(), (DataNodeContainer) schema, codecProvider);
310         } else if (schema instanceof LeafSchemaNode) {
311             return toSimpleNodeWithType(xmlElement, (LeafSchemaNode) schema, codecProvider);
312         } else if (schema instanceof LeafListSchemaNode) {
313             return toSimpleNodeWithType(xmlElement, (LeafListSchemaNode) schema, codecProvider);
314
315         }
316         return null;
317     }
318
319     private static Node<?> toSimpleNodeWithType(Element xmlElement, LeafSchemaNode schema,
320             XmlCodecProvider codecProvider) {
321         TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
322         String text = xmlElement.getTextContent();
323         Object value;
324         if (codec != null) {
325             value = codec.deserialize(text);
326
327         } else {
328             value = xmlElement.getTextContent();
329         }
330         return new SimpleNodeTOImpl<Object>(schema.getQName(), null, value);
331     }
332
333     private static Node<?> toSimpleNodeWithType(Element xmlElement, LeafListSchemaNode schema,
334             XmlCodecProvider codecProvider) {
335         TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
336         String text = xmlElement.getTextContent();
337         Object value;
338         if (codec != null) {
339             value = codec.deserialize(text);
340
341         } else {
342             value = xmlElement.getTextContent();
343         }
344         return new SimpleNodeTOImpl<Object>(schema.getQName(), null, value);
345     }
346
347     private static Node<?> toCompositeNodeWithSchema(Element xmlElement, QName qName, DataNodeContainer schema,
348             XmlCodecProvider codecProvider) {
349         List<Node<?>> values = toDomNodes(xmlElement, Optional.fromNullable(schema.getChildNodes()));
350         return ImmutableCompositeNode.create(qName, values);
351     }
352
353     private static void checkQName(Element xmlElement, QName qName) {
354         checkState(Objects.equal(xmlElement.getNamespaceURI(), qName.getNamespace().toString()));
355         checkState(qName.getLocalName().equals(xmlElement.getLocalName()));
356     }
357
358     private static final Optional<DataSchemaNode> findFirstSchema(QName qname, Set<DataSchemaNode> dataSchemaNode) {
359         if (dataSchemaNode != null && !dataSchemaNode.isEmpty() && qname != null) {
360             for (DataSchemaNode dsn : dataSchemaNode) {
361                 if (qname.isEqualWithoutRevision(dsn.getQName())) {
362                     return Optional.<DataSchemaNode> of(dsn);
363                 } else if (dsn instanceof ChoiceNode) {
364                     for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
365                         Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
366                         if (foundDsn != null) {
367                             return foundDsn;
368                         }
369                     }
370                 }
371             }
372         }
373         return Optional.absent();
374     }
375
376     public static Node<?> toDomNode(Document doc) {
377         return toDomNode(doc.getDocumentElement());
378     }
379
380     private static Node<?> toDomNode(Element element) {
381         QName qname = qNameFromElement(element);
382
383         ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
384         NodeList nodes = element.getChildNodes();
385         boolean isSimpleObject = true;
386         String value = null;
387         for (int i = 0; i < nodes.getLength(); i++) {
388             org.w3c.dom.Node child = nodes.item(i);
389             if (child instanceof Element) {
390                 isSimpleObject = false;
391                 values.add(toDomNode((Element) child));
392             }
393             if (isSimpleObject && child instanceof org.w3c.dom.Text) {
394                 value = element.getTextContent();
395                 if (!Strings.isNullOrEmpty(value)) {
396                     isSimpleObject = true;
397                 }
398             }
399         }
400         if (isSimpleObject) {
401             return new SimpleNodeTOImpl<>(qname, null, value);
402         }
403         return ImmutableCompositeNode.create(qname, values.build());
404     }
405
406     public static List<Node<?>> toDomNodes(final Element element, final Optional<Set<DataSchemaNode>> context) {
407         return forEachChild(element.getChildNodes(), new Function<Element, Optional<Node<?>>>() {
408
409             @Override
410             public Optional<Node<?>> apply(Element input) {
411                 if (context.isPresent()) {
412                     QName partialQName = qNameFromElement(input);
413                     Optional<DataSchemaNode> schemaNode = findFirstSchema(partialQName, context.get());
414                     if (schemaNode.isPresent()) {
415                         return Optional.<Node<?>> fromNullable(//
416                                 toNodeWithSchema(input, schemaNode.get(), DEFAULT_XML_VALUE_CODEC_PROVIDER));
417                     }
418                 }
419                 return Optional.<Node<?>> fromNullable(toDomNode(element));
420             }
421
422         });
423
424     }
425     
426     /**
427      * Converts XML Document containing notification data from Netconf device to
428      * Data DOM Nodes. <br>
429      * By specification defined in <a
430      * href="http://tools.ietf.org/search/rfc6020#section-7.14">RFC 6020</a>
431      * there are xml elements containing notifications metadata, like eventTime
432      * or root notification element which specifies namespace for which is
433      * notification defined in yang model. Those elements MUST be stripped off
434      * notifications body. This method returns pure notification body which
435      * begins in element which is equal to notifications name defined in
436      * corresponding yang model. Rest of notification metadata are obfuscated,
437      * thus Data DOM contains only pure notification body.
438      * 
439      * @param document
440      *            XML Document containing notification body
441      * @param notifications
442      *            Notifications Definition Schema
443      * @return Data DOM Nodes containing xml notification body definition or
444      *         <code>null</code> if there is no NotificationDefinition with
445      *         Element with equal notification QName defined in XML Document.
446      */
447     public static CompositeNode notificationToDomNodes(final Document document,
448             final Optional<Set<NotificationDefinition>> notifications) {
449         if (notifications.isPresent() && (document != null) && (document.getDocumentElement() != null)) {
450             final NodeList originChildNodes = document.getDocumentElement().getChildNodes();
451
452             for (int i = 0; i < originChildNodes.getLength(); i++) {
453                 org.w3c.dom.Node child = originChildNodes.item(i);
454                 if (child instanceof Element) {
455                     final Element childElement = (Element) child;
456                     final QName partialQName = qNameFromElement(childElement);
457                     final Optional<NotificationDefinition> notificationDef = findNotification(partialQName,
458                             notifications.get());
459                     if (notificationDef.isPresent()) {
460                         final Set<DataSchemaNode> dataNodes = notificationDef.get().getChildNodes();
461                         final List<Node<?>> domNodes = toDomNodes(childElement,
462                                 Optional.<Set<DataSchemaNode>> fromNullable(dataNodes));
463                         return ImmutableCompositeNode.create(partialQName, domNodes);
464                     }
465                 }
466             }
467         }
468         return null;
469     }
470
471     private static Optional<NotificationDefinition> findNotification(final QName notifName,
472             final Set<NotificationDefinition> notifications) {
473         if ((notifName != null) && (notifications != null)) {
474             for (final NotificationDefinition notification : notifications) {
475                 if ((notification != null) && notifName.isEqualWithoutRevision(notification.getQName())) {
476                     return Optional.<NotificationDefinition>fromNullable(notification);
477                 }
478             }
479         }
480         return Optional.<NotificationDefinition>absent();
481     }
482
483     private static final <T> List<T> forEachChild(NodeList nodes, Function<Element, Optional<T>> forBody) {
484         ImmutableList.Builder<T> ret = ImmutableList.<T> builder();
485         for (int i = 0; i < nodes.getLength(); i++) {
486             org.w3c.dom.Node child = nodes.item(i);
487             if (child instanceof Element) {
488                 Optional<T> result = forBody.apply((Element) child);
489                 if (result.isPresent()) {
490                     ret.add(result.get());
491                 }
492             }
493         }
494         return ret.build();
495     }
496
497     public static final XmlCodecProvider defaultValueCodecProvider() {
498         return DEFAULT_XML_VALUE_CODEC_PROVIDER;
499     }
500
501 }