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