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;
12 import com.google.common.base.Function;
13 import com.google.common.base.Objects;
14 import com.google.common.base.Optional;
15 import com.google.common.base.Preconditions;
16 import com.google.common.base.Strings;
17 import com.google.common.collect.ImmutableList;
20 import java.util.ArrayList;
21 import java.util.List;
23 import java.util.Map.Entry;
26 import javax.activation.UnsupportedDataTypeException;
27 import javax.xml.parsers.DocumentBuilder;
28 import javax.xml.parsers.DocumentBuilderFactory;
29 import javax.xml.parsers.ParserConfigurationException;
31 import org.opendaylight.yangtools.yang.common.QName;
32 import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
33 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
34 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
35 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
36 import org.opendaylight.yangtools.yang.data.api.Node;
37 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
39 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
40 import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
41 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
42 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
43 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
44 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
45 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
47 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
52 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
53 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
55 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
56 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59 import org.w3c.dom.Attr;
60 import org.w3c.dom.Document;
61 import org.w3c.dom.Element;
62 import org.w3c.dom.NodeList;
64 public class XmlDocumentUtils {
66 private static class ElementWithSchemaContext {
68 SchemaContext schemaContext;
70 ElementWithSchemaContext(final Element element,final SchemaContext schemaContext) {
71 this.schemaContext = schemaContext;
72 this.element = element;
75 Element getElement() {
79 SchemaContext getSchemaContext() {
84 private static final XmlCodecProvider DEFAULT_XML_VALUE_CODEC_PROVIDER = new XmlCodecProvider() {
87 public TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codecFor(final TypeDefinition<?> baseType) {
88 return TypeDefinitionAwareCodec.from(baseType);
92 private static final Logger logger = LoggerFactory.getLogger(XmlDocumentUtils.class);
95 * Converts Data DOM structure to XML Document for specified XML Codec Provider and corresponding
96 * Data Node Container schema. The CompositeNode data parameter enters as root of Data DOM tree and will
97 * be transformed to root in XML Document. Each element of Data DOM tree is compared against specified Data
98 * Node Container Schema and transformed accordingly.
100 * @param data Data DOM root element
101 * @param schema Data Node Container Schema
102 * @param codecProvider XML Codec Provider
103 * @return new instance of XML Document
104 * @throws UnsupportedDataTypeException
106 public static Document toDocument(final CompositeNode data, final DataNodeContainer schema, final XmlCodecProvider codecProvider)
107 throws UnsupportedDataTypeException {
108 Preconditions.checkNotNull(data);
109 Preconditions.checkNotNull(schema);
111 Document doc = getDocument();
113 if (schema instanceof ContainerSchemaNode || schema instanceof ListSchemaNode) {
114 doc.appendChild(createXmlRootElement(doc, data, (SchemaNode) schema, codecProvider));
117 throw new UnsupportedDataTypeException(
118 "Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
122 public static Document getDocument() {
123 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
126 DocumentBuilder bob = dbf.newDocumentBuilder();
127 doc = bob.newDocument();
128 } catch (ParserConfigurationException e) {
129 throw new RuntimeException(e);
135 * Converts Data DOM structure to XML Document for specified XML Codec Provider. The CompositeNode
136 * data parameter enters as root of Data DOM tree and will be transformed to root in XML Document. The child
137 * nodes of Data Tree are transformed accordingly.
139 * @param data Data DOM root element
140 * @param codecProvider XML Codec Provider
141 * @return new instance of XML Document
142 * @throws UnsupportedDataTypeException
144 public static Document toDocument(final CompositeNode data, final XmlCodecProvider codecProvider)
145 throws UnsupportedDataTypeException {
146 Preconditions.checkNotNull(data);
148 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
149 dbf.setNamespaceAware(true);
152 DocumentBuilder bob = dbf.newDocumentBuilder();
153 doc = bob.newDocument();
154 } catch (ParserConfigurationException e) {
158 doc.appendChild(createXmlRootElement(doc, data, null, codecProvider));
162 private static Element createXmlRootElement(final Document doc, final Node<?> data, final SchemaNode schema,
163 final XmlCodecProvider codecProvider) throws UnsupportedDataTypeException {
164 Element itemEl = createElementFor(doc, data);
165 if (data instanceof SimpleNode<?>) {
166 if (schema instanceof LeafListSchemaNode) {
167 writeValueByType(itemEl, (SimpleNode<?>) data, ((LeafListSchemaNode) schema).getType(),
168 (DataSchemaNode) schema, codecProvider);
169 } else if (schema instanceof LeafSchemaNode) {
170 writeValueByType(itemEl, (SimpleNode<?>) data, ((LeafSchemaNode) schema).getType(),
171 (DataSchemaNode) schema, codecProvider);
173 Object value = data.getValue();
175 itemEl.setTextContent(String.valueOf(value));
178 } else { // CompositeNode
179 for (Node<?> child : ((CompositeNode) data).getValue()) {
180 DataSchemaNode childSchema = null;
181 if (schema instanceof DataNodeContainer) {
182 childSchema = findFirstSchema(child.getNodeType(), ((DataNodeContainer) schema).getChildNodes()).orNull();
183 if (logger.isDebugEnabled()) {
184 if (childSchema == null) {
185 logger.debug("Probably the data node \""
186 + ((child == null) ? "" : child.getNodeType().getLocalName())
187 + "\" is not conform to schema");
191 itemEl.appendChild(createXmlRootElement(doc, child, childSchema, codecProvider));
197 private static final Element createElementFor(final Document doc, final QName qname, final Object obj) {
199 if (qname.getNamespace() != null) {
200 ret = doc.createElementNS(qname.getNamespace().toString(), qname.getLocalName());
202 ret = doc.createElementNS(null, qname.getLocalName());
205 if (obj instanceof AttributesContainer) {
206 final Map<QName, String> attrs = ((AttributesContainer)obj).getAttributes();
209 for (Entry<QName, String> attribute : attrs.entrySet()) {
210 ret.setAttributeNS(attribute.getKey().getNamespace().toString(), attribute.getKey().getLocalName(),
211 attribute.getValue());
219 public static Element createElementFor(final Document doc, final Node<?> data) {
220 return createElementFor(doc, data.getNodeType(), data);
223 public static Element createElementFor(final Document doc, final NormalizedNode<?, ?> data) {
224 return createElementFor(doc, data.getNodeType(), data);
227 public static void writeValueByType(final Element element, final SimpleNode<?> node, final TypeDefinition<?> type,
228 final DataSchemaNode schema, final XmlCodecProvider codecProvider) {
230 Object nodeValue = node.getValue();
232 writeValueByType(element, type, codecProvider, nodeValue);
235 public static void writeValueByType(final Element element, final TypeDefinition<?> type, final XmlCodecProvider codecProvider, final Object nodeValue) {
236 TypeDefinition<?> baseType = resolveBaseTypeFrom(type);
237 if (baseType instanceof IdentityrefTypeDefinition) {
238 if (nodeValue instanceof QName) {
239 QName value = (QName) nodeValue;
241 if (value.getPrefix() != null && !value.getPrefix().isEmpty()) {
242 prefix = value.getPrefix();
244 element.setAttribute("xmlns:" + prefix, value.getNamespace().toString());
245 element.setTextContent(prefix + ":" + value.getLocalName());
247 Object value = nodeValue;
248 logger.debug("Value of {}:{} is not instance of QName but is {}", baseType.getQName().getNamespace(),
249 baseType.getQName().getLocalName(), value != null ? value.getClass() : "null");
251 element.setTextContent(String.valueOf(value));
254 } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
255 if (nodeValue instanceof InstanceIdentifier) {
256 InstanceIdentifierForXmlCodec.serialize((InstanceIdentifier)nodeValue,element);
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 public final static TypeDefinition<?> resolveBaseTypeFrom(final TypeDefinition<?> type) {
286 TypeDefinition<?> superType = type;
287 while (superType.getBaseType() != null) {
288 superType = superType.getBaseType();
293 public static Node<?> toDomNode(final Element xmlElement, final Optional<DataSchemaNode> schema,
294 final Optional<XmlCodecProvider> codecProvider) {
295 if (schema.isPresent()) {
296 return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(DEFAULT_XML_VALUE_CODEC_PROVIDER));
298 return toDomNode(xmlElement);
301 public static CompositeNode fromElement(final Element xmlElement) {
302 CompositeNodeBuilder<ImmutableCompositeNode> node = ImmutableCompositeNode.builder();
303 node.setQName(qNameFromElement(xmlElement));
305 return node.toInstance();
308 public static QName qNameFromElement(final Element xmlElement) {
309 String namespace = xmlElement.getNamespaceURI();
310 String localName = xmlElement.getLocalName();
311 return QName.create(namespace != null ? URI.create(namespace) : null, null, localName);
314 private static Node<?> toNodeWithSchema(final Element xmlElement, final DataSchemaNode schema, final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
315 checkQName(xmlElement, schema.getQName());
316 if (schema instanceof DataNodeContainer) {
317 return toCompositeNodeWithSchema(xmlElement, schema.getQName(), (DataNodeContainer) schema, codecProvider,schemaCtx);
318 } else if (schema instanceof LeafSchemaNode) {
319 return toSimpleNodeWithType(xmlElement, (LeafSchemaNode) schema, codecProvider,schemaCtx);
320 } else if (schema instanceof LeafListSchemaNode) {
321 return toSimpleNodeWithType(xmlElement, (LeafListSchemaNode) schema, codecProvider,schemaCtx);
326 private static Node<?> toNodeWithSchema(final Element xmlElement, final DataSchemaNode schema, final XmlCodecProvider codecProvider) {
327 return toNodeWithSchema(xmlElement, schema, codecProvider, null);
330 protected static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafSchemaNode schema,
331 final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
332 TypeDefinitionAwareCodec<? extends Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
333 String text = xmlElement.getTextContent();
336 value = codec.deserialize(text);
339 if (schema.getType() instanceof org.opendaylight.yangtools.yang.model.util.InstanceIdentifier) {
340 value = InstanceIdentifierForXmlCodec.deserialize(xmlElement,schemaCtx);
341 } else if(schema.getType() instanceof IdentityrefTypeDefinition){
342 value = InstanceIdentifierForXmlCodec.toIdentity(xmlElement.getTextContent(), xmlElement, schemaCtx);
346 value = xmlElement.getTextContent();
349 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
350 return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
353 private static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafListSchemaNode schema,
354 final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
355 TypeDefinitionAwareCodec<? extends Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
356 String text = xmlElement.getTextContent();
359 value = codec.deserialize(text);
361 if (schema.getType() instanceof org.opendaylight.yangtools.yang.model.util.InstanceIdentifier) {
362 value = InstanceIdentifierForXmlCodec.deserialize(xmlElement,schemaCtx);
365 value = xmlElement.getTextContent();
368 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
369 return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
372 private static Node<?> toCompositeNodeWithSchema(final Element xmlElement, final QName qName, final DataNodeContainer schema,
373 final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
374 List<Node<?>> values = toDomNodes(xmlElement, Optional.fromNullable(schema.getChildNodes()),schemaCtx);
375 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
376 return ImmutableCompositeNode.create(qName, values, modifyAction.orNull());
379 public static final QName OPERATION_ATTRIBUTE_QNAME = QName.create(URI.create("urn:ietf:params:xml:ns:netconf:base:1.0"), null, "operation");
381 public static Optional<ModifyAction> getModifyOperationFromAttributes(final Element xmlElement) {
382 Attr attributeNodeNS = xmlElement.getAttributeNodeNS(OPERATION_ATTRIBUTE_QNAME.getNamespace().toString(), OPERATION_ATTRIBUTE_QNAME.getLocalName());
383 if(attributeNodeNS == null) {
384 return Optional.absent();
387 ModifyAction action = ModifyAction.fromXmlValue(attributeNodeNS.getValue());
388 Preconditions.checkArgument(action.isOnElementPermitted(), "Unexpected operation %s on %s", action, xmlElement);
390 return Optional.of(action);
393 private static void checkQName(final Element xmlElement, final QName qName) {
394 checkState(Objects.equal(xmlElement.getNamespaceURI(), qName.getNamespace().toString()));
395 checkState(qName.getLocalName().equals(xmlElement.getLocalName()));
398 public static final Optional<DataSchemaNode> findFirstSchema(final QName qname, final Set<DataSchemaNode> dataSchemaNode) {
399 if (dataSchemaNode != null && !dataSchemaNode.isEmpty() && qname != null) {
400 for (DataSchemaNode dsn : dataSchemaNode) {
401 if (qname.isEqualWithoutRevision(dsn.getQName())) {
402 return Optional.<DataSchemaNode> of(dsn);
403 } else if (dsn instanceof ChoiceNode) {
404 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
405 Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
406 if (foundDsn != null && foundDsn.isPresent()) {
413 return Optional.absent();
416 public static Node<?> toDomNode(final Document doc) {
417 return toDomNode(doc.getDocumentElement());
420 private static Node<?> toDomNode(final Element element) {
421 QName qname = qNameFromElement(element);
423 ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
424 NodeList nodes = element.getChildNodes();
425 boolean isSimpleObject = true;
427 for (int i = 0; i < nodes.getLength(); i++) {
428 org.w3c.dom.Node child = nodes.item(i);
429 if (child instanceof Element) {
430 isSimpleObject = false;
431 values.add(toDomNode((Element) child));
433 if (isSimpleObject && child instanceof org.w3c.dom.Text) {
434 value = element.getTextContent();
435 if (!Strings.isNullOrEmpty(value)) {
436 isSimpleObject = true;
440 if (isSimpleObject) {
441 return new SimpleNodeTOImpl<>(qname, null, value);
443 return ImmutableCompositeNode.create(qname, values.build());
446 public static List<Node<?>> toDomNodes(final Element element, final Optional<Set<DataSchemaNode>> context,final SchemaContext schemaCtx) {
447 return forEachChild(element.getChildNodes(),schemaCtx, new Function<ElementWithSchemaContext, Optional<Node<?>>>() {
450 public Optional<Node<?>> apply(final ElementWithSchemaContext input) {
451 if (context.isPresent()) {
452 QName partialQName = qNameFromElement(input.getElement());
453 Optional<DataSchemaNode> schemaNode = findFirstSchema(partialQName, context.get());
454 if (schemaNode.isPresent()) {
455 return Optional.<Node<?>> fromNullable(//
456 toNodeWithSchema(input.getElement(), schemaNode.get(), DEFAULT_XML_VALUE_CODEC_PROVIDER,input.getSchemaContext()));
459 return Optional.<Node<?>> fromNullable(toDomNode(input.getElement()));
466 public static List<Node<?>> toDomNodes(final Element element, final Optional<Set<DataSchemaNode>> context) {
467 return toDomNodes(element,context,null);
471 * Converts XML Document containing notification data from Netconf device to
472 * Data DOM Nodes. <br>
473 * By specification defined in <a
474 * href="http://tools.ietf.org/search/rfc6020#section-7.14">RFC 6020</a>
475 * there are xml elements containing notifications metadata, like eventTime
476 * or root notification element which specifies namespace for which is
477 * notification defined in yang model. Those elements MUST be stripped off
478 * notifications body. This method returns pure notification body which
479 * begins in element which is equal to notifications name defined in
480 * corresponding yang model. Rest of notification metadata are obfuscated,
481 * thus Data DOM contains only pure notification body.
484 * XML Document containing notification body
485 * @param notifications
486 * Notifications Definition Schema
487 * @return Data DOM Nodes containing xml notification body definition or
488 * <code>null</code> if there is no NotificationDefinition with
489 * Element with equal notification QName defined in XML Document.
491 public static CompositeNode notificationToDomNodes(final Document document,
492 final Optional<Set<NotificationDefinition>> notifications, final SchemaContext schemaCtx) {
493 if (notifications.isPresent() && (document != null) && (document.getDocumentElement() != null)) {
494 final NodeList originChildNodes = document.getDocumentElement().getChildNodes();
495 for (int i = 0; i < originChildNodes.getLength(); i++) {
496 org.w3c.dom.Node child = originChildNodes.item(i);
497 if (child instanceof Element) {
498 final Element childElement = (Element) child;
499 final QName partialQName = qNameFromElement(childElement);
500 final Optional<NotificationDefinition> notificationDef = findNotification(partialQName,
501 notifications.get());
502 if (notificationDef.isPresent()) {
503 final Set<DataSchemaNode> dataNodes = notificationDef.get().getChildNodes();
504 final List<Node<?>> domNodes = toDomNodes(childElement,
505 Optional.<Set<DataSchemaNode>> fromNullable(dataNodes),schemaCtx);
506 return ImmutableCompositeNode.create(notificationDef.get().getQName(), domNodes);
514 public static CompositeNode notificationToDomNodes(final Document document,
515 final Optional<Set<NotificationDefinition>> notifications) {
516 return notificationToDomNodes(document, notifications,null);
519 private static Optional<NotificationDefinition> findNotification(final QName notifName,
520 final Set<NotificationDefinition> notifications) {
521 if ((notifName != null) && (notifications != null)) {
522 for (final NotificationDefinition notification : notifications) {
523 if ((notification != null) && notifName.isEqualWithoutRevision(notification.getQName())) {
524 return Optional.<NotificationDefinition>fromNullable(notification);
528 return Optional.<NotificationDefinition>absent();
531 private static final <T> List<T> forEachChild(final NodeList nodes, final SchemaContext schemaContext, final Function<ElementWithSchemaContext, Optional<T>> forBody) {
532 final int l = nodes.getLength();
534 return ImmutableList.of();
537 final List<T> list = new ArrayList<>(l);
538 for (int i = 0; i < l; i++) {
539 org.w3c.dom.Node child = nodes.item(i);
540 if (child instanceof Element) {
541 Optional<T> result = forBody.apply(new ElementWithSchemaContext((Element) child,schemaContext));
542 if (result.isPresent()) {
543 list.add(result.get());
547 return ImmutableList.copyOf(list);
550 public static final XmlCodecProvider defaultValueCodecProvider() {
551 return DEFAULT_XML_VALUE_CODEC_PROVIDER;