NPE prevention in log
[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.SchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
41 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.w3c.dom.Document;
45 import org.w3c.dom.Element;
46 import org.w3c.dom.NodeList;
47
48 import com.google.common.base.Function;
49 import com.google.common.base.Objects;
50 import com.google.common.base.Optional;
51 import com.google.common.base.Preconditions;
52 import com.google.common.base.Strings;
53 import com.google.common.collect.ImmutableList;
54
55 public class XmlDocumentUtils {
56
57     private static final XmlCodecProvider DEFAULT_XML_VALUE_CODEC_PROVIDER = new XmlCodecProvider() {
58
59         @Override
60         public TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codecFor(TypeDefinition<?> baseType) {
61             return TypeDefinitionAwareCodec.from(baseType);
62         }
63     };
64
65     private static final Logger logger = LoggerFactory.getLogger(XmlDocumentUtils.class);
66
67     public static Document toDocument(CompositeNode data, DataNodeContainer schema, XmlCodecProvider codecProvider)
68             throws UnsupportedDataTypeException {
69         Preconditions.checkNotNull(data);
70         Preconditions.checkNotNull(schema);
71
72         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
73         Document doc = null;
74         try {
75             DocumentBuilder bob = dbf.newDocumentBuilder();
76             doc = bob.newDocument();
77         } catch (ParserConfigurationException e) {
78             return null;
79         }
80
81         if (schema instanceof ContainerSchemaNode || schema instanceof ListSchemaNode) {
82             doc.appendChild(createXmlRootElement(doc, data, (SchemaNode) schema, codecProvider));
83             return doc;
84         } else {
85             throw new UnsupportedDataTypeException(
86                     "Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
87         }
88     }
89
90     private static Element createXmlRootElement(Document doc, Node<?> data, SchemaNode schema,
91             XmlCodecProvider codecProvider) throws UnsupportedDataTypeException {
92         Element itemEl = createElementFor(doc, data);
93         if (data instanceof SimpleNode<?>) {
94             if (schema instanceof LeafListSchemaNode) {
95                 writeValueByType(itemEl, (SimpleNode<?>) data, ((LeafListSchemaNode) schema).getType(),
96                         (DataSchemaNode) schema, codecProvider);
97             } else if (schema instanceof LeafSchemaNode) {
98                 writeValueByType(itemEl, (SimpleNode<?>) data, ((LeafSchemaNode) schema).getType(),
99                         (DataSchemaNode) schema, codecProvider);
100             } else {
101                 Object value = data.getValue();
102                 if (value != null) {
103                     itemEl.setTextContent(String.valueOf(value));
104                 }
105             }
106         } else { // CompositeNode
107             for (Node<?> child : ((CompositeNode) data).getChildren()) {
108                 DataSchemaNode childSchema = null;
109                 if (schema != null) {
110                     childSchema = findFirstSchemaForNode(child, ((DataNodeContainer) schema).getChildNodes());
111                     if (logger.isDebugEnabled()) {
112                         if (childSchema == null) {
113                             logger.debug("Probably the data node \""
114                                     + ((child == null) ? "" : child.getNodeType().getLocalName())
115                                     + "\" is not conform to schema");
116                         }
117                     }
118                 }
119                 itemEl.appendChild(createXmlRootElement(doc, child, childSchema, codecProvider));
120             }
121         }
122         return itemEl;
123     }
124
125     private static Element createElementFor(Document doc, Node<?> data) {
126         QName dataType = data.getNodeType();
127         Element ret;
128         if (dataType.getNamespace() != null) {
129             ret = doc.createElementNS(dataType.getNamespace().toString(), dataType.getLocalName());
130         } else {
131             ret = doc.createElementNS(null, dataType.getLocalName());
132         }
133         if (data instanceof AttributesContainer && ((AttributesContainer) data).getAttributes() != null) {
134             for (Entry<QName, String> attribute : ((AttributesContainer) data).getAttributes().entrySet()) {
135                 ret.setAttributeNS(attribute.getKey().getNamespace().toString(), attribute.getKey().getLocalName(),
136                         attribute.getValue());
137             }
138
139         }
140         return ret;
141     }
142
143     public static void writeValueByType(Element element, SimpleNode<?> node, TypeDefinition<?> type,
144             DataSchemaNode schema, XmlCodecProvider codecProvider) {
145
146         TypeDefinition<?> baseType = resolveBaseTypeFrom(type);
147
148         if (baseType instanceof IdentityrefTypeDefinition) {
149             if (node.getValue() instanceof QName) {
150                 QName value = (QName) node.getValue();
151                 String prefix = "x";
152                 if (value.getPrefix() != null && !value.getPrefix().isEmpty()) {
153                     prefix = value.getPrefix();
154                 }
155                 element.setAttribute("xmlns:" + prefix, value.getNamespace().toString());
156                 element.setTextContent(prefix + ":" + value.getLocalName());
157             } else {
158                 Object value = node.getValue();
159                 logger.debug("Value of {}:{} is not instance of QName but is {}", baseType.getQName().getNamespace(), //
160                         baseType.getQName().getLocalName(), //
161                         node != null ? value.getClass() : "null");
162                 if (value != null) {
163                     element.setTextContent(String.valueOf(value));
164                 }
165             }
166         } else {
167             if (node.getValue() != null) {
168                 final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
169                 if (codec != null) {
170                     try {
171                         final String text = codec.serialize(node.getValue());
172                         element.setTextContent(text);
173                     } catch (ClassCastException e) {
174                         logger.error("Provided node did not have type required by mapping. Using stream instead.", e);
175                         element.setTextContent(String.valueOf(node.getValue()));
176                     }
177                 } else {
178                     logger.error("Failed to find codec for {}, falling back to using stream", baseType);
179                     element.setTextContent(String.valueOf(node.getValue()));
180                 }
181             }
182         }
183     }
184
185     public final static TypeDefinition<?> resolveBaseTypeFrom(TypeDefinition<?> type) {
186         TypeDefinition<?> superType = type;
187         while (superType.getBaseType() != null) {
188             superType = superType.getBaseType();
189         }
190         return superType;
191     }
192
193     private static final DataSchemaNode findFirstSchemaForNode(Node<?> node, Set<DataSchemaNode> dataSchemaNode) {
194         if (dataSchemaNode != null && node != null) {
195             for (DataSchemaNode dsn : dataSchemaNode) {
196                 if (node.getNodeType().getLocalName().equals(dsn.getQName().getLocalName())) {
197                     return dsn;
198                 } else if (dsn instanceof ChoiceNode) {
199                     for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
200                         DataSchemaNode foundDsn = findFirstSchemaForNode(node, choiceCase.getChildNodes());
201                         if (foundDsn != null) {
202                             return foundDsn;
203                         }
204                     }
205                 }
206             }
207         }
208         return null;
209     }
210
211     public static Node<?> toDomNode(Element xmlElement, Optional<DataSchemaNode> schema,
212             Optional<XmlCodecProvider> codecProvider) {
213         if (schema.isPresent()) {
214             return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(DEFAULT_XML_VALUE_CODEC_PROVIDER));
215         }
216         return toDomNode(xmlElement);
217     }
218
219     public static CompositeNode fromElement(Element xmlElement) {
220         CompositeNodeBuilder<ImmutableCompositeNode> node = ImmutableCompositeNode.builder();
221         node.setQName(qNameFromElement(xmlElement));
222
223         return node.toInstance();
224     }
225
226     private static QName qNameFromElement(Element xmlElement) {
227         String namespace = xmlElement.getNamespaceURI();
228         String localName = xmlElement.getLocalName();
229         return QName.create(namespace != null ? URI.create(namespace) : null, null, localName);
230     }
231
232     private static Node<?> toNodeWithSchema(Element xmlElement, DataSchemaNode schema, XmlCodecProvider codecProvider) {
233         checkQName(xmlElement, schema.getQName());
234         if (schema instanceof DataNodeContainer) {
235             return toCompositeNodeWithSchema(xmlElement, schema.getQName(), (DataNodeContainer) schema, codecProvider);
236         } else if (schema instanceof LeafSchemaNode) {
237             return toSimpleNodeWithType(xmlElement, (LeafSchemaNode) schema, codecProvider);
238         } else if (schema instanceof LeafListSchemaNode) {
239             return toSimpleNodeWithType(xmlElement, (LeafListSchemaNode) schema, codecProvider);
240
241         }
242         return null;
243     }
244
245     private static Node<?> toSimpleNodeWithType(Element xmlElement, LeafSchemaNode schema,
246             XmlCodecProvider codecProvider) {
247         TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
248         String text = xmlElement.getTextContent();
249         Object value;
250         if (codec != null) {
251             value = codec.deserialize(text);
252
253         } else {
254             value = xmlElement.getTextContent();
255         }
256         return new SimpleNodeTOImpl<Object>(schema.getQName(), null, value);
257     }
258
259     private static Node<?> toSimpleNodeWithType(Element xmlElement, LeafListSchemaNode schema,
260             XmlCodecProvider codecProvider) {
261         TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
262         String text = xmlElement.getTextContent();
263         Object value;
264         if (codec != null) {
265             value = codec.deserialize(text);
266
267         } else {
268             value = xmlElement.getTextContent();
269         }
270         return new SimpleNodeTOImpl<Object>(schema.getQName(), null, value);
271     }
272
273     private static Node<?> toCompositeNodeWithSchema(Element xmlElement, QName qName, DataNodeContainer schema,
274             XmlCodecProvider codecProvider) {
275         List<Node<?>> values = toDomNodes(xmlElement, Optional.fromNullable(schema.getChildNodes()));
276         return ImmutableCompositeNode.create(qName, values);
277     }
278
279     private static void checkQName(Element xmlElement, QName qName) {
280         checkState(Objects.equal(xmlElement.getNamespaceURI(), qName.getNamespace().toString()));
281         checkState(qName.getLocalName().equals(xmlElement.getLocalName()));
282     }
283
284     private static final Optional<DataSchemaNode> findFirstSchema(QName qname, Set<DataSchemaNode> dataSchemaNode) {
285         if (dataSchemaNode != null && !dataSchemaNode.isEmpty() && qname != null) {
286             for (DataSchemaNode dsn : dataSchemaNode) {
287                 if (qname.isEqualWithoutRevision(dsn.getQName())) {
288                     return Optional.<DataSchemaNode> of(dsn);
289                 } else if (dsn instanceof ChoiceNode) {
290                     for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
291                         Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
292                         if (foundDsn != null) {
293                             return foundDsn;
294                         }
295                     }
296                 }
297             }
298         }
299         return Optional.absent();
300     }
301
302     public static Node<?> toDomNode(Document doc) {
303         return toDomNode(doc.getDocumentElement());
304     }
305
306     private static Node<?> toDomNode(Element element) {
307         QName qname = qNameFromElement(element);
308
309         ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
310         NodeList nodes = element.getChildNodes();
311         boolean isSimpleObject = true;
312         String value = null;
313         for (int i = 0; i < nodes.getLength(); i++) {
314             org.w3c.dom.Node child = nodes.item(i);
315             if (child instanceof Element) {
316                 isSimpleObject = false;
317                 values.add(toDomNode((Element) child));
318             }
319             if (isSimpleObject && child instanceof org.w3c.dom.Text) {
320                 value = element.getTextContent();
321                 if (!Strings.isNullOrEmpty(value)) {
322                     isSimpleObject = true;
323                 }
324             }
325         }
326         if (isSimpleObject) {
327             return new SimpleNodeTOImpl<>(qname, null, value);
328         }
329         return ImmutableCompositeNode.create(qname, values.build());
330     }
331
332     public static List<Node<?>> toDomNodes(final Element element, final Optional<Set<DataSchemaNode>> context) {
333         return forEachChild(element.getChildNodes(), new Function<Element, Optional<Node<?>>>() {
334
335             @Override
336             public Optional<Node<?>> apply(Element input) {
337                 if (context.isPresent()) {
338                     QName partialQName = qNameFromElement(input);
339                     Optional<DataSchemaNode> schemaNode = findFirstSchema(partialQName, context.get());
340                     if (schemaNode.isPresent()) {
341                         return Optional.<Node<?>> fromNullable(//
342                                 toNodeWithSchema(input, schemaNode.get(), DEFAULT_XML_VALUE_CODEC_PROVIDER));
343                     }
344                 }
345                 return Optional.<Node<?>> fromNullable(toDomNode(element));
346             }
347
348         });
349
350     }
351
352     private static final <T> List<T> forEachChild(NodeList nodes, Function<Element, Optional<T>> forBody) {
353         ImmutableList.Builder<T> ret = ImmutableList.<T> builder();
354         for (int i = 0; i < nodes.getLength(); i++) {
355             org.w3c.dom.Node child = nodes.item(i);
356             if (child instanceof Element) {
357                 Optional<T> result = forBody.apply((Element) child);
358                 if (result.isPresent()) {
359                     ret.add(result.get());
360                 }
361             }
362         }
363         return ret.build();
364     }
365
366     public static final XmlCodecProvider defaultValueCodecProvider() {
367         return DEFAULT_XML_VALUE_CODEC_PROVIDER;
368     }
369
370 }