Merge "Changed generation of POST operation block"
[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                 logger.debug("Value of {}:{} is not instance of QName but is {}", baseType.getQName().getNamespace(), //
159                         baseType.getQName().getLocalName(), //
160                         node.getValue().getClass());
161                 element.setTextContent(String.valueOf(node.getValue()));
162             }
163         } else {
164             if (node.getValue() != null) {
165                 final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
166                 if (codec != null) {
167                     try {
168                         final String text = codec.serialize(node.getValue());
169                         element.setTextContent(text);
170                     } catch (ClassCastException e) {
171                         logger.error("Provided node did not have type required by mapping. Using stream instead.", e);
172                         element.setTextContent(String.valueOf(node.getValue()));
173                     }
174                 } else {
175                     logger.error("Failed to find codec for {}, falling back to using stream", baseType);
176                     element.setTextContent(String.valueOf(node.getValue()));
177                 }
178             }
179         }
180     }
181
182     public final static TypeDefinition<?> resolveBaseTypeFrom(TypeDefinition<?> type) {
183         TypeDefinition<?> superType = type;
184         while (superType.getBaseType() != null) {
185             superType = superType.getBaseType();
186         }
187         return superType;
188     }
189
190     private static final DataSchemaNode findFirstSchemaForNode(Node<?> node, Set<DataSchemaNode> dataSchemaNode) {
191         if (dataSchemaNode != null && node != null) {
192             for (DataSchemaNode dsn : dataSchemaNode) {
193                 if (node.getNodeType().getLocalName().equals(dsn.getQName().getLocalName())) {
194                     return dsn;
195                 } else if (dsn instanceof ChoiceNode) {
196                     for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
197                         DataSchemaNode foundDsn = findFirstSchemaForNode(node, choiceCase.getChildNodes());
198                         if (foundDsn != null) {
199                             return foundDsn;
200                         }
201                     }
202                 }
203             }
204         }
205         return null;
206     }
207
208     public static Node<?> toDomNode(Element xmlElement, Optional<DataSchemaNode> schema,
209             Optional<XmlCodecProvider> codecProvider) {
210         if (schema.isPresent()) {
211             return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(DEFAULT_XML_VALUE_CODEC_PROVIDER));
212         }
213         return toDomNode(xmlElement);
214     }
215
216     public static CompositeNode fromElement(Element xmlElement) {
217         CompositeNodeBuilder<ImmutableCompositeNode> node = ImmutableCompositeNode.builder();
218         node.setQName(qNameFromElement(xmlElement));
219
220         return node.toInstance();
221     }
222
223     private static QName qNameFromElement(Element xmlElement) {
224         String namespace = xmlElement.getNamespaceURI();
225         String localName = xmlElement.getLocalName();
226         return QName.create(namespace != null ? URI.create(namespace) : null, null, localName);
227     }
228
229     private static Node<?> toNodeWithSchema(Element xmlElement, DataSchemaNode schema, XmlCodecProvider codecProvider) {
230         checkQName(xmlElement, schema.getQName());
231         if (schema instanceof DataNodeContainer) {
232             return toCompositeNodeWithSchema(xmlElement, schema.getQName(), (DataNodeContainer) schema, codecProvider);
233         } else if (schema instanceof LeafSchemaNode) {
234             return toSimpleNodeWithType(xmlElement, (LeafSchemaNode) schema, codecProvider);
235         } else if (schema instanceof LeafListSchemaNode) {
236             return toSimpleNodeWithType(xmlElement, (LeafListSchemaNode) schema, codecProvider);
237
238         }
239         return null;
240     }
241
242     private static Node<?> toSimpleNodeWithType(Element xmlElement, LeafSchemaNode schema,
243             XmlCodecProvider codecProvider) {
244         TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
245         String text = xmlElement.getTextContent();
246         Object value;
247         if (codec != null) {
248             value = codec.deserialize(text);
249
250         } else {
251             value = xmlElement.getTextContent();
252         }
253         return new SimpleNodeTOImpl<Object>(schema.getQName(), null, value);
254     }
255
256     private static Node<?> toSimpleNodeWithType(Element xmlElement, LeafListSchemaNode schema,
257             XmlCodecProvider codecProvider) {
258         TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
259         String text = xmlElement.getTextContent();
260         Object value;
261         if (codec != null) {
262             value = codec.deserialize(text);
263
264         } else {
265             value = xmlElement.getTextContent();
266         }
267         return new SimpleNodeTOImpl<Object>(schema.getQName(), null, value);
268     }
269
270     private static Node<?> toCompositeNodeWithSchema(Element xmlElement, QName qName, DataNodeContainer schema,
271             XmlCodecProvider codecProvider) {
272         List<Node<?>> values = toDomNodes(xmlElement, Optional.fromNullable(schema.getChildNodes()));
273         return ImmutableCompositeNode.create(qName, values);
274     }
275
276     private static void checkQName(Element xmlElement, QName qName) {
277         checkState(Objects.equal(xmlElement.getNamespaceURI(), qName.getNamespace().toString()));
278         checkState(qName.getLocalName().equals(xmlElement.getLocalName()));
279     }
280
281     private static final Optional<DataSchemaNode> findFirstSchema(QName qname, Set<DataSchemaNode> dataSchemaNode) {
282         if (dataSchemaNode != null && !dataSchemaNode.isEmpty() && qname != null) {
283             for (DataSchemaNode dsn : dataSchemaNode) {
284                 if (qname.isEqualWithoutRevision(dsn.getQName())) {
285                     return Optional.<DataSchemaNode> of(dsn);
286                 } else if (dsn instanceof ChoiceNode) {
287                     for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
288                         Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
289                         if (foundDsn != null) {
290                             return foundDsn;
291                         }
292                     }
293                 }
294             }
295         }
296         return Optional.absent();
297     }
298
299     public static Node<?> toDomNode(Document doc) {
300         return toDomNode(doc.getDocumentElement());
301     }
302
303     private static Node<?> toDomNode(Element element) {
304         QName qname = qNameFromElement(element);
305
306         ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
307         NodeList nodes = element.getChildNodes();
308         boolean isSimpleObject = true;
309         String value = null;
310         for (int i = 0; i < nodes.getLength(); i++) {
311             org.w3c.dom.Node child = nodes.item(i);
312             if (child instanceof Element) {
313                 isSimpleObject = false;
314                 values.add(toDomNode((Element) child));
315             }
316             if (isSimpleObject && child instanceof org.w3c.dom.Text) {
317                 value = element.getTextContent();
318                 if (!Strings.isNullOrEmpty(value)) {
319                     isSimpleObject = true;
320                 }
321             }
322         }
323         if (isSimpleObject) {
324             return new SimpleNodeTOImpl<>(qname, null, value);
325         }
326         return ImmutableCompositeNode.create(qname, values.build());
327     }
328
329     public static List<Node<?>> toDomNodes(final Element element, final Optional<Set<DataSchemaNode>> context) {
330         return forEachChild(element.getChildNodes(), new Function<Element, Optional<Node<?>>>() {
331
332             @Override
333             public Optional<Node<?>> apply(Element input) {
334                 if (context.isPresent()) {
335                     QName partialQName = qNameFromElement(input);
336                     Optional<DataSchemaNode> schemaNode = findFirstSchema(partialQName, context.get());
337                     if (schemaNode.isPresent()) {
338                         return Optional.<Node<?>> fromNullable(//
339                                 toNodeWithSchema(input, schemaNode.get(), DEFAULT_XML_VALUE_CODEC_PROVIDER));
340                     }
341                 }
342                 return Optional.<Node<?>> fromNullable(toDomNode(element));
343             }
344
345         });
346
347     }
348
349     private static final <T> List<T> forEachChild(NodeList nodes, Function<Element, Optional<T>> forBody) {
350         ImmutableList.Builder<T> ret = ImmutableList.<T> builder();
351         for (int i = 0; i < nodes.getLength(); i++) {
352             org.w3c.dom.Node child = nodes.item(i);
353             if (child instanceof Element) {
354                 Optional<T> result = forBody.apply((Element) child);
355                 if (result.isPresent()) {
356                     ret.add(result.get());
357                 }
358             }
359         }
360         return ret.build();
361     }
362
363     public static final XmlCodecProvider defaultValueCodecProvider() {
364         return DEFAULT_XML_VALUE_CODEC_PROVIDER;
365     }
366
367 }