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;
11 import com.google.common.base.Function;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Strings;
15 import com.google.common.collect.ImmutableList;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.Collections;
20 import java.util.List;
22 import java.util.Map.Entry;
23 import java.util.Objects;
25 import javax.activation.UnsupportedDataTypeException;
26 import javax.annotation.Nonnull;
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;
34 import org.opendaylight.yangtools.yang.common.QName;
35 import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
36 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
37 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
38 import org.opendaylight.yangtools.yang.data.api.Node;
39 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
40 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
41 import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
42 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
43 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
45 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
46 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
48 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
53 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
54 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
55 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
57 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
58 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
59 import org.opendaylight.yangtools.yang.model.util.InstanceIdentifierType;
60 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
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 final class XmlDocumentUtils {
70 private XmlDocumentUtils() {
71 throw new UnsupportedOperationException("Utility class should not be instantiated");
74 private static class ElementWithSchemaContext {
76 SchemaContext schemaContext;
78 ElementWithSchemaContext(final Element element,final SchemaContext schemaContext) {
79 this.schemaContext = schemaContext;
80 this.element = element;
83 Element getElement() {
87 SchemaContext getSchemaContext() {
92 public static final QName OPERATION_ATTRIBUTE_QNAME = QName.create(SchemaContext.NAME, "operation");
93 private static final QName RPC_REPLY_QNAME = QName.create(SchemaContext.NAME, "rpc-reply");
94 private static final Logger LOG = LoggerFactory.getLogger(XmlDocumentUtils.class);
95 private static final XMLOutputFactory FACTORY = XMLOutputFactory.newFactory();
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 schemaNode Data Node Container Schema
105 * @param codecProvider XML Codec Provider
106 * @return new instance of XML Document
107 * @throws UnsupportedDataTypeException
109 * @deprecated Use {@link #toDocument(org.opendaylight.yangtools.yang.data.api.CompositeNode, com.google.common.base.Optional, org.opendaylight.yangtools.yang.model.api.DataNodeContainer, XmlCodecProvider)} instead.
110 * The whole schema context allows for proper serialization of leafrefs.
113 public static Document toDocument(final CompositeNode data, final DataNodeContainer schemaNode, final XmlCodecProvider codecProvider)
114 throws UnsupportedDataTypeException {
115 return toDocument(data, Optional.<SchemaContext>absent(), schemaNode, codecProvider);
119 * Serializes data DOM node into a w3c DOM document. Whole schema context is used to resolve leafref elements.
121 * @param data Data DOM root element
122 * @param schemaContext Entire schema context for correct leafref resolution
123 * @param schemaNode Data Node Container Schema
124 * @param codecProvider XML Codec Provider
125 * @return serialized w3c DOM document
126 * @throws UnsupportedDataTypeException
128 public static Document toDocument(final CompositeNode data, final SchemaContext schemaContext, final DataNodeContainer schemaNode, final XmlCodecProvider codecProvider)
129 throws UnsupportedDataTypeException {
130 return toDocument(data, Optional.of(schemaContext), schemaNode, codecProvider);
133 private static Document toDocument(final CompositeNode data, final Optional<SchemaContext> schemaContext, final DataNodeContainer schema, final XmlCodecProvider codecProvider)
134 throws UnsupportedDataTypeException {
135 Preconditions.checkNotNull(data);
136 Preconditions.checkNotNull(schema);
138 if (!(schema instanceof ContainerSchemaNode || schema instanceof ListSchemaNode)) {
139 throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
142 final DOMResult result = new DOMResult(getDocument());
144 final XMLStreamWriter writer = FACTORY.createXMLStreamWriter(result);
145 XmlStreamUtils xmlStreamUtils = schemaContext.isPresent() ? XmlStreamUtils.create(codecProvider, schemaContext.get()) : XmlStreamUtils.create(codecProvider);
146 xmlStreamUtils.writeDocument(writer, data, (SchemaNode) schema);
148 return (Document)result.getNode();
149 } catch (XMLStreamException e) {
150 LOG.error("Failed to serialize data {}", data, e);
155 public static Document getDocument() {
156 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
159 DocumentBuilder bob = dbf.newDocumentBuilder();
160 doc = bob.newDocument();
161 } catch (ParserConfigurationException e) {
162 throw new RuntimeException(e);
168 * Converts Data DOM structure to XML Document for specified XML Codec Provider. The CompositeNode
169 * data parameter enters as root of Data DOM tree and will be transformed to root in XML Document. The child
170 * nodes of Data Tree are transformed accordingly.
172 * @param data Data DOM root element
173 * @param codecProvider XML Codec Provider
174 * @return new instance of XML Document
176 public static Document toDocument(final CompositeNode data, final XmlCodecProvider codecProvider) {
177 final DOMResult result = new DOMResult(getDocument());
179 final XMLStreamWriter writer = FACTORY.createXMLStreamWriter(result);
180 XmlStreamUtils.create(codecProvider).writeDocument(writer, data);
182 return (Document)result.getNode();
183 } catch (XMLStreamException e) {
184 LOG.error("Failed to serialize data {}", data, e);
189 private static final Element createElementFor(final Document doc, final QName qname, final Object obj) {
191 if (qname.getNamespace() != null) {
192 ret = doc.createElementNS(qname.getNamespace().toString(), qname.getLocalName());
194 ret = doc.createElementNS(null, qname.getLocalName());
197 if (obj instanceof AttributesContainer) {
198 final Map<QName, String> attrs = ((AttributesContainer)obj).getAttributes();
201 for (Entry<QName, String> attribute : attrs.entrySet()) {
202 ret.setAttributeNS(attribute.getKey().getNamespace().toString(), attribute.getKey().getLocalName(),
203 attribute.getValue());
211 public static Element createElementFor(final Document doc, final Node<?> data) {
212 return createElementFor(doc, data.getNodeType(), data);
215 public static Element createElementFor(final Document doc, final NormalizedNode<?, ?> data) {
216 return createElementFor(doc, data.getNodeType(), data);
219 public static Node<?> toDomNode(final Element xmlElement, final Optional<DataSchemaNode> schema,
220 final Optional<XmlCodecProvider> codecProvider) {
221 return toDomNode(xmlElement, schema, codecProvider, Optional.<SchemaContext>absent());
224 public static Node<?> toDomNode(final Element xmlElement, final Optional<DataSchemaNode> schema,
225 final Optional<XmlCodecProvider> codecProvider, final Optional<SchemaContext> schemaContext) {
226 if (schema.isPresent()) {
227 if(schemaContext.isPresent()) {
228 return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(XmlUtils.DEFAULT_XML_CODEC_PROVIDER), schemaContext.get());
230 return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(XmlUtils.DEFAULT_XML_CODEC_PROVIDER));
233 return toDomNode(xmlElement);
236 public static QName qNameFromElement(final Element xmlElement) {
237 String namespace = xmlElement.getNamespaceURI();
238 String localName = xmlElement.getLocalName();
239 return QName.create(namespace != null ? URI.create(namespace) : null, null, localName);
242 private static Node<?> toNodeWithSchema(final Element xmlElement, final DataSchemaNode schema, final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
243 checkQName(xmlElement, schema.getQName());
244 if (schema instanceof DataNodeContainer) {
245 return toCompositeNodeWithSchema(xmlElement, schema.getQName(), (DataNodeContainer) schema, codecProvider,schemaCtx);
246 } else if (schema instanceof LeafSchemaNode) {
247 return toSimpleNodeWithType(xmlElement, (LeafSchemaNode) schema, codecProvider,schemaCtx);
248 } else if (schema instanceof LeafListSchemaNode) {
249 return toSimpleNodeWithType(xmlElement, (LeafListSchemaNode) schema, codecProvider,schemaCtx);
250 } else if (schema instanceof AnyXmlSchemaNode) {
251 return toDomNode(xmlElement);
256 private static Node<?> toNodeWithSchema(final Element xmlElement, final DataSchemaNode schema, final XmlCodecProvider codecProvider) {
257 return toNodeWithSchema(xmlElement, schema, codecProvider, null);
260 protected static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafSchemaNode schema,
261 final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
262 final Object value = resolveValueFromSchemaType(xmlElement, schema, schema.getType(), codecProvider, schemaCtx);
263 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
264 return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
267 private static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafListSchemaNode schema,
268 final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
269 final Object value = resolveValueFromSchemaType(xmlElement, schema, schema.getType(), codecProvider, schemaCtx);
270 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
271 return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
274 private static Object resolveValueFromSchemaType(final Element xmlElement, final DataSchemaNode schema, final TypeDefinition<?> type,
275 final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
277 TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
278 if (baseType instanceof LeafrefTypeDefinition) {
279 final LeafrefTypeDefinition leafrefTypeDefinition = (LeafrefTypeDefinition) baseType;
280 baseType = SchemaContextUtil.getBaseTypeForLeafRef(leafrefTypeDefinition, schemaCtx, schema);
283 final String text = xmlElement.getTextContent();
286 if (baseType instanceof InstanceIdentifierType) {
287 value = InstanceIdentifierForXmlCodec.deserialize(xmlElement, schemaCtx);
288 } else if (baseType instanceof IdentityrefTypeDefinition) {
289 value = InstanceIdentifierForXmlCodec.toIdentity(text, xmlElement, schemaCtx);
291 final TypeDefinitionAwareCodec<?, ?> codec = codecProvider.codecFor(baseType);
293 LOG.info("No codec for schema {}, falling back to text", schema);
296 value = codec.deserialize(text);
302 private static Node<?> toCompositeNodeWithSchema(final Element xmlElement, final QName qName, final DataNodeContainer schema,
303 final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
304 List<Node<?>> values = toDomNodes(xmlElement, Optional.fromNullable(schema.getChildNodes()),schemaCtx);
305 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
306 return ImmutableCompositeNode.create(qName, values, modifyAction.orNull());
309 public static Optional<ModifyAction> getModifyOperationFromAttributes(final Element xmlElement) {
310 Attr attributeNodeNS = xmlElement.getAttributeNodeNS(OPERATION_ATTRIBUTE_QNAME.getNamespace().toString(), OPERATION_ATTRIBUTE_QNAME.getLocalName());
311 if(attributeNodeNS == null) {
312 return Optional.absent();
315 ModifyAction action = ModifyAction.fromXmlValue(attributeNodeNS.getValue());
316 Preconditions.checkArgument(action.isOnElementPermitted(), "Unexpected operation %s on %s", action, xmlElement);
318 return Optional.of(action);
321 private static void checkQName(final Element xmlElement, final QName qName) {
322 checkState(Objects.equals(xmlElement.getNamespaceURI(), qName.getNamespace().toString()), "Not equal: %s to: %s for: %s and: %s", qName.getNamespace(), xmlElement.getNamespaceURI(), qName, xmlElement);
323 checkState(qName.getLocalName().equals(xmlElement.getLocalName()), "Not equal: %s to: %s for: %s and: %s", qName.getLocalName(), xmlElement.getLocalName(), qName, xmlElement);
326 public static final Optional<DataSchemaNode> findFirstSchema(final QName qname, final Iterable<DataSchemaNode> dataSchemaNode) {
327 if (dataSchemaNode != null && qname != null) {
328 for (DataSchemaNode dsn : dataSchemaNode) {
329 if (qname.isEqualWithoutRevision(dsn.getQName())) {
330 return Optional.<DataSchemaNode> of(dsn);
331 } else if (dsn instanceof ChoiceNode) {
332 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
333 Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
334 if (foundDsn != null && foundDsn.isPresent()) {
341 return Optional.absent();
344 public static Node<?> toDomNode(final Document doc) {
345 return toDomNode(doc.getDocumentElement());
348 private static Node<?> toDomNode(final Element element) {
349 QName qname = qNameFromElement(element);
351 ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
352 NodeList nodes = element.getChildNodes();
353 boolean isSimpleObject = true;
355 for (int i = 0; i < nodes.getLength(); i++) {
356 org.w3c.dom.Node child = nodes.item(i);
357 if (child instanceof Element) {
358 isSimpleObject = false;
359 values.add(toDomNode((Element) child));
361 if (isSimpleObject && child instanceof org.w3c.dom.Text) {
362 value = element.getTextContent();
363 if (!Strings.isNullOrEmpty(value)) {
364 isSimpleObject = true;
368 if (isSimpleObject) {
369 return new SimpleNodeTOImpl<>(qname, null, value);
371 return ImmutableCompositeNode.create(qname, values.build());
374 public static List<Node<?>> toDomNodes(final Element element, final Optional<? extends Iterable<DataSchemaNode>> context, final SchemaContext schemaCtx) {
375 return forEachChild(element.getChildNodes(), schemaCtx, new Function<ElementWithSchemaContext, Optional<Node<?>>>() {
378 public Optional<Node<?>> apply(final @Nonnull ElementWithSchemaContext input) {
379 if (context.isPresent()) {
380 Preconditions.checkNotNull(input);
381 QName partialQName = qNameFromElement(input.getElement());
382 Optional<DataSchemaNode> schemaNode = findFirstSchema(partialQName, context.get());
383 if (schemaNode.isPresent()) {
384 return Optional.<Node<?>> fromNullable(
385 toNodeWithSchema(input.getElement(), schemaNode.get(), XmlUtils.DEFAULT_XML_CODEC_PROVIDER, input.getSchemaContext()));
388 return Optional.<Node<?>> fromNullable(toDomNode(input.getElement()));
394 public static List<Node<?>> toDomNodes(final Element element, final Optional<? extends Iterable<DataSchemaNode>> context) {
395 return toDomNodes(element, context, null);
399 * Converts XML Document containing notification data from Netconf device to
400 * Data DOM Nodes. <br>
401 * By specification defined in <a
402 * href="http://tools.ietf.org/search/rfc6020#section-7.14">RFC 6020</a>
403 * there are xml elements containing notifications metadata, like eventTime
404 * or root notification element which specifies namespace for which is
405 * notification defined in yang model. Those elements MUST be stripped off
406 * notifications body. This method returns pure notification body which
407 * begins in element which is equal to notifications name defined in
408 * corresponding yang model. Rest of notification metadata are obfuscated,
409 * thus Data DOM contains only pure notification body.
412 * XML Document containing notification body
413 * @param notifications
414 * Notifications Definition Schema
415 * @return Data DOM Nodes containing xml notification body definition or
416 * <code>null</code> if there is no NotificationDefinition with
417 * Element with equal notification QName defined in XML Document.
419 public static CompositeNode notificationToDomNodes(final Document document,
420 final Optional<Set<NotificationDefinition>> notifications, final SchemaContext schemaCtx) {
421 if (notifications.isPresent() && (document != null) && (document.getDocumentElement() != null)) {
422 final NodeList originChildNodes = document.getDocumentElement().getChildNodes();
423 for (int i = 0; i < originChildNodes.getLength(); i++) {
424 org.w3c.dom.Node child = originChildNodes.item(i);
425 if (child instanceof Element) {
426 final Element childElement = (Element) child;
427 final QName partialQName = qNameFromElement(childElement);
428 final Optional<NotificationDefinition> notificationDef = findNotification(partialQName,
429 notifications.get());
430 if (notificationDef.isPresent()) {
431 final Iterable<DataSchemaNode> dataNodes = notificationDef.get().getChildNodes();
432 final List<Node<?>> domNodes = toDomNodes(childElement,
433 Optional.<Iterable<DataSchemaNode>> fromNullable(dataNodes),schemaCtx);
434 return ImmutableCompositeNode.create(notificationDef.get().getQName(), domNodes);
443 * Transforms XML Document representing Rpc output body into Composite Node structure based on Rpc definition
444 * within given Schema Context. The transformation is based on Rpc Definition which is defined in provided Schema Context.
445 * If Rpc Definition is missing from given Schema Context the method will return <code>null</code>
447 * @param document XML Document containing Output RPC message
448 * @param rpcName Rpc QName
449 * @param context Schema Context
450 * @return Rpc message in Composite Node data structures if Rpc definition is present within provided Schema Context, otherwise
451 * returns <code>null</code>
453 public static CompositeNode rpcReplyToDomNodes(final Document document, final QName rpcName,
454 final SchemaContext context) {
455 Preconditions.checkNotNull(document);
456 Preconditions.checkNotNull(rpcName);
457 Preconditions.checkNotNull(context);
459 Optional<RpcDefinition> rpcDefinition = findRpc(rpcName, context);
460 if (rpcDefinition.isPresent()) {
461 RpcDefinition rpc = rpcDefinition.get();
463 final Collection<DataSchemaNode> outputNode = rpc.getOutput() != null ? rpc.getOutput().getChildNodes() : null;
464 final Element rpcReplyElement = document.getDocumentElement();
465 final QName partialQName = qNameFromElement(rpcReplyElement);
467 if (RPC_REPLY_QNAME.equals(partialQName)) {
468 final List<Node<?>> domNodes = toDomNodes(rpcReplyElement, Optional.fromNullable(outputNode), context);
469 QName qName = rpc.getOutput() != null ? rpc.getOutput().getQName() : QName.cachedReference(QName.create(rpcName, "output"));
470 List<Node<?>> rpcOutNodes = Collections.<Node<?>>singletonList(ImmutableCompositeNode.create(
472 return ImmutableCompositeNode.create(rpcName, rpcOutNodes);
479 * Method searches given schema context for Rpc Definition with given QName.
480 * Returns Rpc Definition if is present within given Schema Context, otherwise returns Optional.absent().
482 * @param rpc Rpc QName
483 * @param context Schema Context
484 * @return Rpc Definition if is present within given Schema Context, otherwise returns Optional.absent().
486 private static Optional<RpcDefinition> findRpc(final QName rpc, final SchemaContext context) {
487 Preconditions.checkNotNull(rpc);
488 Preconditions.checkNotNull(context);
489 for (final RpcDefinition rpcDefinition : context.getOperations()) {
490 if ((rpcDefinition != null) && rpc.equals(rpcDefinition.getQName())) {
491 return Optional.of(rpcDefinition);
494 return Optional.absent();
497 public static CompositeNode notificationToDomNodes(final Document document,
498 final Optional<Set<NotificationDefinition>> notifications) {
499 return notificationToDomNodes(document, notifications,null);
502 private static Optional<NotificationDefinition> findNotification(final QName notifName,
503 final Set<NotificationDefinition> notifications) {
504 if ((notifName != null) && (notifications != null)) {
505 for (final NotificationDefinition notification : notifications) {
506 if ((notification != null) && notifName.isEqualWithoutRevision(notification.getQName())) {
507 return Optional.<NotificationDefinition>fromNullable(notification);
511 return Optional.<NotificationDefinition>absent();
514 private static final <T> List<T> forEachChild(final NodeList nodes, final SchemaContext schemaContext, final Function<ElementWithSchemaContext, Optional<T>> forBody) {
515 final int l = nodes.getLength();
517 return ImmutableList.of();
520 final List<T> list = new ArrayList<>(l);
521 for (int i = 0; i < l; i++) {
522 org.w3c.dom.Node child = nodes.item(i);
523 if (child instanceof Element) {
524 Optional<T> result = forBody.apply(new ElementWithSchemaContext((Element) child,schemaContext));
525 if (result.isPresent()) {
526 list.add(result.get());
530 return ImmutableList.copyOf(list);
533 public static final XmlCodecProvider defaultValueCodecProvider() {
534 return XmlUtils.DEFAULT_XML_CODEC_PROVIDER;