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.ArrayList;
14 import java.util.List;
16 import java.util.Map.Entry;
19 import javax.activation.UnsupportedDataTypeException;
20 import javax.xml.parsers.DocumentBuilder;
21 import javax.xml.parsers.DocumentBuilderFactory;
22 import javax.xml.parsers.ParserConfigurationException;
23 import javax.xml.stream.XMLOutputFactory;
24 import javax.xml.stream.XMLStreamException;
25 import javax.xml.stream.XMLStreamWriter;
26 import javax.xml.transform.dom.DOMResult;
28 import org.opendaylight.yangtools.yang.common.QName;
29 import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
30 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
31 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
32 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
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.api.schema.NormalizedNode;
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.SchemaContext;
50 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
52 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
53 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56 import org.w3c.dom.Attr;
57 import org.w3c.dom.Document;
58 import org.w3c.dom.Element;
59 import org.w3c.dom.NodeList;
61 import com.google.common.base.Function;
62 import com.google.common.base.Objects;
63 import com.google.common.base.Optional;
64 import com.google.common.base.Preconditions;
65 import com.google.common.base.Strings;
66 import com.google.common.collect.ImmutableList;
68 public class XmlDocumentUtils {
69 private static class ElementWithSchemaContext {
71 SchemaContext schemaContext;
73 ElementWithSchemaContext(final Element element,final SchemaContext schemaContext) {
74 this.schemaContext = schemaContext;
75 this.element = element;
78 Element getElement() {
82 SchemaContext getSchemaContext() {
87 public static final QName OPERATION_ATTRIBUTE_QNAME = QName.create(URI.create("urn:ietf:params:xml:ns:netconf:base:1.0"), null, "operation");
88 private static final Logger logger = LoggerFactory.getLogger(XmlDocumentUtils.class);
89 private static final XMLOutputFactory FACTORY = XMLOutputFactory.newFactory();
90 private static final XmlCodecProvider DEFAULT_XML_VALUE_CODEC_PROVIDER = new XmlCodecProvider() {
92 public TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codecFor(final TypeDefinition<?> baseType) {
93 return TypeDefinitionAwareCodec.from(baseType);
98 * Converts Data DOM structure to XML Document for specified XML Codec Provider and corresponding
99 * Data Node Container schema. The CompositeNode data parameter enters as root of Data DOM tree and will
100 * be transformed to root in XML Document. Each element of Data DOM tree is compared against specified Data
101 * Node Container Schema and transformed accordingly.
103 * @param data Data DOM root element
104 * @param schema Data Node Container Schema
105 * @param codecProvider XML Codec Provider
106 * @return new instance of XML Document
107 * @throws UnsupportedDataTypeException
109 public static Document toDocument(final CompositeNode data, final DataNodeContainer schema, final XmlCodecProvider codecProvider)
110 throws UnsupportedDataTypeException {
111 Preconditions.checkNotNull(data);
112 Preconditions.checkNotNull(schema);
114 if (!(schema instanceof ContainerSchemaNode || schema instanceof ListSchemaNode)) {
115 throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
118 final DOMResult result = new DOMResult();
119 result.setNode(getDocument());
121 final XMLStreamWriter writer = FACTORY.createXMLStreamWriter(result);
122 XmlStreamUtils.create(codecProvider).writeDocument(writer, data, (SchemaNode)schema);
124 return (Document)result.getNode();
125 } catch (XMLStreamException e) {
126 logger.error("Failed to serialize data {}", data, e);
131 public static Document getDocument() {
132 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
135 DocumentBuilder bob = dbf.newDocumentBuilder();
136 doc = bob.newDocument();
137 } catch (ParserConfigurationException e) {
138 throw new RuntimeException(e);
144 * Converts Data DOM structure to XML Document for specified XML Codec Provider. The CompositeNode
145 * data parameter enters as root of Data DOM tree and will be transformed to root in XML Document. The child
146 * nodes of Data Tree are transformed accordingly.
148 * @param data Data DOM root element
149 * @param codecProvider XML Codec Provider
150 * @return new instance of XML Document
151 * @throws UnsupportedDataTypeException
153 public static Document toDocument(final CompositeNode data, final XmlCodecProvider codecProvider) {
154 final DOMResult result = new DOMResult();
156 final XMLStreamWriter writer = FACTORY.createXMLStreamWriter(result);
157 XmlStreamUtils.create(codecProvider).writeDocument(writer, data);
159 return (Document)result.getNode();
160 } catch (XMLStreamException e) {
161 logger.error("Failed to serialize data {}", data, e);
166 private static final Element createElementFor(final Document doc, final QName qname, final Object obj) {
168 if (qname.getNamespace() != null) {
169 ret = doc.createElementNS(qname.getNamespace().toString(), qname.getLocalName());
171 ret = doc.createElementNS(null, qname.getLocalName());
174 if (obj instanceof AttributesContainer) {
175 final Map<QName, String> attrs = ((AttributesContainer)obj).getAttributes();
178 for (Entry<QName, String> attribute : attrs.entrySet()) {
179 ret.setAttributeNS(attribute.getKey().getNamespace().toString(), attribute.getKey().getLocalName(),
180 attribute.getValue());
188 public static Element createElementFor(final Document doc, final Node<?> data) {
189 return createElementFor(doc, data.getNodeType(), data);
192 public static Element createElementFor(final Document doc, final NormalizedNode<?, ?> data) {
193 return createElementFor(doc, data.getNodeType(), data);
196 public static void writeValueByType(final Element element, final SimpleNode<?> node, final TypeDefinition<?> type,
197 final DataSchemaNode schema, final XmlCodecProvider codecProvider) {
199 Object nodeValue = node.getValue();
201 writeValueByType(element, type, codecProvider, nodeValue);
204 public static void writeValueByType(final Element element, final TypeDefinition<?> type, final XmlCodecProvider codecProvider, final Object nodeValue) {
205 TypeDefinition<?> baseType = resolveBaseTypeFrom(type);
206 if (baseType instanceof IdentityrefTypeDefinition) {
207 if (nodeValue instanceof QName) {
208 QName value = (QName) nodeValue;
210 if (value.getPrefix() != null && !value.getPrefix().isEmpty()) {
211 prefix = value.getPrefix();
213 element.setAttribute("xmlns:" + prefix, value.getNamespace().toString());
214 element.setTextContent(prefix + ":" + value.getLocalName());
216 Object value = nodeValue;
217 logger.debug("Value of {}:{} is not instance of QName but is {}", baseType.getQName().getNamespace(),
218 baseType.getQName().getLocalName(), value != null ? value.getClass() : "null");
220 element.setTextContent(String.valueOf(value));
223 } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
224 if (nodeValue instanceof InstanceIdentifier) {
225 InstanceIdentifierForXmlCodec.serialize((InstanceIdentifier)nodeValue,element);
227 Object value = nodeValue;
228 logger.debug("Value of {}:{} is not instance of InstanceIdentifier but is {}", baseType.getQName()
230 baseType.getQName().getLocalName(), value != null ? value.getClass() : "null");
232 element.setTextContent(String.valueOf(value));
236 if (nodeValue != null) {
237 final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
240 final String text = codec.serialize(nodeValue);
241 element.setTextContent(text);
242 } catch (ClassCastException e) {
243 logger.error("Provided node value {} did not have type {} required by mapping. Using stream instead.", nodeValue, baseType, e);
244 element.setTextContent(String.valueOf(nodeValue));
247 logger.error("Failed to find codec for {}, falling back to using stream", baseType);
248 element.setTextContent(String.valueOf(nodeValue));
254 public final static TypeDefinition<?> resolveBaseTypeFrom(final TypeDefinition<?> type) {
255 TypeDefinition<?> superType = type;
256 while (superType.getBaseType() != null) {
257 superType = superType.getBaseType();
262 public static Node<?> toDomNode(final Element xmlElement, final Optional<DataSchemaNode> schema,
263 final Optional<XmlCodecProvider> codecProvider) {
264 if (schema.isPresent()) {
265 return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(DEFAULT_XML_VALUE_CODEC_PROVIDER));
267 return toDomNode(xmlElement);
270 public static CompositeNode fromElement(final Element xmlElement) {
271 CompositeNodeBuilder<ImmutableCompositeNode> node = ImmutableCompositeNode.builder();
272 node.setQName(qNameFromElement(xmlElement));
274 return node.toInstance();
277 public static QName qNameFromElement(final Element xmlElement) {
278 String namespace = xmlElement.getNamespaceURI();
279 String localName = xmlElement.getLocalName();
280 return QName.create(namespace != null ? URI.create(namespace) : null, null, localName);
283 private static Node<?> toNodeWithSchema(final Element xmlElement, final DataSchemaNode schema, final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
284 checkQName(xmlElement, schema.getQName());
285 if (schema instanceof DataNodeContainer) {
286 return toCompositeNodeWithSchema(xmlElement, schema.getQName(), (DataNodeContainer) schema, codecProvider,schemaCtx);
287 } else if (schema instanceof LeafSchemaNode) {
288 return toSimpleNodeWithType(xmlElement, (LeafSchemaNode) schema, codecProvider,schemaCtx);
289 } else if (schema instanceof LeafListSchemaNode) {
290 return toSimpleNodeWithType(xmlElement, (LeafListSchemaNode) schema, codecProvider,schemaCtx);
295 private static Node<?> toNodeWithSchema(final Element xmlElement, final DataSchemaNode schema, final XmlCodecProvider codecProvider) {
296 return toNodeWithSchema(xmlElement, schema, codecProvider, null);
299 protected static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafSchemaNode schema,
300 final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
301 TypeDefinitionAwareCodec<? extends Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
302 String text = xmlElement.getTextContent();
305 value = codec.deserialize(text);
308 if (schema.getType() instanceof org.opendaylight.yangtools.yang.model.util.InstanceIdentifier) {
309 value = InstanceIdentifierForXmlCodec.deserialize(xmlElement,schemaCtx);
310 } else if(schema.getType() instanceof IdentityrefTypeDefinition){
311 value = InstanceIdentifierForXmlCodec.toIdentity(xmlElement.getTextContent(), xmlElement, schemaCtx);
315 value = xmlElement.getTextContent();
318 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
319 return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
322 private static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafListSchemaNode schema,
323 final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
324 TypeDefinitionAwareCodec<? extends Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
325 String text = xmlElement.getTextContent();
328 value = codec.deserialize(text);
330 if (schema.getType() instanceof org.opendaylight.yangtools.yang.model.util.InstanceIdentifier) {
331 value = InstanceIdentifierForXmlCodec.deserialize(xmlElement,schemaCtx);
334 value = xmlElement.getTextContent();
337 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
338 return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
341 private static Node<?> toCompositeNodeWithSchema(final Element xmlElement, final QName qName, final DataNodeContainer schema,
342 final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
343 List<Node<?>> values = toDomNodes(xmlElement, Optional.fromNullable(schema.getChildNodes()),schemaCtx);
344 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
345 return ImmutableCompositeNode.create(qName, values, modifyAction.orNull());
348 public static Optional<ModifyAction> getModifyOperationFromAttributes(final Element xmlElement) {
349 Attr attributeNodeNS = xmlElement.getAttributeNodeNS(OPERATION_ATTRIBUTE_QNAME.getNamespace().toString(), OPERATION_ATTRIBUTE_QNAME.getLocalName());
350 if(attributeNodeNS == null) {
351 return Optional.absent();
354 ModifyAction action = ModifyAction.fromXmlValue(attributeNodeNS.getValue());
355 Preconditions.checkArgument(action.isOnElementPermitted(), "Unexpected operation %s on %s", action, xmlElement);
357 return Optional.of(action);
360 private static void checkQName(final Element xmlElement, final QName qName) {
361 checkState(Objects.equal(xmlElement.getNamespaceURI(), qName.getNamespace().toString()));
362 checkState(qName.getLocalName().equals(xmlElement.getLocalName()));
365 public static final Optional<DataSchemaNode> findFirstSchema(final QName qname, final Set<DataSchemaNode> dataSchemaNode) {
366 if (dataSchemaNode != null && !dataSchemaNode.isEmpty() && qname != null) {
367 for (DataSchemaNode dsn : dataSchemaNode) {
368 if (qname.isEqualWithoutRevision(dsn.getQName())) {
369 return Optional.<DataSchemaNode> of(dsn);
370 } else if (dsn instanceof ChoiceNode) {
371 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
372 Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
373 if (foundDsn != null && foundDsn.isPresent()) {
380 return Optional.absent();
383 public static Node<?> toDomNode(final Document doc) {
384 return toDomNode(doc.getDocumentElement());
387 private static Node<?> toDomNode(final Element element) {
388 QName qname = qNameFromElement(element);
390 ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
391 NodeList nodes = element.getChildNodes();
392 boolean isSimpleObject = true;
394 for (int i = 0; i < nodes.getLength(); i++) {
395 org.w3c.dom.Node child = nodes.item(i);
396 if (child instanceof Element) {
397 isSimpleObject = false;
398 values.add(toDomNode((Element) child));
400 if (isSimpleObject && child instanceof org.w3c.dom.Text) {
401 value = element.getTextContent();
402 if (!Strings.isNullOrEmpty(value)) {
403 isSimpleObject = true;
407 if (isSimpleObject) {
408 return new SimpleNodeTOImpl<>(qname, null, value);
410 return ImmutableCompositeNode.create(qname, values.build());
413 public static List<Node<?>> toDomNodes(final Element element, final Optional<Set<DataSchemaNode>> context,final SchemaContext schemaCtx) {
414 return forEachChild(element.getChildNodes(),schemaCtx, new Function<ElementWithSchemaContext, Optional<Node<?>>>() {
417 public Optional<Node<?>> apply(final ElementWithSchemaContext input) {
418 if (context.isPresent()) {
419 QName partialQName = qNameFromElement(input.getElement());
420 Optional<DataSchemaNode> schemaNode = findFirstSchema(partialQName, context.get());
421 if (schemaNode.isPresent()) {
422 return Optional.<Node<?>> fromNullable(//
423 toNodeWithSchema(input.getElement(), schemaNode.get(), DEFAULT_XML_VALUE_CODEC_PROVIDER,input.getSchemaContext()));
426 return Optional.<Node<?>> fromNullable(toDomNode(input.getElement()));
433 public static List<Node<?>> toDomNodes(final Element element, final Optional<Set<DataSchemaNode>> context) {
434 return toDomNodes(element,context,null);
438 * Converts XML Document containing notification data from Netconf device to
439 * Data DOM Nodes. <br>
440 * By specification defined in <a
441 * href="http://tools.ietf.org/search/rfc6020#section-7.14">RFC 6020</a>
442 * there are xml elements containing notifications metadata, like eventTime
443 * or root notification element which specifies namespace for which is
444 * notification defined in yang model. Those elements MUST be stripped off
445 * notifications body. This method returns pure notification body which
446 * begins in element which is equal to notifications name defined in
447 * corresponding yang model. Rest of notification metadata are obfuscated,
448 * thus Data DOM contains only pure notification body.
451 * XML Document containing notification body
452 * @param notifications
453 * Notifications Definition Schema
454 * @return Data DOM Nodes containing xml notification body definition or
455 * <code>null</code> if there is no NotificationDefinition with
456 * Element with equal notification QName defined in XML Document.
458 public static CompositeNode notificationToDomNodes(final Document document,
459 final Optional<Set<NotificationDefinition>> notifications, final SchemaContext schemaCtx) {
460 if (notifications.isPresent() && (document != null) && (document.getDocumentElement() != null)) {
461 final NodeList originChildNodes = document.getDocumentElement().getChildNodes();
462 for (int i = 0; i < originChildNodes.getLength(); i++) {
463 org.w3c.dom.Node child = originChildNodes.item(i);
464 if (child instanceof Element) {
465 final Element childElement = (Element) child;
466 final QName partialQName = qNameFromElement(childElement);
467 final Optional<NotificationDefinition> notificationDef = findNotification(partialQName,
468 notifications.get());
469 if (notificationDef.isPresent()) {
470 final Set<DataSchemaNode> dataNodes = notificationDef.get().getChildNodes();
471 final List<Node<?>> domNodes = toDomNodes(childElement,
472 Optional.<Set<DataSchemaNode>> fromNullable(dataNodes),schemaCtx);
473 return ImmutableCompositeNode.create(notificationDef.get().getQName(), domNodes);
481 public static CompositeNode notificationToDomNodes(final Document document,
482 final Optional<Set<NotificationDefinition>> notifications) {
483 return notificationToDomNodes(document, notifications,null);
486 private static Optional<NotificationDefinition> findNotification(final QName notifName,
487 final Set<NotificationDefinition> notifications) {
488 if ((notifName != null) && (notifications != null)) {
489 for (final NotificationDefinition notification : notifications) {
490 if ((notification != null) && notifName.isEqualWithoutRevision(notification.getQName())) {
491 return Optional.<NotificationDefinition>fromNullable(notification);
495 return Optional.<NotificationDefinition>absent();
498 private static final <T> List<T> forEachChild(final NodeList nodes, final SchemaContext schemaContext, final Function<ElementWithSchemaContext, Optional<T>> forBody) {
499 final int l = nodes.getLength();
501 return ImmutableList.of();
504 final List<T> list = new ArrayList<>(l);
505 for (int i = 0; i < l; i++) {
506 org.w3c.dom.Node child = nodes.item(i);
507 if (child instanceof Element) {
508 Optional<T> result = forBody.apply(new ElementWithSchemaContext((Element) child,schemaContext));
509 if (result.isPresent()) {
510 list.add(result.get());
514 return ImmutableList.copyOf(list);
517 public static final XmlCodecProvider defaultValueCodecProvider() {
518 return DEFAULT_XML_VALUE_CODEC_PROVIDER;