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.ModifyAction;
34 import org.opendaylight.yangtools.yang.data.api.Node;
35 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
36 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
37 import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
38 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
39 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
40 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
41 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
42 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
44 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
49 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
51 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
52 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.w3c.dom.Attr;
56 import org.w3c.dom.Document;
57 import org.w3c.dom.Element;
58 import org.w3c.dom.NodeList;
60 import com.google.common.base.Function;
61 import com.google.common.base.Objects;
62 import com.google.common.base.Optional;
63 import com.google.common.base.Preconditions;
64 import com.google.common.base.Strings;
65 import com.google.common.collect.ImmutableList;
67 public class XmlDocumentUtils {
69 private static final XmlCodecProvider DEFAULT_XML_VALUE_CODEC_PROVIDER = new XmlCodecProvider() {
72 public TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codecFor(TypeDefinition<?> baseType) {
73 return TypeDefinitionAwareCodec.from(baseType);
77 private static final Logger logger = LoggerFactory.getLogger(XmlDocumentUtils.class);
80 * Converts Data DOM structure to XML Document for specified XML Codec Provider and corresponding
81 * Data Node Container schema. The CompositeNode data parameter enters as root of Data DOM tree and will
82 * be transformed to root in XML Document. Each element of Data DOM tree is compared against specified Data
83 * Node Container Schema and transformed accordingly.
85 * @param data Data DOM root element
86 * @param schema Data Node Container Schema
87 * @param codecProvider XML Codec Provider
88 * @return new instance of XML Document
89 * @throws UnsupportedDataTypeException
91 public static Document toDocument(CompositeNode data, DataNodeContainer schema, XmlCodecProvider codecProvider)
92 throws UnsupportedDataTypeException {
93 Preconditions.checkNotNull(data);
94 Preconditions.checkNotNull(schema);
96 Document doc = getDocument();
98 if (schema instanceof ContainerSchemaNode || schema instanceof ListSchemaNode) {
99 doc.appendChild(createXmlRootElement(doc, data, (SchemaNode) schema, codecProvider));
102 throw new UnsupportedDataTypeException(
103 "Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
107 public static Document getDocument() {
108 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
111 DocumentBuilder bob = dbf.newDocumentBuilder();
112 doc = bob.newDocument();
113 } catch (ParserConfigurationException e) {
114 throw new RuntimeException(e);
120 * Converts Data DOM structure to XML Document for specified XML Codec Provider. The CompositeNode
121 * data parameter enters as root of Data DOM tree and will be transformed to root in XML Document. The child
122 * nodes of Data Tree are transformed accordingly.
124 * @param data Data DOM root element
125 * @param codecProvider XML Codec Provider
126 * @return new instance of XML Document
127 * @throws UnsupportedDataTypeException
129 public static Document toDocument(CompositeNode data, XmlCodecProvider codecProvider)
130 throws UnsupportedDataTypeException {
131 Preconditions.checkNotNull(data);
133 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
134 dbf.setNamespaceAware(true);
137 DocumentBuilder bob = dbf.newDocumentBuilder();
138 doc = bob.newDocument();
139 } catch (ParserConfigurationException e) {
143 doc.appendChild(createXmlRootElement(doc, data, null, codecProvider));
147 private static Element createXmlRootElement(Document doc, Node<?> data, SchemaNode schema,
148 XmlCodecProvider codecProvider) throws UnsupportedDataTypeException {
149 Element itemEl = createElementFor(doc, data);
150 if (data instanceof SimpleNode<?>) {
151 if (schema instanceof LeafListSchemaNode) {
152 writeValueByType(itemEl, (SimpleNode<?>) data, ((LeafListSchemaNode) schema).getType(),
153 (DataSchemaNode) schema, codecProvider);
154 } else if (schema instanceof LeafSchemaNode) {
155 writeValueByType(itemEl, (SimpleNode<?>) data, ((LeafSchemaNode) schema).getType(),
156 (DataSchemaNode) schema, codecProvider);
158 Object value = data.getValue();
160 itemEl.setTextContent(String.valueOf(value));
163 } else { // CompositeNode
164 for (Node<?> child : ((CompositeNode) data).getChildren()) {
165 DataSchemaNode childSchema = null;
166 if (schema != null) {
167 childSchema = findFirstSchemaForNode(child, ((DataNodeContainer) schema).getChildNodes());
168 if (logger.isDebugEnabled()) {
169 if (childSchema == null) {
170 logger.debug("Probably the data node \""
171 + ((child == null) ? "" : child.getNodeType().getLocalName())
172 + "\" is not conform to schema");
176 itemEl.appendChild(createXmlRootElement(doc, child, childSchema, codecProvider));
182 public static Element createElementFor(Document doc, Node<?> data) {
183 QName dataType = data.getNodeType();
185 if (dataType.getNamespace() != null) {
186 ret = doc.createElementNS(dataType.getNamespace().toString(), dataType.getLocalName());
188 ret = doc.createElementNS(null, dataType.getLocalName());
190 if (data instanceof AttributesContainer && ((AttributesContainer) data).getAttributes() != null) {
191 for (Entry<QName, String> attribute : ((AttributesContainer) data).getAttributes().entrySet()) {
192 ret.setAttributeNS(attribute.getKey().getNamespace().toString(), attribute.getKey().getLocalName(),
193 attribute.getValue());
200 public static void writeValueByType(Element element, SimpleNode<?> node, TypeDefinition<?> type,
201 DataSchemaNode schema, XmlCodecProvider codecProvider) {
203 Object nodeValue = node.getValue();
205 writeValueByType(element, type, codecProvider, nodeValue);
208 public static void writeValueByType(Element element, TypeDefinition<?> type, XmlCodecProvider codecProvider, Object nodeValue) {
209 TypeDefinition<?> baseType = resolveBaseTypeFrom(type);
210 if (baseType instanceof IdentityrefTypeDefinition) {
211 if (nodeValue instanceof QName) {
212 QName value = (QName) nodeValue;
214 if (value.getPrefix() != null && !value.getPrefix().isEmpty()) {
215 prefix = value.getPrefix();
217 element.setAttribute("xmlns:" + prefix, value.getNamespace().toString());
218 element.setTextContent(prefix + ":" + value.getLocalName());
220 Object value = nodeValue;
221 logger.debug("Value of {}:{} is not instance of QName but is {}", baseType.getQName().getNamespace(),
222 baseType.getQName().getLocalName(), value != null ? value.getClass() : "null");
224 element.setTextContent(String.valueOf(value));
227 } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
228 if (nodeValue instanceof InstanceIdentifier) {
229 // Map< key = namespace, value = prefix>
230 Map<String, String> prefixes = new HashMap<>();
231 InstanceIdentifier instanceIdentifier = (InstanceIdentifier) nodeValue;
232 StringBuilder textContent = new StringBuilder();
233 for (PathArgument pathArgument : instanceIdentifier.getPath()) {
234 textContent.append("/");
235 writeIdentifierWithNamespacePrefix(element, textContent, pathArgument.getNodeType(), prefixes);
236 if (pathArgument instanceof NodeIdentifierWithPredicates) {
237 Map<QName, Object> predicates = ((NodeIdentifierWithPredicates) pathArgument).getKeyValues();
239 for (QName keyValue : predicates.keySet()) {
240 String predicateValue = String.valueOf(predicates.get(keyValue));
241 textContent.append("[");
242 writeIdentifierWithNamespacePrefix(element, textContent, keyValue, prefixes);
243 textContent.append("='");
244 textContent.append(predicateValue);
245 textContent.append("'");
246 textContent.append("]");
248 } else if (pathArgument instanceof NodeWithValue) {
249 textContent.append("[.='");
250 textContent.append(((NodeWithValue)pathArgument).getValue());
251 textContent.append("'");
252 textContent.append("]");
255 element.setTextContent(textContent.toString());
258 Object value = nodeValue;
259 logger.debug("Value of {}:{} is not instance of InstanceIdentifier but is {}", baseType.getQName()
261 baseType.getQName().getLocalName(), value != null ? value.getClass() : "null");
263 element.setTextContent(String.valueOf(value));
267 if (nodeValue != null) {
268 final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
271 final String text = codec.serialize(nodeValue);
272 element.setTextContent(text);
273 } catch (ClassCastException e) {
274 logger.error("Provided node value {} did not have type {} required by mapping. Using stream instead.", nodeValue, baseType, e);
275 element.setTextContent(String.valueOf(nodeValue));
278 logger.error("Failed to find codec for {}, falling back to using stream", baseType);
279 element.setTextContent(String.valueOf(nodeValue));
285 private static void writeIdentifierWithNamespacePrefix(Element element, StringBuilder textContent, QName qName,
286 Map<String, String> prefixes) {
287 String namespace = qName.getNamespace().toString();
288 String prefix = prefixes.get(namespace);
289 if (prefix == null) {
290 prefix = qName.getPrefix();
291 if (prefix == null || prefix.isEmpty() || prefixes.containsValue(prefix)) {
292 prefix = generateNewPrefix(prefixes.values());
296 element.setAttribute("xmlns:" + prefix, namespace.toString());
297 textContent.append(prefix);
298 prefixes.put(namespace, prefix);
300 textContent.append(":");
301 textContent.append(qName.getLocalName());
304 private static String generateNewPrefix(Collection<String> prefixes) {
305 StringBuilder result = null;
306 Random random = new Random();
308 result = new StringBuilder();
309 for (int i = 0; i < 4; i++) {
310 int randomNumber = 0x61 + (Math.abs(random.nextInt()) % 26);
311 result.append(Character.toChars(randomNumber));
313 } while (prefixes.contains(result.toString()));
315 return result.toString();
318 public final static TypeDefinition<?> resolveBaseTypeFrom(TypeDefinition<?> type) {
319 TypeDefinition<?> superType = type;
320 while (superType.getBaseType() != null) {
321 superType = superType.getBaseType();
326 private static final DataSchemaNode findFirstSchemaForNode(Node<?> node, Set<DataSchemaNode> dataSchemaNode) {
327 if (dataSchemaNode != null && node != null) {
328 for (DataSchemaNode dsn : dataSchemaNode) {
329 if (node.getNodeType().getLocalName().equals(dsn.getQName().getLocalName())) {
331 } else if (dsn instanceof ChoiceNode) {
332 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
333 DataSchemaNode foundDsn = findFirstSchemaForNode(node, choiceCase.getChildNodes());
334 if (foundDsn != null) {
344 public static Node<?> toDomNode(Element xmlElement, Optional<DataSchemaNode> schema,
345 Optional<XmlCodecProvider> codecProvider) {
346 if (schema.isPresent()) {
347 return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(DEFAULT_XML_VALUE_CODEC_PROVIDER));
349 return toDomNode(xmlElement);
352 public static CompositeNode fromElement(Element xmlElement) {
353 CompositeNodeBuilder<ImmutableCompositeNode> node = ImmutableCompositeNode.builder();
354 node.setQName(qNameFromElement(xmlElement));
356 return node.toInstance();
359 public static QName qNameFromElement(Element xmlElement) {
360 String namespace = xmlElement.getNamespaceURI();
361 String localName = xmlElement.getLocalName();
362 return QName.create(namespace != null ? URI.create(namespace) : null, null, localName);
365 private static Node<?> toNodeWithSchema(Element xmlElement, DataSchemaNode schema, XmlCodecProvider codecProvider) {
366 checkQName(xmlElement, schema.getQName());
367 if (schema instanceof DataNodeContainer) {
368 return toCompositeNodeWithSchema(xmlElement, schema.getQName(), (DataNodeContainer) schema, codecProvider);
369 } else if (schema instanceof LeafSchemaNode) {
370 return toSimpleNodeWithType(xmlElement, (LeafSchemaNode) schema, codecProvider);
371 } else if (schema instanceof LeafListSchemaNode) {
372 return toSimpleNodeWithType(xmlElement, (LeafListSchemaNode) schema, codecProvider);
378 private static Node<?> toSimpleNodeWithType(Element xmlElement, LeafSchemaNode 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();
390 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
391 return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
394 private static Node<?> toSimpleNodeWithType(Element xmlElement, LeafListSchemaNode schema,
395 XmlCodecProvider codecProvider) {
396 TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
397 String text = xmlElement.getTextContent();
400 value = codec.deserialize(text);
403 value = xmlElement.getTextContent();
406 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
407 return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
410 private static Node<?> toCompositeNodeWithSchema(Element xmlElement, QName qName, DataNodeContainer schema,
411 XmlCodecProvider codecProvider) {
412 List<Node<?>> values = toDomNodes(xmlElement, Optional.fromNullable(schema.getChildNodes()));
413 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
414 return ImmutableCompositeNode.create(qName, values, modifyAction.orNull());
417 public static final QName OPERATION_ATTRIBUTE_QNAME = QName.create(URI.create("urn:ietf:params:xml:ns:netconf:base:1.0"), null, "operation");
419 public static Optional<ModifyAction> getModifyOperationFromAttributes(Element xmlElement) {
420 Attr attributeNodeNS = xmlElement.getAttributeNodeNS(OPERATION_ATTRIBUTE_QNAME.getNamespace().toString(), OPERATION_ATTRIBUTE_QNAME.getLocalName());
421 if(attributeNodeNS == null)
422 return Optional.absent();
424 ModifyAction action = ModifyAction.fromXmlValue(attributeNodeNS.getValue());
425 Preconditions.checkArgument(action.isOnElementPermitted(), "Unexpected operation %s on %s", action, xmlElement);
427 return Optional.of(action);
430 private static void checkQName(Element xmlElement, QName qName) {
431 checkState(Objects.equal(xmlElement.getNamespaceURI(), qName.getNamespace().toString()));
432 checkState(qName.getLocalName().equals(xmlElement.getLocalName()));
435 public static final Optional<DataSchemaNode> findFirstSchema(QName qname, Set<DataSchemaNode> dataSchemaNode) {
436 if (dataSchemaNode != null && !dataSchemaNode.isEmpty() && qname != null) {
437 for (DataSchemaNode dsn : dataSchemaNode) {
438 if (qname.isEqualWithoutRevision(dsn.getQName())) {
439 return Optional.<DataSchemaNode> of(dsn);
440 } else if (dsn instanceof ChoiceNode) {
441 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
442 Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
443 if (foundDsn != null && foundDsn.isPresent()) {
450 return Optional.absent();
453 public static Node<?> toDomNode(Document doc) {
454 return toDomNode(doc.getDocumentElement());
457 private static Node<?> toDomNode(Element element) {
458 QName qname = qNameFromElement(element);
460 ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
461 NodeList nodes = element.getChildNodes();
462 boolean isSimpleObject = true;
464 for (int i = 0; i < nodes.getLength(); i++) {
465 org.w3c.dom.Node child = nodes.item(i);
466 if (child instanceof Element) {
467 isSimpleObject = false;
468 values.add(toDomNode((Element) child));
470 if (isSimpleObject && child instanceof org.w3c.dom.Text) {
471 value = element.getTextContent();
472 if (!Strings.isNullOrEmpty(value)) {
473 isSimpleObject = true;
477 if (isSimpleObject) {
478 return new SimpleNodeTOImpl<>(qname, null, value);
480 return ImmutableCompositeNode.create(qname, values.build());
483 public static List<Node<?>> toDomNodes(final Element element, final Optional<Set<DataSchemaNode>> context) {
484 return forEachChild(element.getChildNodes(), new Function<Element, Optional<Node<?>>>() {
487 public Optional<Node<?>> apply(Element input) {
488 if (context.isPresent()) {
489 QName partialQName = qNameFromElement(input);
490 Optional<DataSchemaNode> schemaNode = findFirstSchema(partialQName, context.get());
491 if (schemaNode.isPresent()) {
492 return Optional.<Node<?>> fromNullable(//
493 toNodeWithSchema(input, schemaNode.get(), DEFAULT_XML_VALUE_CODEC_PROVIDER));
496 return Optional.<Node<?>> fromNullable(toDomNode(input));
504 * Converts XML Document containing notification data from Netconf device to
505 * Data DOM Nodes. <br>
506 * By specification defined in <a
507 * href="http://tools.ietf.org/search/rfc6020#section-7.14">RFC 6020</a>
508 * there are xml elements containing notifications metadata, like eventTime
509 * or root notification element which specifies namespace for which is
510 * notification defined in yang model. Those elements MUST be stripped off
511 * notifications body. This method returns pure notification body which
512 * begins in element which is equal to notifications name defined in
513 * corresponding yang model. Rest of notification metadata are obfuscated,
514 * thus Data DOM contains only pure notification body.
517 * XML Document containing notification body
518 * @param notifications
519 * Notifications Definition Schema
520 * @return Data DOM Nodes containing xml notification body definition or
521 * <code>null</code> if there is no NotificationDefinition with
522 * Element with equal notification QName defined in XML Document.
524 public static CompositeNode notificationToDomNodes(final Document document,
525 final Optional<Set<NotificationDefinition>> notifications) {
526 if (notifications.isPresent() && (document != null) && (document.getDocumentElement() != null)) {
527 final NodeList originChildNodes = document.getDocumentElement().getChildNodes();
529 for (int i = 0; i < originChildNodes.getLength(); i++) {
530 org.w3c.dom.Node child = originChildNodes.item(i);
531 if (child instanceof Element) {
532 final Element childElement = (Element) child;
533 final QName partialQName = qNameFromElement(childElement);
534 final Optional<NotificationDefinition> notificationDef = findNotification(partialQName,
535 notifications.get());
536 if (notificationDef.isPresent()) {
537 final Set<DataSchemaNode> dataNodes = notificationDef.get().getChildNodes();
538 final List<Node<?>> domNodes = toDomNodes(childElement,
539 Optional.<Set<DataSchemaNode>> fromNullable(dataNodes));
540 return ImmutableCompositeNode.create(notificationDef.get().getQName(), domNodes);
548 private static Optional<NotificationDefinition> findNotification(final QName notifName,
549 final Set<NotificationDefinition> notifications) {
550 if ((notifName != null) && (notifications != null)) {
551 for (final NotificationDefinition notification : notifications) {
552 if ((notification != null) && notifName.isEqualWithoutRevision(notification.getQName())) {
553 return Optional.<NotificationDefinition>fromNullable(notification);
557 return Optional.<NotificationDefinition>absent();
560 private static final <T> List<T> forEachChild(NodeList nodes, Function<Element, Optional<T>> forBody) {
561 ImmutableList.Builder<T> ret = ImmutableList.<T> builder();
562 for (int i = 0; i < nodes.getLength(); i++) {
563 org.w3c.dom.Node child = nodes.item(i);
564 if (child instanceof Element) {
565 Optional<T> result = forBody.apply((Element) child);
566 if (result.isPresent()) {
567 ret.add(result.get());
574 public static final XmlCodecProvider defaultValueCodecProvider() {
575 return DEFAULT_XML_VALUE_CODEC_PROVIDER;