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