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.Collection;
14 import java.util.HashMap;
15 import java.util.List;
17 import java.util.Map.Entry;
18 import java.util.Random;
21 import javax.activation.UnsupportedDataTypeException;
22 import javax.xml.parsers.DocumentBuilder;
23 import javax.xml.parsers.DocumentBuilderFactory;
24 import javax.xml.parsers.ParserConfigurationException;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
28 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
29 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
31 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeWithValue;
32 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
33 import org.opendaylight.yangtools.yang.data.api.Node;
34 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
35 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
36 import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
37 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
38 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
39 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
40 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
41 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
43 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
48 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
50 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
51 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import org.w3c.dom.Document;
55 import org.w3c.dom.Element;
56 import org.w3c.dom.NodeList;
58 import com.google.common.base.Function;
59 import com.google.common.base.Objects;
60 import com.google.common.base.Optional;
61 import com.google.common.base.Preconditions;
62 import com.google.common.base.Strings;
63 import com.google.common.collect.ImmutableList;
65 public class XmlDocumentUtils {
67 private static final XmlCodecProvider DEFAULT_XML_VALUE_CODEC_PROVIDER = new XmlCodecProvider() {
70 public TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codecFor(TypeDefinition<?> baseType) {
71 return TypeDefinitionAwareCodec.from(baseType);
75 private static final Logger logger = LoggerFactory.getLogger(XmlDocumentUtils.class);
78 * Converts Data DOM structure to XML Document for specified XML Codec Provider and corresponding
79 * Data Node Container schema. The CompositeNode data parameter enters as root of Data DOM tree and will
80 * be transformed to root in XML Document. Each element of Data DOM tree is compared against specified Data
81 * Node Container Schema and transformed accordingly.
83 * @param data Data DOM root element
84 * @param schema Data Node Container Schema
85 * @param codecProvider XML Codec Provider
86 * @return new instance of XML Document
87 * @throws UnsupportedDataTypeException
89 public static Document toDocument(CompositeNode data, DataNodeContainer schema, XmlCodecProvider codecProvider)
90 throws UnsupportedDataTypeException {
91 Preconditions.checkNotNull(data);
92 Preconditions.checkNotNull(schema);
94 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
97 DocumentBuilder bob = dbf.newDocumentBuilder();
98 doc = bob.newDocument();
99 } catch (ParserConfigurationException e) {
103 if (schema instanceof ContainerSchemaNode || schema instanceof ListSchemaNode) {
104 doc.appendChild(createXmlRootElement(doc, data, (SchemaNode) schema, codecProvider));
107 throw new UnsupportedDataTypeException(
108 "Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
113 * Converts Data DOM structure to XML Document for specified XML Codec Provider. The CompositeNode
114 * data parameter enters as root of Data DOM tree and will be transformed to root in XML Document. The child
115 * nodes of Data Tree are transformed accordingly.
117 * @param data Data DOM root element
118 * @param codecProvider XML Codec Provider
119 * @return new instance of XML Document
120 * @throws UnsupportedDataTypeException
122 public static Document toDocument(CompositeNode data, XmlCodecProvider codecProvider)
123 throws UnsupportedDataTypeException {
124 Preconditions.checkNotNull(data);
126 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
129 DocumentBuilder bob = dbf.newDocumentBuilder();
130 doc = bob.newDocument();
131 } catch (ParserConfigurationException e) {
135 doc.appendChild(createXmlRootElement(doc, data, null, codecProvider));
139 private static Element createXmlRootElement(Document doc, Node<?> data, SchemaNode schema,
140 XmlCodecProvider codecProvider) throws UnsupportedDataTypeException {
141 Element itemEl = createElementFor(doc, data);
142 if (data instanceof SimpleNode<?>) {
143 if (schema instanceof LeafListSchemaNode) {
144 writeValueByType(itemEl, (SimpleNode<?>) data, ((LeafListSchemaNode) schema).getType(),
145 (DataSchemaNode) schema, codecProvider);
146 } else if (schema instanceof LeafSchemaNode) {
147 writeValueByType(itemEl, (SimpleNode<?>) data, ((LeafSchemaNode) schema).getType(),
148 (DataSchemaNode) schema, codecProvider);
150 Object value = data.getValue();
152 itemEl.setTextContent(String.valueOf(value));
155 } else { // CompositeNode
156 for (Node<?> child : ((CompositeNode) data).getChildren()) {
157 DataSchemaNode childSchema = null;
158 if (schema != null) {
159 childSchema = findFirstSchemaForNode(child, ((DataNodeContainer) schema).getChildNodes());
160 if (logger.isDebugEnabled()) {
161 if (childSchema == null) {
162 logger.debug("Probably the data node \""
163 + ((child == null) ? "" : child.getNodeType().getLocalName())
164 + "\" is not conform to schema");
168 itemEl.appendChild(createXmlRootElement(doc, child, childSchema, codecProvider));
174 private static Element createElementFor(Document doc, Node<?> data) {
175 QName dataType = data.getNodeType();
177 if (dataType.getNamespace() != null) {
178 ret = doc.createElementNS(dataType.getNamespace().toString(), dataType.getLocalName());
180 ret = doc.createElementNS(null, dataType.getLocalName());
182 if (data instanceof AttributesContainer && ((AttributesContainer) data).getAttributes() != null) {
183 for (Entry<QName, String> attribute : ((AttributesContainer) data).getAttributes().entrySet()) {
184 ret.setAttributeNS(attribute.getKey().getNamespace().toString(), attribute.getKey().getLocalName(),
185 attribute.getValue());
192 public static void writeValueByType(Element element, SimpleNode<?> node, TypeDefinition<?> type,
193 DataSchemaNode schema, XmlCodecProvider codecProvider) {
194 TypeDefinition<?> baseType = resolveBaseTypeFrom(type);
196 if (baseType instanceof IdentityrefTypeDefinition) {
197 if (node.getValue() instanceof QName) {
198 QName value = (QName) node.getValue();
200 if (value.getPrefix() != null && !value.getPrefix().isEmpty()) {
201 prefix = value.getPrefix();
203 element.setAttribute("xmlns:" + prefix, value.getNamespace().toString());
204 element.setTextContent(prefix + ":" + value.getLocalName());
206 Object value = node.getValue();
207 logger.debug("Value of {}:{} is not instance of QName but is {}", baseType.getQName().getNamespace(),
208 baseType.getQName().getLocalName(), value != null ? value.getClass() : "null");
210 element.setTextContent(String.valueOf(value));
213 } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
214 if (node.getValue() instanceof InstanceIdentifier) {
215 // Map< key = namespace, value = prefix>
216 Map<String, String> prefixes = new HashMap<>();
217 InstanceIdentifier instanceIdentifier = (InstanceIdentifier) node.getValue();
218 StringBuilder textContent = new StringBuilder();
219 for (PathArgument pathArgument : instanceIdentifier.getPath()) {
220 textContent.append("/");
221 writeIdentifierWithNamespacePrefix(element, textContent, pathArgument.getNodeType(), prefixes);
222 if (pathArgument instanceof NodeIdentifierWithPredicates) {
223 Map<QName, Object> predicates = ((NodeIdentifierWithPredicates) pathArgument).getKeyValues();
225 for (QName keyValue : predicates.keySet()) {
226 String predicateValue = String.valueOf(predicates.get(keyValue));
227 textContent.append("[");
228 writeIdentifierWithNamespacePrefix(element, textContent, keyValue, prefixes);
229 textContent.append("='");
230 textContent.append(predicateValue);
231 textContent.append("'");
232 textContent.append("]");
234 } else if (pathArgument instanceof NodeWithValue) {
235 textContent.append("[.='");
236 textContent.append(((NodeWithValue)pathArgument).getValue());
237 textContent.append("'");
238 textContent.append("]");
241 element.setTextContent(textContent.toString());
244 Object value = node.getValue();
245 logger.debug("Value of {}:{} is not instance of InstanceIdentifier but is {}", baseType.getQName()
247 baseType.getQName().getLocalName(), value != null ? value.getClass() : "null");
249 element.setTextContent(String.valueOf(value));
253 if (node.getValue() != null) {
254 final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
257 final String text = codec.serialize(node.getValue());
258 element.setTextContent(text);
259 } catch (ClassCastException e) {
260 logger.error("Provided node {} did not have type {} required by mapping. Using stream instead.", node, baseType, e);
261 element.setTextContent(String.valueOf(node.getValue()));
264 logger.error("Failed to find codec for {}, falling back to using stream", baseType);
265 element.setTextContent(String.valueOf(node.getValue()));
271 private static void writeIdentifierWithNamespacePrefix(Element element, StringBuilder textContent, QName qName,
272 Map<String, String> prefixes) {
273 String namespace = qName.getNamespace().toString();
274 String prefix = prefixes.get(namespace);
275 if (prefix == null) {
276 prefix = qName.getPrefix();
277 if (prefix == null || prefix.isEmpty() || prefixes.containsValue(prefix)) {
278 prefix = generateNewPrefix(prefixes.values());
282 element.setAttribute("xmlns:" + prefix, namespace.toString());
283 textContent.append(prefix);
284 prefixes.put(namespace, prefix);
286 textContent.append(":");
287 textContent.append(qName.getLocalName());
290 private static String generateNewPrefix(Collection<String> prefixes) {
291 StringBuilder result = null;
292 Random random = new Random();
294 result = new StringBuilder();
295 for (int i = 0; i < 4; i++) {
296 int randomNumber = 0x61 + (Math.abs(random.nextInt()) % 26);
297 result.append(Character.toChars(randomNumber));
299 } while (prefixes.contains(result.toString()));
301 return result.toString();
304 public final static TypeDefinition<?> resolveBaseTypeFrom(TypeDefinition<?> type) {
305 TypeDefinition<?> superType = type;
306 while (superType.getBaseType() != null) {
307 superType = superType.getBaseType();
312 private static final DataSchemaNode findFirstSchemaForNode(Node<?> node, Set<DataSchemaNode> dataSchemaNode) {
313 if (dataSchemaNode != null && node != null) {
314 for (DataSchemaNode dsn : dataSchemaNode) {
315 if (node.getNodeType().getLocalName().equals(dsn.getQName().getLocalName())) {
317 } else if (dsn instanceof ChoiceNode) {
318 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
319 DataSchemaNode foundDsn = findFirstSchemaForNode(node, choiceCase.getChildNodes());
320 if (foundDsn != null) {
330 public static Node<?> toDomNode(Element xmlElement, Optional<DataSchemaNode> schema,
331 Optional<XmlCodecProvider> codecProvider) {
332 if (schema.isPresent()) {
333 return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(DEFAULT_XML_VALUE_CODEC_PROVIDER));
335 return toDomNode(xmlElement);
338 public static CompositeNode fromElement(Element xmlElement) {
339 CompositeNodeBuilder<ImmutableCompositeNode> node = ImmutableCompositeNode.builder();
340 node.setQName(qNameFromElement(xmlElement));
342 return node.toInstance();
345 private static QName qNameFromElement(Element xmlElement) {
346 String namespace = xmlElement.getNamespaceURI();
347 String localName = xmlElement.getLocalName();
348 return QName.create(namespace != null ? URI.create(namespace) : null, null, localName);
351 private static Node<?> toNodeWithSchema(Element xmlElement, DataSchemaNode schema, XmlCodecProvider codecProvider) {
352 checkQName(xmlElement, schema.getQName());
353 if (schema instanceof DataNodeContainer) {
354 return toCompositeNodeWithSchema(xmlElement, schema.getQName(), (DataNodeContainer) schema, codecProvider);
355 } else if (schema instanceof LeafSchemaNode) {
356 return toSimpleNodeWithType(xmlElement, (LeafSchemaNode) schema, codecProvider);
357 } else if (schema instanceof LeafListSchemaNode) {
358 return toSimpleNodeWithType(xmlElement, (LeafListSchemaNode) schema, codecProvider);
364 private static Node<?> toSimpleNodeWithType(Element xmlElement, LeafSchemaNode schema,
365 XmlCodecProvider codecProvider) {
366 TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
367 String text = xmlElement.getTextContent();
370 value = codec.deserialize(text);
373 value = xmlElement.getTextContent();
375 return new SimpleNodeTOImpl<Object>(schema.getQName(), null, value);
378 private static Node<?> toSimpleNodeWithType(Element xmlElement, LeafListSchemaNode schema,
379 XmlCodecProvider codecProvider) {
380 TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
381 String text = xmlElement.getTextContent();
384 value = codec.deserialize(text);
387 value = xmlElement.getTextContent();
389 return new SimpleNodeTOImpl<Object>(schema.getQName(), null, value);
392 private static Node<?> toCompositeNodeWithSchema(Element xmlElement, QName qName, DataNodeContainer schema,
393 XmlCodecProvider codecProvider) {
394 List<Node<?>> values = toDomNodes(xmlElement, Optional.fromNullable(schema.getChildNodes()));
395 return ImmutableCompositeNode.create(qName, values);
398 private static void checkQName(Element xmlElement, QName qName) {
399 checkState(Objects.equal(xmlElement.getNamespaceURI(), qName.getNamespace().toString()));
400 checkState(qName.getLocalName().equals(xmlElement.getLocalName()));
403 private static final Optional<DataSchemaNode> findFirstSchema(QName qname, Set<DataSchemaNode> dataSchemaNode) {
404 if (dataSchemaNode != null && !dataSchemaNode.isEmpty() && qname != null) {
405 for (DataSchemaNode dsn : dataSchemaNode) {
406 if (qname.isEqualWithoutRevision(dsn.getQName())) {
407 return Optional.<DataSchemaNode> of(dsn);
408 } else if (dsn instanceof ChoiceNode) {
409 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
410 Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
411 if (foundDsn != null && foundDsn.isPresent()) {
418 return Optional.absent();
421 public static Node<?> toDomNode(Document doc) {
422 return toDomNode(doc.getDocumentElement());
425 private static Node<?> toDomNode(Element element) {
426 QName qname = qNameFromElement(element);
428 ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
429 NodeList nodes = element.getChildNodes();
430 boolean isSimpleObject = true;
432 for (int i = 0; i < nodes.getLength(); i++) {
433 org.w3c.dom.Node child = nodes.item(i);
434 if (child instanceof Element) {
435 isSimpleObject = false;
436 values.add(toDomNode((Element) child));
438 if (isSimpleObject && child instanceof org.w3c.dom.Text) {
439 value = element.getTextContent();
440 if (!Strings.isNullOrEmpty(value)) {
441 isSimpleObject = true;
445 if (isSimpleObject) {
446 return new SimpleNodeTOImpl<>(qname, null, value);
448 return ImmutableCompositeNode.create(qname, values.build());
451 public static List<Node<?>> toDomNodes(final Element element, final Optional<Set<DataSchemaNode>> context) {
452 return forEachChild(element.getChildNodes(), new Function<Element, Optional<Node<?>>>() {
455 public Optional<Node<?>> apply(Element input) {
456 if (context.isPresent()) {
457 QName partialQName = qNameFromElement(input);
458 Optional<DataSchemaNode> schemaNode = findFirstSchema(partialQName, context.get());
459 if (schemaNode.isPresent()) {
460 return Optional.<Node<?>> fromNullable(//
461 toNodeWithSchema(input, schemaNode.get(), DEFAULT_XML_VALUE_CODEC_PROVIDER));
464 return Optional.<Node<?>> fromNullable(toDomNode(input));
472 * Converts XML Document containing notification data from Netconf device to
473 * Data DOM Nodes. <br>
474 * By specification defined in <a
475 * href="http://tools.ietf.org/search/rfc6020#section-7.14">RFC 6020</a>
476 * there are xml elements containing notifications metadata, like eventTime
477 * or root notification element which specifies namespace for which is
478 * notification defined in yang model. Those elements MUST be stripped off
479 * notifications body. This method returns pure notification body which
480 * begins in element which is equal to notifications name defined in
481 * corresponding yang model. Rest of notification metadata are obfuscated,
482 * thus Data DOM contains only pure notification body.
485 * XML Document containing notification body
486 * @param notifications
487 * Notifications Definition Schema
488 * @return Data DOM Nodes containing xml notification body definition or
489 * <code>null</code> if there is no NotificationDefinition with
490 * Element with equal notification QName defined in XML Document.
492 public static CompositeNode notificationToDomNodes(final Document document,
493 final Optional<Set<NotificationDefinition>> notifications) {
494 if (notifications.isPresent() && (document != null) && (document.getDocumentElement() != null)) {
495 final NodeList originChildNodes = document.getDocumentElement().getChildNodes();
497 for (int i = 0; i < originChildNodes.getLength(); i++) {
498 org.w3c.dom.Node child = originChildNodes.item(i);
499 if (child instanceof Element) {
500 final Element childElement = (Element) child;
501 final QName partialQName = qNameFromElement(childElement);
502 final Optional<NotificationDefinition> notificationDef = findNotification(partialQName,
503 notifications.get());
504 if (notificationDef.isPresent()) {
505 final Set<DataSchemaNode> dataNodes = notificationDef.get().getChildNodes();
506 final List<Node<?>> domNodes = toDomNodes(childElement,
507 Optional.<Set<DataSchemaNode>> fromNullable(dataNodes));
508 return ImmutableCompositeNode.create(notificationDef.get().getQName(), domNodes);
516 private static Optional<NotificationDefinition> findNotification(final QName notifName,
517 final Set<NotificationDefinition> notifications) {
518 if ((notifName != null) && (notifications != null)) {
519 for (final NotificationDefinition notification : notifications) {
520 if ((notification != null) && notifName.isEqualWithoutRevision(notification.getQName())) {
521 return Optional.<NotificationDefinition>fromNullable(notification);
525 return Optional.<NotificationDefinition>absent();
528 private static final <T> List<T> forEachChild(NodeList nodes, Function<Element, Optional<T>> forBody) {
529 ImmutableList.Builder<T> ret = ImmutableList.<T> builder();
530 for (int i = 0; i < nodes.getLength(); i++) {
531 org.w3c.dom.Node child = nodes.item(i);
532 if (child instanceof Element) {
533 Optional<T> result = forBody.apply((Element) child);
534 if (result.isPresent()) {
535 ret.add(result.get());
542 public static final XmlCodecProvider defaultValueCodecProvider() {
543 return DEFAULT_XML_VALUE_CODEC_PROVIDER;