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;
30 import javax.xml.stream.XMLOutputFactory;
31 import javax.xml.stream.XMLStreamException;
32 import javax.xml.stream.XMLStreamWriter;
33 import javax.xml.transform.dom.DOMResult;
35 import org.opendaylight.yangtools.yang.common.QName;
36 import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
37 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
38 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
39 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
40 import org.opendaylight.yangtools.yang.data.api.Node;
41 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
43 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
44 import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
45 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
46 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
47 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
48 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
49 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
51 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
56 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
57 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
59 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
60 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63 import org.w3c.dom.Attr;
64 import org.w3c.dom.Document;
65 import org.w3c.dom.Element;
66 import org.w3c.dom.NodeList;
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();
120 final XMLStreamWriter writer = FACTORY.createXMLStreamWriter(result);
121 XmlStreamUtils.create(codecProvider).writeDocument(writer, data, (SchemaNode)schema);
123 return (Document)result.getNode();
124 } catch (XMLStreamException e) {
125 logger.error("Failed to serialize data {}", data, e);
130 public static Document getDocument() {
131 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
134 DocumentBuilder bob = dbf.newDocumentBuilder();
135 doc = bob.newDocument();
136 } catch (ParserConfigurationException e) {
137 throw new RuntimeException(e);
143 * Converts Data DOM structure to XML Document for specified XML Codec Provider. The CompositeNode
144 * data parameter enters as root of Data DOM tree and will be transformed to root in XML Document. The child
145 * nodes of Data Tree are transformed accordingly.
147 * @param data Data DOM root element
148 * @param codecProvider XML Codec Provider
149 * @return new instance of XML Document
150 * @throws UnsupportedDataTypeException
152 public static Document toDocument(final CompositeNode data, final XmlCodecProvider codecProvider) {
153 final DOMResult result = new DOMResult();
155 final XMLStreamWriter writer = FACTORY.createXMLStreamWriter(result);
156 XmlStreamUtils.create(codecProvider).writeDocument(writer, data);
158 return (Document)result.getNode();
159 } catch (XMLStreamException e) {
160 logger.error("Failed to serialize data {}", data, e);
165 private static final Element createElementFor(final Document doc, final QName qname, final Object obj) {
167 if (qname.getNamespace() != null) {
168 ret = doc.createElementNS(qname.getNamespace().toString(), qname.getLocalName());
170 ret = doc.createElementNS(null, qname.getLocalName());
173 if (obj instanceof AttributesContainer) {
174 final Map<QName, String> attrs = ((AttributesContainer)obj).getAttributes();
177 for (Entry<QName, String> attribute : attrs.entrySet()) {
178 ret.setAttributeNS(attribute.getKey().getNamespace().toString(), attribute.getKey().getLocalName(),
179 attribute.getValue());
187 public static Element createElementFor(final Document doc, final Node<?> data) {
188 return createElementFor(doc, data.getNodeType(), data);
191 public static Element createElementFor(final Document doc, final NormalizedNode<?, ?> data) {
192 return createElementFor(doc, data.getNodeType(), data);
195 public static void writeValueByType(final Element element, final SimpleNode<?> node, final TypeDefinition<?> type,
196 final DataSchemaNode schema, final XmlCodecProvider codecProvider) {
198 Object nodeValue = node.getValue();
200 writeValueByType(element, type, codecProvider, nodeValue);
203 public static void writeValueByType(final Element element, final TypeDefinition<?> type, final XmlCodecProvider codecProvider, final Object nodeValue) {
204 TypeDefinition<?> baseType = resolveBaseTypeFrom(type);
205 if (baseType instanceof IdentityrefTypeDefinition) {
206 if (nodeValue instanceof QName) {
207 QName value = (QName) nodeValue;
209 if (value.getPrefix() != null && !value.getPrefix().isEmpty()) {
210 prefix = value.getPrefix();
212 element.setAttribute("xmlns:" + prefix, value.getNamespace().toString());
213 element.setTextContent(prefix + ":" + value.getLocalName());
215 Object value = nodeValue;
216 logger.debug("Value of {}:{} is not instance of QName but is {}", baseType.getQName().getNamespace(),
217 baseType.getQName().getLocalName(), value != null ? value.getClass() : "null");
219 element.setTextContent(String.valueOf(value));
222 } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
223 if (nodeValue instanceof InstanceIdentifier) {
224 InstanceIdentifierForXmlCodec.serialize((InstanceIdentifier)nodeValue,element);
226 Object value = nodeValue;
227 logger.debug("Value of {}:{} is not instance of InstanceIdentifier but is {}", baseType.getQName()
229 baseType.getQName().getLocalName(), value != null ? value.getClass() : "null");
231 element.setTextContent(String.valueOf(value));
235 if (nodeValue != null) {
236 final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
239 final String text = codec.serialize(nodeValue);
240 element.setTextContent(text);
241 } catch (ClassCastException e) {
242 logger.error("Provided node value {} did not have type {} required by mapping. Using stream instead.", nodeValue, baseType, e);
243 element.setTextContent(String.valueOf(nodeValue));
246 logger.error("Failed to find codec for {}, falling back to using stream", baseType);
247 element.setTextContent(String.valueOf(nodeValue));
253 public final static TypeDefinition<?> resolveBaseTypeFrom(final TypeDefinition<?> type) {
254 TypeDefinition<?> superType = type;
255 while (superType.getBaseType() != null) {
256 superType = superType.getBaseType();
261 public static Node<?> toDomNode(final Element xmlElement, final Optional<DataSchemaNode> schema,
262 final Optional<XmlCodecProvider> codecProvider) {
263 if (schema.isPresent()) {
264 return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(DEFAULT_XML_VALUE_CODEC_PROVIDER));
266 return toDomNode(xmlElement);
269 public static CompositeNode fromElement(final Element xmlElement) {
270 CompositeNodeBuilder<ImmutableCompositeNode> node = ImmutableCompositeNode.builder();
271 node.setQName(qNameFromElement(xmlElement));
273 return node.toInstance();
276 public static QName qNameFromElement(final Element xmlElement) {
277 String namespace = xmlElement.getNamespaceURI();
278 String localName = xmlElement.getLocalName();
279 return QName.create(namespace != null ? URI.create(namespace) : null, null, localName);
282 private static Node<?> toNodeWithSchema(final Element xmlElement, final DataSchemaNode schema, final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
283 checkQName(xmlElement, schema.getQName());
284 if (schema instanceof DataNodeContainer) {
285 return toCompositeNodeWithSchema(xmlElement, schema.getQName(), (DataNodeContainer) schema, codecProvider,schemaCtx);
286 } else if (schema instanceof LeafSchemaNode) {
287 return toSimpleNodeWithType(xmlElement, (LeafSchemaNode) schema, codecProvider,schemaCtx);
288 } else if (schema instanceof LeafListSchemaNode) {
289 return toSimpleNodeWithType(xmlElement, (LeafListSchemaNode) schema, codecProvider,schemaCtx);
294 private static Node<?> toNodeWithSchema(final Element xmlElement, final DataSchemaNode schema, final XmlCodecProvider codecProvider) {
295 return toNodeWithSchema(xmlElement, schema, codecProvider, null);
298 protected static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafSchemaNode schema,
299 final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
300 TypeDefinitionAwareCodec<? extends Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
301 String text = xmlElement.getTextContent();
304 value = codec.deserialize(text);
307 if (schema.getType() instanceof org.opendaylight.yangtools.yang.model.util.InstanceIdentifier) {
308 value = InstanceIdentifierForXmlCodec.deserialize(xmlElement,schemaCtx);
309 } else if(schema.getType() instanceof IdentityrefTypeDefinition){
310 value = InstanceIdentifierForXmlCodec.toIdentity(xmlElement.getTextContent(), xmlElement, schemaCtx);
314 value = xmlElement.getTextContent();
317 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
318 return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
321 private static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafListSchemaNode schema,
322 final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
323 TypeDefinitionAwareCodec<? extends Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
324 String text = xmlElement.getTextContent();
327 value = codec.deserialize(text);
329 if (schema.getType() instanceof org.opendaylight.yangtools.yang.model.util.InstanceIdentifier) {
330 value = InstanceIdentifierForXmlCodec.deserialize(xmlElement,schemaCtx);
333 value = xmlElement.getTextContent();
336 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
337 return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
340 private static Node<?> toCompositeNodeWithSchema(final Element xmlElement, final QName qName, final DataNodeContainer schema,
341 final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
342 List<Node<?>> values = toDomNodes(xmlElement, Optional.fromNullable(schema.getChildNodes()),schemaCtx);
343 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
344 return ImmutableCompositeNode.create(qName, values, modifyAction.orNull());
347 public static Optional<ModifyAction> getModifyOperationFromAttributes(final Element xmlElement) {
348 Attr attributeNodeNS = xmlElement.getAttributeNodeNS(OPERATION_ATTRIBUTE_QNAME.getNamespace().toString(), OPERATION_ATTRIBUTE_QNAME.getLocalName());
349 if(attributeNodeNS == null) {
350 return Optional.absent();
353 ModifyAction action = ModifyAction.fromXmlValue(attributeNodeNS.getValue());
354 Preconditions.checkArgument(action.isOnElementPermitted(), "Unexpected operation %s on %s", action, xmlElement);
356 return Optional.of(action);
359 private static void checkQName(final Element xmlElement, final QName qName) {
360 checkState(Objects.equal(xmlElement.getNamespaceURI(), qName.getNamespace().toString()));
361 checkState(qName.getLocalName().equals(xmlElement.getLocalName()));
364 public static final Optional<DataSchemaNode> findFirstSchema(final QName qname, final Set<DataSchemaNode> dataSchemaNode) {
365 if (dataSchemaNode != null && !dataSchemaNode.isEmpty() && qname != null) {
366 for (DataSchemaNode dsn : dataSchemaNode) {
367 if (qname.isEqualWithoutRevision(dsn.getQName())) {
368 return Optional.<DataSchemaNode> of(dsn);
369 } else if (dsn instanceof ChoiceNode) {
370 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
371 Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
372 if (foundDsn != null && foundDsn.isPresent()) {
379 return Optional.absent();
382 public static Node<?> toDomNode(final Document doc) {
383 return toDomNode(doc.getDocumentElement());
386 private static Node<?> toDomNode(final Element element) {
387 QName qname = qNameFromElement(element);
389 ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
390 NodeList nodes = element.getChildNodes();
391 boolean isSimpleObject = true;
393 for (int i = 0; i < nodes.getLength(); i++) {
394 org.w3c.dom.Node child = nodes.item(i);
395 if (child instanceof Element) {
396 isSimpleObject = false;
397 values.add(toDomNode((Element) child));
399 if (isSimpleObject && child instanceof org.w3c.dom.Text) {
400 value = element.getTextContent();
401 if (!Strings.isNullOrEmpty(value)) {
402 isSimpleObject = true;
406 if (isSimpleObject) {
407 return new SimpleNodeTOImpl<>(qname, null, value);
409 return ImmutableCompositeNode.create(qname, values.build());
412 public static List<Node<?>> toDomNodes(final Element element, final Optional<Set<DataSchemaNode>> context,final SchemaContext schemaCtx) {
413 return forEachChild(element.getChildNodes(),schemaCtx, new Function<ElementWithSchemaContext, Optional<Node<?>>>() {
416 public Optional<Node<?>> apply(final ElementWithSchemaContext input) {
417 if (context.isPresent()) {
418 QName partialQName = qNameFromElement(input.getElement());
419 Optional<DataSchemaNode> schemaNode = findFirstSchema(partialQName, context.get());
420 if (schemaNode.isPresent()) {
421 return Optional.<Node<?>> fromNullable(//
422 toNodeWithSchema(input.getElement(), schemaNode.get(), DEFAULT_XML_VALUE_CODEC_PROVIDER,input.getSchemaContext()));
425 return Optional.<Node<?>> fromNullable(toDomNode(input.getElement()));
432 public static List<Node<?>> toDomNodes(final Element element, final Optional<Set<DataSchemaNode>> context) {
433 return toDomNodes(element,context,null);
437 * Converts XML Document containing notification data from Netconf device to
438 * Data DOM Nodes. <br>
439 * By specification defined in <a
440 * href="http://tools.ietf.org/search/rfc6020#section-7.14">RFC 6020</a>
441 * there are xml elements containing notifications metadata, like eventTime
442 * or root notification element which specifies namespace for which is
443 * notification defined in yang model. Those elements MUST be stripped off
444 * notifications body. This method returns pure notification body which
445 * begins in element which is equal to notifications name defined in
446 * corresponding yang model. Rest of notification metadata are obfuscated,
447 * thus Data DOM contains only pure notification body.
450 * XML Document containing notification body
451 * @param notifications
452 * Notifications Definition Schema
453 * @return Data DOM Nodes containing xml notification body definition or
454 * <code>null</code> if there is no NotificationDefinition with
455 * Element with equal notification QName defined in XML Document.
457 public static CompositeNode notificationToDomNodes(final Document document,
458 final Optional<Set<NotificationDefinition>> notifications, final SchemaContext schemaCtx) {
459 if (notifications.isPresent() && (document != null) && (document.getDocumentElement() != null)) {
460 final NodeList originChildNodes = document.getDocumentElement().getChildNodes();
461 for (int i = 0; i < originChildNodes.getLength(); i++) {
462 org.w3c.dom.Node child = originChildNodes.item(i);
463 if (child instanceof Element) {
464 final Element childElement = (Element) child;
465 final QName partialQName = qNameFromElement(childElement);
466 final Optional<NotificationDefinition> notificationDef = findNotification(partialQName,
467 notifications.get());
468 if (notificationDef.isPresent()) {
469 final Set<DataSchemaNode> dataNodes = notificationDef.get().getChildNodes();
470 final List<Node<?>> domNodes = toDomNodes(childElement,
471 Optional.<Set<DataSchemaNode>> fromNullable(dataNodes),schemaCtx);
472 return ImmutableCompositeNode.create(notificationDef.get().getQName(), domNodes);
480 public static CompositeNode notificationToDomNodes(final Document document,
481 final Optional<Set<NotificationDefinition>> notifications) {
482 return notificationToDomNodes(document, notifications,null);
485 private static Optional<NotificationDefinition> findNotification(final QName notifName,
486 final Set<NotificationDefinition> notifications) {
487 if ((notifName != null) && (notifications != null)) {
488 for (final NotificationDefinition notification : notifications) {
489 if ((notification != null) && notifName.isEqualWithoutRevision(notification.getQName())) {
490 return Optional.<NotificationDefinition>fromNullable(notification);
494 return Optional.<NotificationDefinition>absent();
497 private static final <T> List<T> forEachChild(final NodeList nodes, final SchemaContext schemaContext, final Function<ElementWithSchemaContext, Optional<T>> forBody) {
498 final int l = nodes.getLength();
500 return ImmutableList.of();
503 final List<T> list = new ArrayList<>(l);
504 for (int i = 0; i < l; i++) {
505 org.w3c.dom.Node child = nodes.item(i);
506 if (child instanceof Element) {
507 Optional<T> result = forBody.apply(new ElementWithSchemaContext((Element) child,schemaContext));
508 if (result.isPresent()) {
509 list.add(result.get());
513 return ImmutableList.copyOf(list);
516 public static final XmlCodecProvider defaultValueCodecProvider() {
517 return DEFAULT_XML_VALUE_CODEC_PROVIDER;