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;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.List;
24 import java.util.Map.Entry;
26 import javax.activation.UnsupportedDataTypeException;
27 import javax.annotation.Nonnull;
28 import javax.xml.parsers.DocumentBuilder;
29 import javax.xml.parsers.DocumentBuilderFactory;
30 import javax.xml.parsers.ParserConfigurationException;
31 import javax.xml.stream.XMLOutputFactory;
32 import javax.xml.stream.XMLStreamException;
33 import javax.xml.stream.XMLStreamWriter;
34 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.ModifyAction;
39 import org.opendaylight.yangtools.yang.data.api.Node;
40 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
41 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
42 import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
43 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
44 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
46 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
47 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
49 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
54 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
55 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
56 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
58 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
59 import org.opendaylight.yangtools.yang.model.util.InstanceIdentifierType;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62 import org.w3c.dom.Attr;
63 import org.w3c.dom.Document;
64 import org.w3c.dom.Element;
65 import org.w3c.dom.NodeList;
67 public class XmlDocumentUtils {
68 private static class ElementWithSchemaContext {
70 SchemaContext schemaContext;
72 ElementWithSchemaContext(final Element element,final SchemaContext schemaContext) {
73 this.schemaContext = schemaContext;
74 this.element = element;
77 Element getElement() {
81 SchemaContext getSchemaContext() {
86 public static final QName OPERATION_ATTRIBUTE_QNAME = QName.create(SchemaContext.NAME, "operation");
87 private static final QName RPC_REPLY_QNAME = QName.create(SchemaContext.NAME, "rpc-reply");
88 private static final Logger LOG = LoggerFactory.getLogger(XmlDocumentUtils.class);
89 private static final XMLOutputFactory FACTORY = XMLOutputFactory.newFactory();
92 * Converts Data DOM structure to XML Document for specified XML Codec Provider and corresponding
93 * Data Node Container schema. The CompositeNode data parameter enters as root of Data DOM tree and will
94 * be transformed to root in XML Document. Each element of Data DOM tree is compared against specified Data
95 * Node Container Schema and transformed accordingly.
97 * @param data Data DOM root element
98 * @param schemaNode Data Node Container Schema
99 * @param codecProvider XML Codec Provider
100 * @return new instance of XML Document
101 * @throws UnsupportedDataTypeException
103 * @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.
104 * The whole schema context allows for proper serialization of leafrefs.
106 public static Document toDocument(final CompositeNode data, final DataNodeContainer schemaNode, final XmlCodecProvider codecProvider)
107 throws UnsupportedDataTypeException {
108 return toDocument(data, Optional.<SchemaContext>absent(), schemaNode, codecProvider);
112 * Serializes data DOM node into a w3c DOM document. Whole schema context is used to resolve leafref elements.
114 * @param data Data DOM root element
115 * @param schemaContext Entire schema context for correct leafref resolution
116 * @param schema Data Node Container Schema
117 * @param codecProvider XML Codec Provider
118 * @return serialized w3c DOM document
119 * @throws UnsupportedDataTypeException
121 public static Document toDocument(final CompositeNode data, final SchemaContext schemaContext, final DataNodeContainer schemaNode, final XmlCodecProvider codecProvider)
122 throws UnsupportedDataTypeException {
123 return toDocument(data, Optional.of(schemaContext), schemaNode, codecProvider);
126 private static Document toDocument(final CompositeNode data, final Optional<SchemaContext> schemaContext, final DataNodeContainer schema, final XmlCodecProvider codecProvider)
127 throws UnsupportedDataTypeException {
128 Preconditions.checkNotNull(data);
129 Preconditions.checkNotNull(schema);
131 if (!(schema instanceof ContainerSchemaNode || schema instanceof ListSchemaNode)) {
132 throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
135 final DOMResult result = new DOMResult(getDocument());
137 final XMLStreamWriter writer = FACTORY.createXMLStreamWriter(result);
138 XmlStreamUtils xmlStreamUtils = schemaContext.isPresent() ? XmlStreamUtils.create(codecProvider, schemaContext.get()) : XmlStreamUtils.create(codecProvider);
139 xmlStreamUtils.writeDocument(writer, data, (SchemaNode) schema);
141 return (Document)result.getNode();
142 } catch (XMLStreamException e) {
143 LOG.error("Failed to serialize data {}", data, e);
148 public static Document getDocument() {
149 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
152 DocumentBuilder bob = dbf.newDocumentBuilder();
153 doc = bob.newDocument();
154 } catch (ParserConfigurationException e) {
155 throw new RuntimeException(e);
161 * Converts Data DOM structure to XML Document for specified XML Codec Provider. The CompositeNode
162 * data parameter enters as root of Data DOM tree and will be transformed to root in XML Document. The child
163 * nodes of Data Tree are transformed accordingly.
165 * @param data Data DOM root element
166 * @param codecProvider XML Codec Provider
167 * @return new instance of XML Document
168 * @throws UnsupportedDataTypeException
170 public static Document toDocument(final CompositeNode data, final XmlCodecProvider codecProvider) {
171 final DOMResult result = new DOMResult(getDocument());
173 final XMLStreamWriter writer = FACTORY.createXMLStreamWriter(result);
174 XmlStreamUtils.create(codecProvider).writeDocument(writer, data);
176 return (Document)result.getNode();
177 } catch (XMLStreamException e) {
178 LOG.error("Failed to serialize data {}", data, e);
183 private static final Element createElementFor(final Document doc, final QName qname, final Object obj) {
185 if (qname.getNamespace() != null) {
186 ret = doc.createElementNS(qname.getNamespace().toString(), qname.getLocalName());
188 ret = doc.createElementNS(null, qname.getLocalName());
191 if (obj instanceof AttributesContainer) {
192 final Map<QName, String> attrs = ((AttributesContainer)obj).getAttributes();
195 for (Entry<QName, String> attribute : attrs.entrySet()) {
196 ret.setAttributeNS(attribute.getKey().getNamespace().toString(), attribute.getKey().getLocalName(),
197 attribute.getValue());
205 public static Element createElementFor(final Document doc, final Node<?> data) {
206 return createElementFor(doc, data.getNodeType(), data);
209 public static Element createElementFor(final Document doc, final NormalizedNode<?, ?> data) {
210 return createElementFor(doc, data.getNodeType(), data);
213 public static Node<?> toDomNode(final Element xmlElement, final Optional<DataSchemaNode> schema,
214 final Optional<XmlCodecProvider> codecProvider) {
215 return toDomNode(xmlElement, schema, codecProvider, Optional.<SchemaContext>absent());
218 public static Node<?> toDomNode(final Element xmlElement, final Optional<DataSchemaNode> schema,
219 final Optional<XmlCodecProvider> codecProvider, final Optional<SchemaContext> schemaContext) {
220 if (schema.isPresent()) {
221 if(schemaContext.isPresent()) {
222 return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(XmlUtils.DEFAULT_XML_CODEC_PROVIDER), schemaContext.get());
224 return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(XmlUtils.DEFAULT_XML_CODEC_PROVIDER));
227 return toDomNode(xmlElement);
230 public static QName qNameFromElement(final Element xmlElement) {
231 String namespace = xmlElement.getNamespaceURI();
232 String localName = xmlElement.getLocalName();
233 return QName.create(namespace != null ? URI.create(namespace) : null, null, localName);
236 private static Node<?> toNodeWithSchema(final Element xmlElement, final DataSchemaNode schema, final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
237 checkQName(xmlElement, schema.getQName());
238 if (schema instanceof DataNodeContainer) {
239 return toCompositeNodeWithSchema(xmlElement, schema.getQName(), (DataNodeContainer) schema, codecProvider,schemaCtx);
240 } else if (schema instanceof LeafSchemaNode) {
241 return toSimpleNodeWithType(xmlElement, (LeafSchemaNode) schema, codecProvider,schemaCtx);
242 } else if (schema instanceof LeafListSchemaNode) {
243 return toSimpleNodeWithType(xmlElement, (LeafListSchemaNode) schema, codecProvider,schemaCtx);
244 } else if (schema instanceof AnyXmlSchemaNode) {
245 return toDomNode(xmlElement);
250 private static Node<?> toNodeWithSchema(final Element xmlElement, final DataSchemaNode schema, final XmlCodecProvider codecProvider) {
251 return toNodeWithSchema(xmlElement, schema, codecProvider, null);
254 protected static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafSchemaNode schema,
255 final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
256 final Object value = resolveValueFromSchemaType(xmlElement, schema, schema.getType(), codecProvider, schemaCtx);
257 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
258 return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
261 private static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafListSchemaNode schema,
262 final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
263 final Object value = resolveValueFromSchemaType(xmlElement, schema, schema.getType(), codecProvider, schemaCtx);
264 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
265 return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
268 private static Object resolveValueFromSchemaType(final Element xmlElement, final DataSchemaNode schema, final TypeDefinition<?> type,
269 final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
270 final TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
271 final String text = xmlElement.getTextContent();
274 if (baseType instanceof InstanceIdentifierType) {
275 value = InstanceIdentifierForXmlCodec.deserialize(xmlElement, schemaCtx);
276 } else if (baseType instanceof IdentityrefTypeDefinition) {
277 value = InstanceIdentifierForXmlCodec.toIdentity(text, xmlElement, schemaCtx);
279 final TypeDefinitionAwareCodec<?, ?> codec = codecProvider.codecFor(type);
281 LOG.info("No codec for schema {}, falling back to text", schema);
284 value = codec.deserialize(text);
290 private static Node<?> toCompositeNodeWithSchema(final Element xmlElement, final QName qName, final DataNodeContainer schema,
291 final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
292 List<Node<?>> values = toDomNodes(xmlElement, Optional.fromNullable(schema.getChildNodes()),schemaCtx);
293 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
294 return ImmutableCompositeNode.create(qName, values, modifyAction.orNull());
297 public static Optional<ModifyAction> getModifyOperationFromAttributes(final Element xmlElement) {
298 Attr attributeNodeNS = xmlElement.getAttributeNodeNS(OPERATION_ATTRIBUTE_QNAME.getNamespace().toString(), OPERATION_ATTRIBUTE_QNAME.getLocalName());
299 if(attributeNodeNS == null) {
300 return Optional.absent();
303 ModifyAction action = ModifyAction.fromXmlValue(attributeNodeNS.getValue());
304 Preconditions.checkArgument(action.isOnElementPermitted(), "Unexpected operation %s on %s", action, xmlElement);
306 return Optional.of(action);
309 private static void checkQName(final Element xmlElement, final QName qName) {
310 checkState(Objects.equal(xmlElement.getNamespaceURI(), qName.getNamespace().toString()), "Not equal: %s to: %s for: %s and: %s", qName.getNamespace(), xmlElement.getNamespaceURI(), qName, xmlElement);
311 checkState(qName.getLocalName().equals(xmlElement.getLocalName()), "Not equal: %s to: %s for: %s and: %s", qName.getLocalName(), xmlElement.getLocalName(), qName, xmlElement);
314 public static final Optional<DataSchemaNode> findFirstSchema(final QName qname, final Iterable<DataSchemaNode> dataSchemaNode) {
315 if (dataSchemaNode != null && qname != null) {
316 for (DataSchemaNode dsn : dataSchemaNode) {
317 if (qname.isEqualWithoutRevision(dsn.getQName())) {
318 return Optional.<DataSchemaNode> of(dsn);
319 } else if (dsn instanceof ChoiceNode) {
320 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
321 Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
322 if (foundDsn != null && foundDsn.isPresent()) {
329 return Optional.absent();
332 public static Node<?> toDomNode(final Document doc) {
333 return toDomNode(doc.getDocumentElement());
336 private static Node<?> toDomNode(final Element element) {
337 QName qname = qNameFromElement(element);
339 ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
340 NodeList nodes = element.getChildNodes();
341 boolean isSimpleObject = true;
343 for (int i = 0; i < nodes.getLength(); i++) {
344 org.w3c.dom.Node child = nodes.item(i);
345 if (child instanceof Element) {
346 isSimpleObject = false;
347 values.add(toDomNode((Element) child));
349 if (isSimpleObject && child instanceof org.w3c.dom.Text) {
350 value = element.getTextContent();
351 if (!Strings.isNullOrEmpty(value)) {
352 isSimpleObject = true;
356 if (isSimpleObject) {
357 return new SimpleNodeTOImpl<>(qname, null, value);
359 return ImmutableCompositeNode.create(qname, values.build());
362 public static List<Node<?>> toDomNodes(final Element element, final Optional<? extends Iterable<DataSchemaNode>> context, final SchemaContext schemaCtx) {
363 return forEachChild(element.getChildNodes(), schemaCtx, new Function<ElementWithSchemaContext, Optional<Node<?>>>() {
366 public Optional<Node<?>> apply(final @Nonnull ElementWithSchemaContext input) {
367 if (context.isPresent()) {
368 Preconditions.checkNotNull(input);
369 QName partialQName = qNameFromElement(input.getElement());
370 Optional<DataSchemaNode> schemaNode = findFirstSchema(partialQName, context.get());
371 if (schemaNode.isPresent()) {
372 return Optional.<Node<?>> fromNullable(
373 toNodeWithSchema(input.getElement(), schemaNode.get(), XmlUtils.DEFAULT_XML_CODEC_PROVIDER, input.getSchemaContext()));
376 return Optional.<Node<?>> fromNullable(toDomNode(input.getElement()));
382 public static List<Node<?>> toDomNodes(final Element element, final Optional<? extends Iterable<DataSchemaNode>> context) {
383 return toDomNodes(element, context, null);
387 * Converts XML Document containing notification data from Netconf device to
388 * Data DOM Nodes. <br>
389 * By specification defined in <a
390 * href="http://tools.ietf.org/search/rfc6020#section-7.14">RFC 6020</a>
391 * there are xml elements containing notifications metadata, like eventTime
392 * or root notification element which specifies namespace for which is
393 * notification defined in yang model. Those elements MUST be stripped off
394 * notifications body. This method returns pure notification body which
395 * begins in element which is equal to notifications name defined in
396 * corresponding yang model. Rest of notification metadata are obfuscated,
397 * thus Data DOM contains only pure notification body.
400 * XML Document containing notification body
401 * @param notifications
402 * Notifications Definition Schema
403 * @return Data DOM Nodes containing xml notification body definition or
404 * <code>null</code> if there is no NotificationDefinition with
405 * Element with equal notification QName defined in XML Document.
407 public static CompositeNode notificationToDomNodes(final Document document,
408 final Optional<Set<NotificationDefinition>> notifications, final SchemaContext schemaCtx) {
409 if (notifications.isPresent() && (document != null) && (document.getDocumentElement() != null)) {
410 final NodeList originChildNodes = document.getDocumentElement().getChildNodes();
411 for (int i = 0; i < originChildNodes.getLength(); i++) {
412 org.w3c.dom.Node child = originChildNodes.item(i);
413 if (child instanceof Element) {
414 final Element childElement = (Element) child;
415 final QName partialQName = qNameFromElement(childElement);
416 final Optional<NotificationDefinition> notificationDef = findNotification(partialQName,
417 notifications.get());
418 if (notificationDef.isPresent()) {
419 final Iterable<DataSchemaNode> dataNodes = notificationDef.get().getChildNodes();
420 final List<Node<?>> domNodes = toDomNodes(childElement,
421 Optional.<Iterable<DataSchemaNode>> fromNullable(dataNodes),schemaCtx);
422 return ImmutableCompositeNode.create(notificationDef.get().getQName(), domNodes);
431 * Transforms XML Document representing Rpc output body into Composite Node structure based on Rpc definition
432 * within given Schema Context. The transformation is based on Rpc Definition which is defined in provided Schema Context.
433 * If Rpc Definition is missing from given Schema Context the method will return <code>null</code>
435 * @param document XML Document containing Output RPC message
436 * @param rpcName Rpc QName
437 * @param context Schema Context
438 * @return Rpc message in Composite Node data structures if Rpc definition is present within provided Schema Context, otherwise
439 * returns <code>null</code>
441 public static CompositeNode rpcReplyToDomNodes(final Document document, final QName rpcName,
442 final SchemaContext context) {
443 Preconditions.checkNotNull(document);
444 Preconditions.checkNotNull(rpcName);
445 Preconditions.checkNotNull(context);
447 Optional<RpcDefinition> rpcDefinition = findRpc(rpcName, context);
448 if (rpcDefinition.isPresent()) {
449 RpcDefinition rpc = rpcDefinition.get();
451 final Collection<DataSchemaNode> outputNode = rpc.getOutput() != null ? rpc.getOutput().getChildNodes() : null;
452 final Element rpcReplyElement = document.getDocumentElement();
453 final QName partialQName = qNameFromElement(rpcReplyElement);
455 if (RPC_REPLY_QNAME.equals(partialQName)) {
456 final List<Node<?>> domNodes = toDomNodes(rpcReplyElement, Optional.fromNullable(outputNode), context);
457 QName qName = rpc.getOutput() != null ? rpc.getOutput().getQName() : QName.cachedReference(QName.create(rpcName, "output"));
458 List<Node<?>> rpcOutNodes = Collections.<Node<?>>singletonList(ImmutableCompositeNode.create(
460 return ImmutableCompositeNode.create(rpcName, rpcOutNodes);
467 * Method searches given schema context for Rpc Definition with given QName.
468 * Returns Rpc Definition if is present within given Schema Context, otherwise returns Optional.absent().
470 * @param rpc Rpc QName
471 * @param context Schema Context
472 * @return Rpc Definition if is present within given Schema Context, otherwise returns Optional.absent().
474 private static Optional<RpcDefinition> findRpc(final QName rpc, final SchemaContext context) {
475 Preconditions.checkNotNull(rpc);
476 Preconditions.checkNotNull(context);
477 for (final RpcDefinition rpcDefinition : context.getOperations()) {
478 if ((rpcDefinition != null) && rpc.equals(rpcDefinition.getQName())) {
479 return Optional.of(rpcDefinition);
482 return Optional.absent();
485 public static CompositeNode notificationToDomNodes(final Document document,
486 final Optional<Set<NotificationDefinition>> notifications) {
487 return notificationToDomNodes(document, notifications,null);
490 private static Optional<NotificationDefinition> findNotification(final QName notifName,
491 final Set<NotificationDefinition> notifications) {
492 if ((notifName != null) && (notifications != null)) {
493 for (final NotificationDefinition notification : notifications) {
494 if ((notification != null) && notifName.isEqualWithoutRevision(notification.getQName())) {
495 return Optional.<NotificationDefinition>fromNullable(notification);
499 return Optional.<NotificationDefinition>absent();
502 private static final <T> List<T> forEachChild(final NodeList nodes, final SchemaContext schemaContext, final Function<ElementWithSchemaContext, Optional<T>> forBody) {
503 final int l = nodes.getLength();
505 return ImmutableList.of();
508 final List<T> list = new ArrayList<>(l);
509 for (int i = 0; i < l; i++) {
510 org.w3c.dom.Node child = nodes.item(i);
511 if (child instanceof Element) {
512 Optional<T> result = forBody.apply(new ElementWithSchemaContext((Element) child,schemaContext));
513 if (result.isPresent()) {
514 list.add(result.get());
518 return ImmutableList.copyOf(list);
521 public static final XmlCodecProvider defaultValueCodecProvider() {
522 return XmlUtils.DEFAULT_XML_CODEC_PROVIDER;