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 com.google.common.collect.Maps;
27 import org.opendaylight.yangtools.yang.common.QName;
28 import org.opendaylight.yangtools.yang.data.api.*;
29 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
30 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeWithValue;
31 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
32 import org.opendaylight.yangtools.yang.data.api.Node;
33 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
34 import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
35 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
36 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
37 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
38 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
39 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
41 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
46 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
48 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
49 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
54 import com.google.common.base.Function;
55 import com.google.common.base.Objects;
56 import com.google.common.base.Optional;
57 import com.google.common.base.Preconditions;
58 import com.google.common.base.Strings;
59 import com.google.common.collect.ImmutableList;
61 public class XmlDocumentUtils {
63 private static final XmlCodecProvider DEFAULT_XML_VALUE_CODEC_PROVIDER = new XmlCodecProvider() {
66 public TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codecFor(TypeDefinition<?> baseType) {
67 return TypeDefinitionAwareCodec.from(baseType);
71 private static final Logger logger = LoggerFactory.getLogger(XmlDocumentUtils.class);
74 * Converts Data DOM structure to XML Document for specified XML Codec Provider and corresponding
75 * Data Node Container schema. The CompositeNode data parameter enters as root of Data DOM tree and will
76 * be transformed to root in XML Document. Each element of Data DOM tree is compared against specified Data
77 * Node Container Schema and transformed accordingly.
79 * @param data Data DOM root element
80 * @param schema Data Node Container Schema
81 * @param codecProvider XML Codec Provider
82 * @return new instance of XML Document
83 * @throws UnsupportedDataTypeException
85 public static Document toDocument(CompositeNode data, DataNodeContainer schema, XmlCodecProvider codecProvider)
86 throws UnsupportedDataTypeException {
87 Preconditions.checkNotNull(data);
88 Preconditions.checkNotNull(schema);
90 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
91 dbf.setNamespaceAware(true);
94 DocumentBuilder bob = dbf.newDocumentBuilder();
95 doc = bob.newDocument();
96 } catch (ParserConfigurationException e) {
100 if (schema instanceof ContainerSchemaNode || schema instanceof ListSchemaNode) {
101 doc.appendChild(createXmlRootElement(doc, data, (SchemaNode) schema, codecProvider));
104 throw new UnsupportedDataTypeException(
105 "Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
110 * Converts Data DOM structure to XML Document for specified XML Codec Provider. The CompositeNode
111 * data parameter enters as root of Data DOM tree and will be transformed to root in XML Document. The child
112 * nodes of Data Tree are transformed accordingly.
114 * @param data Data DOM root element
115 * @param codecProvider XML Codec Provider
116 * @return new instance of XML Document
117 * @throws UnsupportedDataTypeException
119 public static Document toDocument(CompositeNode data, XmlCodecProvider codecProvider)
120 throws UnsupportedDataTypeException {
121 Preconditions.checkNotNull(data);
123 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
124 dbf.setNamespaceAware(true);
127 DocumentBuilder bob = dbf.newDocumentBuilder();
128 doc = bob.newDocument();
129 } catch (ParserConfigurationException e) {
133 doc.appendChild(createXmlRootElement(doc, data, null, codecProvider));
137 private static Element createXmlRootElement(Document doc, Node<?> data, SchemaNode schema,
138 XmlCodecProvider codecProvider) throws UnsupportedDataTypeException {
139 Element itemEl = createElementFor(doc, data);
140 if (data instanceof SimpleNode<?>) {
141 if (schema instanceof LeafListSchemaNode) {
142 writeValueByType(itemEl, (SimpleNode<?>) data, ((LeafListSchemaNode) schema).getType(),
143 (DataSchemaNode) schema, codecProvider);
144 } else if (schema instanceof LeafSchemaNode) {
145 writeValueByType(itemEl, (SimpleNode<?>) data, ((LeafSchemaNode) schema).getType(),
146 (DataSchemaNode) schema, codecProvider);
148 Object value = data.getValue();
150 itemEl.setTextContent(String.valueOf(value));
153 } else { // CompositeNode
154 for (Node<?> child : ((CompositeNode) data).getChildren()) {
155 DataSchemaNode childSchema = null;
156 if (schema != null) {
157 childSchema = findFirstSchemaForNode(child, ((DataNodeContainer) schema).getChildNodes());
158 if (logger.isDebugEnabled()) {
159 if (childSchema == null) {
160 logger.debug("Probably the data node \""
161 + ((child == null) ? "" : child.getNodeType().getLocalName())
162 + "\" is not conform to schema");
166 itemEl.appendChild(createXmlRootElement(doc, child, childSchema, codecProvider));
172 private static Element createElementFor(Document doc, Node<?> data) {
173 QName dataType = data.getNodeType();
175 if (dataType.getNamespace() != null) {
176 ret = doc.createElementNS(dataType.getNamespace().toString(), dataType.getLocalName());
178 ret = doc.createElementNS(null, dataType.getLocalName());
180 if (data instanceof AttributesContainer && ((AttributesContainer) data).getAttributes() != null) {
181 for (Entry<QName, String> attribute : ((AttributesContainer) data).getAttributes().entrySet()) {
182 ret.setAttributeNS(attribute.getKey().getNamespace().toString(), attribute.getKey().getLocalName(),
183 attribute.getValue());
190 public static void writeValueByType(Element element, SimpleNode<?> node, TypeDefinition<?> type,
191 DataSchemaNode schema, XmlCodecProvider codecProvider) {
192 TypeDefinition<?> baseType = resolveBaseTypeFrom(type);
194 if (baseType instanceof IdentityrefTypeDefinition) {
195 if (node.getValue() instanceof QName) {
196 QName value = (QName) node.getValue();
198 if (value.getPrefix() != null && !value.getPrefix().isEmpty()) {
199 prefix = value.getPrefix();
201 element.setAttribute("xmlns:" + prefix, value.getNamespace().toString());
202 element.setTextContent(prefix + ":" + value.getLocalName());
204 Object value = node.getValue();
205 logger.debug("Value of {}:{} is not instance of QName but is {}", baseType.getQName().getNamespace(),
206 baseType.getQName().getLocalName(), value != null ? value.getClass() : "null");
208 element.setTextContent(String.valueOf(value));
211 } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
212 if (node.getValue() instanceof InstanceIdentifier) {
213 // Map< key = namespace, value = prefix>
214 Map<String, String> prefixes = new HashMap<>();
215 InstanceIdentifier instanceIdentifier = (InstanceIdentifier) node.getValue();
216 StringBuilder textContent = new StringBuilder();
217 for (PathArgument pathArgument : instanceIdentifier.getPath()) {
218 textContent.append("/");
219 writeIdentifierWithNamespacePrefix(element, textContent, pathArgument.getNodeType(), prefixes);
220 if (pathArgument instanceof NodeIdentifierWithPredicates) {
221 Map<QName, Object> predicates = ((NodeIdentifierWithPredicates) pathArgument).getKeyValues();
223 for (QName keyValue : predicates.keySet()) {
224 String predicateValue = String.valueOf(predicates.get(keyValue));
225 textContent.append("[");
226 writeIdentifierWithNamespacePrefix(element, textContent, keyValue, prefixes);
227 textContent.append("='");
228 textContent.append(predicateValue);
229 textContent.append("'");
230 textContent.append("]");
232 } else if (pathArgument instanceof NodeWithValue) {
233 textContent.append("[.='");
234 textContent.append(((NodeWithValue)pathArgument).getValue());
235 textContent.append("'");
236 textContent.append("]");
239 element.setTextContent(textContent.toString());
242 Object value = node.getValue();
243 logger.debug("Value of {}:{} is not instance of InstanceIdentifier but is {}", baseType.getQName()
245 baseType.getQName().getLocalName(), value != null ? value.getClass() : "null");
247 element.setTextContent(String.valueOf(value));
251 if (node.getValue() != null) {
252 final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
255 final String text = codec.serialize(node.getValue());
256 element.setTextContent(text);
257 } catch (ClassCastException e) {
258 logger.error("Provided node {} did not have type {} required by mapping. Using stream instead.", node, baseType, e);
259 element.setTextContent(String.valueOf(node.getValue()));
262 logger.error("Failed to find codec for {}, falling back to using stream", baseType);
263 element.setTextContent(String.valueOf(node.getValue()));
269 private static void writeIdentifierWithNamespacePrefix(Element element, StringBuilder textContent, QName qName,
270 Map<String, String> prefixes) {
271 String namespace = qName.getNamespace().toString();
272 String prefix = prefixes.get(namespace);
273 if (prefix == null) {
274 prefix = qName.getPrefix();
275 if (prefix == null || prefix.isEmpty() || prefixes.containsValue(prefix)) {
276 prefix = generateNewPrefix(prefixes.values());
280 element.setAttribute("xmlns:" + prefix, namespace.toString());
281 textContent.append(prefix);
282 prefixes.put(namespace, prefix);
284 textContent.append(":");
285 textContent.append(qName.getLocalName());
288 private static String generateNewPrefix(Collection<String> prefixes) {
289 StringBuilder result = null;
290 Random random = new Random();
292 result = new StringBuilder();
293 for (int i = 0; i < 4; i++) {
294 int randomNumber = 0x61 + (Math.abs(random.nextInt()) % 26);
295 result.append(Character.toChars(randomNumber));
297 } while (prefixes.contains(result.toString()));
299 return result.toString();
302 public final static TypeDefinition<?> resolveBaseTypeFrom(TypeDefinition<?> type) {
303 TypeDefinition<?> superType = type;
304 while (superType.getBaseType() != null) {
305 superType = superType.getBaseType();
310 private static final DataSchemaNode findFirstSchemaForNode(Node<?> node, Set<DataSchemaNode> dataSchemaNode) {
311 if (dataSchemaNode != null && node != null) {
312 for (DataSchemaNode dsn : dataSchemaNode) {
313 if (node.getNodeType().getLocalName().equals(dsn.getQName().getLocalName())) {
315 } else if (dsn instanceof ChoiceNode) {
316 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
317 DataSchemaNode foundDsn = findFirstSchemaForNode(node, choiceCase.getChildNodes());
318 if (foundDsn != null) {
328 public static Node<?> toDomNode(Element xmlElement, Optional<DataSchemaNode> schema,
329 Optional<XmlCodecProvider> codecProvider) {
330 if (schema.isPresent()) {
331 return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(DEFAULT_XML_VALUE_CODEC_PROVIDER));
333 return toDomNode(xmlElement);
336 public static CompositeNode fromElement(Element xmlElement) {
337 CompositeNodeBuilder<ImmutableCompositeNode> node = ImmutableCompositeNode.builder();
338 node.setQName(qNameFromElement(xmlElement));
340 return node.toInstance();
343 private static QName qNameFromElement(Element xmlElement) {
344 String namespace = xmlElement.getNamespaceURI();
345 String localName = xmlElement.getLocalName();
346 return QName.create(namespace != null ? URI.create(namespace) : null, null, localName);
349 private static Node<?> toNodeWithSchema(Element xmlElement, DataSchemaNode schema, XmlCodecProvider codecProvider) {
350 checkQName(xmlElement, schema.getQName());
351 if (schema instanceof DataNodeContainer) {
352 return toCompositeNodeWithSchema(xmlElement, schema.getQName(), (DataNodeContainer) schema, codecProvider);
353 } else if (schema instanceof LeafSchemaNode) {
354 return toSimpleNodeWithType(xmlElement, (LeafSchemaNode) schema, codecProvider);
355 } else if (schema instanceof LeafListSchemaNode) {
356 return toSimpleNodeWithType(xmlElement, (LeafListSchemaNode) schema, codecProvider);
362 private static Node<?> toSimpleNodeWithType(Element xmlElement, LeafSchemaNode schema,
363 XmlCodecProvider codecProvider) {
364 TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
365 String text = xmlElement.getTextContent();
368 value = codec.deserialize(text);
371 value = xmlElement.getTextContent();
374 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
375 return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
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();
390 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
391 return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
394 private static Node<?> toCompositeNodeWithSchema(Element xmlElement, QName qName, DataNodeContainer schema,
395 XmlCodecProvider codecProvider) {
396 List<Node<?>> values = toDomNodes(xmlElement, Optional.fromNullable(schema.getChildNodes()));
397 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
398 return ImmutableCompositeNode.create(qName, values, modifyAction.orNull());
401 public static final QName OPERATION_ATTRIBUTE_QNAME = QName.create(URI.create("urn:ietf:params:xml:ns:netconf:base:1.0"), null, "operation");
403 public static Optional<ModifyAction> getModifyOperationFromAttributes(Element xmlElement) {
404 Attr attributeNodeNS = xmlElement.getAttributeNodeNS(OPERATION_ATTRIBUTE_QNAME.getNamespace().toString(), OPERATION_ATTRIBUTE_QNAME.getLocalName());
405 if(attributeNodeNS == null)
406 return Optional.absent();
408 ModifyAction action = ModifyAction.fromXmlValue(attributeNodeNS.getValue());
409 Preconditions.checkArgument(action.isOnElementPermitted(), "Unexpected operation %s on %s", action, xmlElement);
411 return Optional.of(action);
414 private static void checkQName(Element xmlElement, QName qName) {
415 checkState(Objects.equal(xmlElement.getNamespaceURI(), qName.getNamespace().toString()));
416 checkState(qName.getLocalName().equals(xmlElement.getLocalName()));
419 private static final Optional<DataSchemaNode> findFirstSchema(QName qname, Set<DataSchemaNode> dataSchemaNode) {
420 if (dataSchemaNode != null && !dataSchemaNode.isEmpty() && qname != null) {
421 for (DataSchemaNode dsn : dataSchemaNode) {
422 if (qname.isEqualWithoutRevision(dsn.getQName())) {
423 return Optional.<DataSchemaNode> of(dsn);
424 } else if (dsn instanceof ChoiceNode) {
425 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
426 Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
427 if (foundDsn != null && foundDsn.isPresent()) {
434 return Optional.absent();
437 public static Node<?> toDomNode(Document doc) {
438 return toDomNode(doc.getDocumentElement());
441 private static Node<?> toDomNode(Element element) {
442 QName qname = qNameFromElement(element);
444 ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
445 NodeList nodes = element.getChildNodes();
446 boolean isSimpleObject = true;
448 for (int i = 0; i < nodes.getLength(); i++) {
449 org.w3c.dom.Node child = nodes.item(i);
450 if (child instanceof Element) {
451 isSimpleObject = false;
452 values.add(toDomNode((Element) child));
454 if (isSimpleObject && child instanceof org.w3c.dom.Text) {
455 value = element.getTextContent();
456 if (!Strings.isNullOrEmpty(value)) {
457 isSimpleObject = true;
461 if (isSimpleObject) {
462 return new SimpleNodeTOImpl<>(qname, null, value);
464 return ImmutableCompositeNode.create(qname, values.build());
467 public static List<Node<?>> toDomNodes(final Element element, final Optional<Set<DataSchemaNode>> context) {
468 return forEachChild(element.getChildNodes(), new Function<Element, Optional<Node<?>>>() {
471 public Optional<Node<?>> apply(Element input) {
472 if (context.isPresent()) {
473 QName partialQName = qNameFromElement(input);
474 Optional<DataSchemaNode> schemaNode = findFirstSchema(partialQName, context.get());
475 if (schemaNode.isPresent()) {
476 return Optional.<Node<?>> fromNullable(//
477 toNodeWithSchema(input, schemaNode.get(), DEFAULT_XML_VALUE_CODEC_PROVIDER));
480 return Optional.<Node<?>> fromNullable(toDomNode(input));
488 * Converts XML Document containing notification data from Netconf device to
489 * Data DOM Nodes. <br>
490 * By specification defined in <a
491 * href="http://tools.ietf.org/search/rfc6020#section-7.14">RFC 6020</a>
492 * there are xml elements containing notifications metadata, like eventTime
493 * or root notification element which specifies namespace for which is
494 * notification defined in yang model. Those elements MUST be stripped off
495 * notifications body. This method returns pure notification body which
496 * begins in element which is equal to notifications name defined in
497 * corresponding yang model. Rest of notification metadata are obfuscated,
498 * thus Data DOM contains only pure notification body.
501 * XML Document containing notification body
502 * @param notifications
503 * Notifications Definition Schema
504 * @return Data DOM Nodes containing xml notification body definition or
505 * <code>null</code> if there is no NotificationDefinition with
506 * Element with equal notification QName defined in XML Document.
508 public static CompositeNode notificationToDomNodes(final Document document,
509 final Optional<Set<NotificationDefinition>> notifications) {
510 if (notifications.isPresent() && (document != null) && (document.getDocumentElement() != null)) {
511 final NodeList originChildNodes = document.getDocumentElement().getChildNodes();
513 for (int i = 0; i < originChildNodes.getLength(); i++) {
514 org.w3c.dom.Node child = originChildNodes.item(i);
515 if (child instanceof Element) {
516 final Element childElement = (Element) child;
517 final QName partialQName = qNameFromElement(childElement);
518 final Optional<NotificationDefinition> notificationDef = findNotification(partialQName,
519 notifications.get());
520 if (notificationDef.isPresent()) {
521 final Set<DataSchemaNode> dataNodes = notificationDef.get().getChildNodes();
522 final List<Node<?>> domNodes = toDomNodes(childElement,
523 Optional.<Set<DataSchemaNode>> fromNullable(dataNodes));
524 return ImmutableCompositeNode.create(notificationDef.get().getQName(), domNodes);
532 private static Optional<NotificationDefinition> findNotification(final QName notifName,
533 final Set<NotificationDefinition> notifications) {
534 if ((notifName != null) && (notifications != null)) {
535 for (final NotificationDefinition notification : notifications) {
536 if ((notification != null) && notifName.isEqualWithoutRevision(notification.getQName())) {
537 return Optional.<NotificationDefinition>fromNullable(notification);
541 return Optional.<NotificationDefinition>absent();
544 private static final <T> List<T> forEachChild(NodeList nodes, Function<Element, Optional<T>> forBody) {
545 ImmutableList.Builder<T> ret = ImmutableList.<T> builder();
546 for (int i = 0; i < nodes.getLength(); i++) {
547 org.w3c.dom.Node child = nodes.item(i);
548 if (child instanceof Element) {
549 Optional<T> result = forBody.apply((Element) child);
550 if (result.isPresent()) {
551 ret.add(result.get());
558 public static final XmlCodecProvider defaultValueCodecProvider() {
559 return DEFAULT_XML_VALUE_CODEC_PROVIDER;