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.*;
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;
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;
46 public class XmlDocumentUtils {
48 private static final XmlCodecProvider DEFAULT_XML_VALUE_CODEC_PROVIDER = new XmlCodecProvider() {
51 public TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codecFor(TypeDefinition<?> baseType) {
52 return TypeDefinitionAwareCodec.from(baseType);
56 private static final Logger logger = LoggerFactory.getLogger(XmlDocumentUtils.class);
58 public static Document toDocument(CompositeNode data, DataNodeContainer schema, XmlCodecProvider codecProvider)
59 throws UnsupportedDataTypeException {
60 Preconditions.checkNotNull(data);
61 Preconditions.checkNotNull(schema);
63 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
66 DocumentBuilder bob = dbf.newDocumentBuilder();
67 doc = bob.newDocument();
68 } catch (ParserConfigurationException e) {
72 if (schema instanceof ContainerSchemaNode || schema instanceof ListSchemaNode) {
73 doc.appendChild(createXmlRootElement(doc, data, (SchemaNode) schema, codecProvider));
76 throw new UnsupportedDataTypeException(
77 "Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
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);
92 Object value = data.getValue();
94 itemEl.setTextContent(String.valueOf(value));
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");
110 itemEl.appendChild(createXmlRootElement(doc, child, childSchema, codecProvider));
116 private static Element createElementFor(Document doc, Node<?> data) {
117 QName dataType = data.getNodeType();
119 if (dataType.getNamespace() != null) {
120 ret = doc.createElementNS(dataType.getNamespace().toString(), dataType.getLocalName());
122 ret = doc.createElementNS(null, dataType.getLocalName());
124 if (data instanceof AttributesContainer) {
125 for (Entry<QName, String> attribute : ((AttributesContainer) data).getAttributes().entrySet()) {
126 ret.setAttributeNS(attribute.getKey().getNamespace().toString(), attribute.getKey().getLocalName(),
127 attribute.getValue());
134 public static void writeValueByType(Element element, SimpleNode<?> node, TypeDefinition<?> type,
135 DataSchemaNode schema, XmlCodecProvider codecProvider) {
137 TypeDefinition<?> baseType = resolveBaseTypeFrom(type);
139 if (baseType instanceof IdentityrefTypeDefinition) {
140 if (node.getValue() instanceof QName) {
141 QName value = (QName) node.getValue();
143 if (value.getPrefix() != null && !value.getPrefix().isEmpty()) {
144 prefix = value.getPrefix();
146 element.setAttribute("xmlns:" + prefix, value.getNamespace().toString());
147 element.setTextContent(prefix + ":" + value.getLocalName());
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()));
155 if (node.getValue() != null) {
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);
167 public final static TypeDefinition<?> resolveBaseTypeFrom(TypeDefinition<?> type) {
168 TypeDefinition<?> superType = type;
169 while (superType.getBaseType() != null) {
170 superType = superType.getBaseType();
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())) {
180 } else if (dsn instanceof ChoiceNode) {
181 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
182 DataSchemaNode foundDsn = findFirstSchemaForNode(node, choiceCase.getChildNodes());
183 if (foundDsn != null) {
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));
198 return toDomNode(xmlElement);
201 public static CompositeNode fromElement(Element xmlElement) {
202 CompositeNodeBuilder<ImmutableCompositeNode> node = ImmutableCompositeNode.builder();
203 node.setQName(qNameFromElement(xmlElement));
205 return node.toInstance();
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);
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);
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();
233 value = codec.deserialize(text);
236 value = xmlElement.getTextContent();
238 return new SimpleNodeTOImpl<Object>(schema.getQName(), null, value);
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();
247 value = codec.deserialize(text);
250 value = xmlElement.getTextContent();
252 return new SimpleNodeTOImpl<Object>(schema.getQName(), null, value);
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);
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()));
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) {
281 return Optional.absent();
284 public static Node<?> toDomNode(Document doc) {
285 return toDomNode(doc.getDocumentElement());
288 private static Node<?> toDomNode(Element element) {
289 QName qname = qNameFromElement(element);
291 ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
292 NodeList nodes = element.getChildNodes();
293 boolean isSimpleObject = true;
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));
301 if (isSimpleObject && child instanceof org.w3c.dom.Text) {
302 value = element.getTextContent();
303 if (!Strings.isNullOrEmpty(value)) {
304 isSimpleObject = true;
308 if (isSimpleObject) {
309 return new SimpleNodeTOImpl<>(qname, null, value);
311 return ImmutableCompositeNode.create(qname, values.build());
314 public static List<Node<?>> toDomNodes(final Element element, final Optional<Set<DataSchemaNode>> context) {
315 return forEachChild(element.getChildNodes(), new Function<Element, Optional<Node<?>>>() {
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));
327 return Optional.<Node<?>> fromNullable(toDomNode(element));
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());
348 public static final XmlCodecProvider defaultValueCodecProvider() {
349 return DEFAULT_XML_VALUE_CODEC_PROVIDER;