2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.data.impl.codec.xml;
10 import static com.google.common.base.Preconditions.checkState;
13 import java.util.List;
14 import java.util.Map.Entry;
17 import javax.activation.UnsupportedDataTypeException;
18 import javax.xml.parsers.DocumentBuilder;
19 import javax.xml.parsers.DocumentBuilderFactory;
20 import javax.xml.parsers.ParserConfigurationException;
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;
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;
55 public class XmlDocumentUtils {
57 private static final XmlCodecProvider DEFAULT_XML_VALUE_CODEC_PROVIDER = new XmlCodecProvider() {
60 public TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codecFor(TypeDefinition<?> baseType) {
61 return TypeDefinitionAwareCodec.from(baseType);
65 private static final Logger logger = LoggerFactory.getLogger(XmlDocumentUtils.class);
67 public static Document toDocument(CompositeNode data, DataNodeContainer schema, XmlCodecProvider codecProvider)
68 throws UnsupportedDataTypeException {
69 Preconditions.checkNotNull(data);
70 Preconditions.checkNotNull(schema);
72 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
75 DocumentBuilder bob = dbf.newDocumentBuilder();
76 doc = bob.newDocument();
77 } catch (ParserConfigurationException e) {
81 if (schema instanceof ContainerSchemaNode || schema instanceof ListSchemaNode) {
82 doc.appendChild(createXmlRootElement(doc, data, (SchemaNode) schema, codecProvider));
85 throw new UnsupportedDataTypeException(
86 "Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
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);
101 Object value = data.getValue();
103 itemEl.setTextContent(String.valueOf(value));
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");
119 itemEl.appendChild(createXmlRootElement(doc, child, childSchema, codecProvider));
125 private static Element createElementFor(Document doc, Node<?> data) {
126 QName dataType = data.getNodeType();
128 if (dataType.getNamespace() != null) {
129 ret = doc.createElementNS(dataType.getNamespace().toString(), dataType.getLocalName());
131 ret = doc.createElementNS(null, dataType.getLocalName());
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());
143 public static void writeValueByType(Element element, SimpleNode<?> node, TypeDefinition<?> type,
144 DataSchemaNode schema, XmlCodecProvider codecProvider) {
146 TypeDefinition<?> baseType = resolveBaseTypeFrom(type);
148 if (baseType instanceof IdentityrefTypeDefinition) {
149 if (node.getValue() instanceof QName) {
150 QName value = (QName) node.getValue();
152 if (value.getPrefix() != null && !value.getPrefix().isEmpty()) {
153 prefix = value.getPrefix();
155 element.setAttribute("xmlns:" + prefix, value.getNamespace().toString());
156 element.setTextContent(prefix + ":" + value.getLocalName());
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()));
164 if (node.getValue() != null) {
165 final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
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()));
175 logger.error("Failed to find codec for {}, falling back to using stream", baseType);
176 element.setTextContent(String.valueOf(node.getValue()));
182 public final static TypeDefinition<?> resolveBaseTypeFrom(TypeDefinition<?> type) {
183 TypeDefinition<?> superType = type;
184 while (superType.getBaseType() != null) {
185 superType = superType.getBaseType();
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())) {
195 } else if (dsn instanceof ChoiceNode) {
196 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
197 DataSchemaNode foundDsn = findFirstSchemaForNode(node, choiceCase.getChildNodes());
198 if (foundDsn != null) {
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));
213 return toDomNode(xmlElement);
216 public static CompositeNode fromElement(Element xmlElement) {
217 CompositeNodeBuilder<ImmutableCompositeNode> node = ImmutableCompositeNode.builder();
218 node.setQName(qNameFromElement(xmlElement));
220 return node.toInstance();
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);
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);
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();
248 value = codec.deserialize(text);
251 value = xmlElement.getTextContent();
253 return new SimpleNodeTOImpl<Object>(schema.getQName(), null, value);
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();
262 value = codec.deserialize(text);
265 value = xmlElement.getTextContent();
267 return new SimpleNodeTOImpl<Object>(schema.getQName(), null, value);
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);
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()));
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) {
296 return Optional.absent();
299 public static Node<?> toDomNode(Document doc) {
300 return toDomNode(doc.getDocumentElement());
303 private static Node<?> toDomNode(Element element) {
304 QName qname = qNameFromElement(element);
306 ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
307 NodeList nodes = element.getChildNodes();
308 boolean isSimpleObject = true;
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));
316 if (isSimpleObject && child instanceof org.w3c.dom.Text) {
317 value = element.getTextContent();
318 if (!Strings.isNullOrEmpty(value)) {
319 isSimpleObject = true;
323 if (isSimpleObject) {
324 return new SimpleNodeTOImpl<>(qname, null, value);
326 return ImmutableCompositeNode.create(qname, values.build());
329 public static List<Node<?>> toDomNodes(final Element element, final Optional<Set<DataSchemaNode>> context) {
330 return forEachChild(element.getChildNodes(), new Function<Element, Optional<Node<?>>>() {
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));
342 return Optional.<Node<?>> fromNullable(toDomNode(element));
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());
363 public static final XmlCodecProvider defaultValueCodecProvider() {
364 return DEFAULT_XML_VALUE_CODEC_PROVIDER;