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