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.Collection;
22 import java.util.Collections;
23 import java.util.List;
25 import java.util.Map.Entry;
28 import javax.activation.UnsupportedDataTypeException;
29 import javax.xml.parsers.DocumentBuilder;
30 import javax.xml.parsers.DocumentBuilderFactory;
31 import javax.xml.parsers.ParserConfigurationException;
32 import javax.xml.stream.XMLOutputFactory;
33 import javax.xml.stream.XMLStreamException;
34 import javax.xml.stream.XMLStreamWriter;
35 import javax.xml.transform.dom.DOMResult;
37 import org.opendaylight.yangtools.yang.common.QName;
38 import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
39 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
40 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
41 import org.opendaylight.yangtools.yang.data.api.Node;
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.model.api.ChoiceCaseNode;
47 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
48 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
50 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
55 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
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.util.InstanceIdentifierType;
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(SchemaContext.NAME, "operation");
88 private static final QName RPC_REPLY_QNAME = QName.create(SchemaContext.NAME, "rpc-reply");
89 private static final Logger LOG = LoggerFactory.getLogger(XmlDocumentUtils.class);
90 private static final XMLOutputFactory FACTORY = XMLOutputFactory.newFactory();
93 * Converts Data DOM structure to XML Document for specified XML Codec Provider and corresponding
94 * Data Node Container schema. The CompositeNode data parameter enters as root of Data DOM tree and will
95 * be transformed to root in XML Document. Each element of Data DOM tree is compared against specified Data
96 * Node Container Schema and transformed accordingly.
98 * @param data Data DOM root element
99 * @param schema Data Node Container Schema
100 * @param codecProvider XML Codec Provider
101 * @return new instance of XML Document
102 * @throws UnsupportedDataTypeException
104 public static Document toDocument(final CompositeNode data, final DataNodeContainer schema, final XmlCodecProvider codecProvider)
105 throws UnsupportedDataTypeException {
106 Preconditions.checkNotNull(data);
107 Preconditions.checkNotNull(schema);
109 if (!(schema instanceof ContainerSchemaNode || schema instanceof ListSchemaNode)) {
110 throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
113 final DOMResult result = new DOMResult(getDocument());
115 final XMLStreamWriter writer = FACTORY.createXMLStreamWriter(result);
116 XmlStreamUtils.create(codecProvider).writeDocument(writer, data, (SchemaNode)schema);
118 return (Document)result.getNode();
119 } catch (XMLStreamException e) {
120 LOG.error("Failed to serialize data {}", data, e);
125 public static Document getDocument() {
126 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
129 DocumentBuilder bob = dbf.newDocumentBuilder();
130 doc = bob.newDocument();
131 } catch (ParserConfigurationException e) {
132 throw new RuntimeException(e);
138 * Converts Data DOM structure to XML Document for specified XML Codec Provider. The CompositeNode
139 * data parameter enters as root of Data DOM tree and will be transformed to root in XML Document. The child
140 * nodes of Data Tree are transformed accordingly.
142 * @param data Data DOM root element
143 * @param codecProvider XML Codec Provider
144 * @return new instance of XML Document
145 * @throws UnsupportedDataTypeException
147 public static Document toDocument(final CompositeNode data, final XmlCodecProvider codecProvider) {
148 final DOMResult result = new DOMResult(getDocument());
150 final XMLStreamWriter writer = FACTORY.createXMLStreamWriter(result);
151 XmlStreamUtils.create(codecProvider).writeDocument(writer, data);
153 return (Document)result.getNode();
154 } catch (XMLStreamException e) {
155 LOG.error("Failed to serialize data {}", data, e);
160 private static final Element createElementFor(final Document doc, final QName qname, final Object obj) {
162 if (qname.getNamespace() != null) {
163 ret = doc.createElementNS(qname.getNamespace().toString(), qname.getLocalName());
165 ret = doc.createElementNS(null, qname.getLocalName());
168 if (obj instanceof AttributesContainer) {
169 final Map<QName, String> attrs = ((AttributesContainer)obj).getAttributes();
172 for (Entry<QName, String> attribute : attrs.entrySet()) {
173 ret.setAttributeNS(attribute.getKey().getNamespace().toString(), attribute.getKey().getLocalName(),
174 attribute.getValue());
182 public static Element createElementFor(final Document doc, final Node<?> data) {
183 return createElementFor(doc, data.getNodeType(), data);
186 public static Element createElementFor(final Document doc, final NormalizedNode<?, ?> data) {
187 return createElementFor(doc, data.getNodeType(), data);
190 public static Node<?> toDomNode(final Element xmlElement, final Optional<DataSchemaNode> schema,
191 final Optional<XmlCodecProvider> codecProvider) {
192 return toDomNode(xmlElement, schema, codecProvider, Optional.<SchemaContext>absent());
195 public static Node<?> toDomNode(final Element xmlElement, final Optional<DataSchemaNode> schema,
196 final Optional<XmlCodecProvider> codecProvider, final Optional<SchemaContext> schemaContext) {
197 if (schema.isPresent()) {
198 if(schemaContext.isPresent()) {
199 return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(XmlUtils.DEFAULT_XML_CODEC_PROVIDER), schemaContext.get());
201 return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(XmlUtils.DEFAULT_XML_CODEC_PROVIDER));
204 return toDomNode(xmlElement);
207 public static QName qNameFromElement(final Element xmlElement) {
208 String namespace = xmlElement.getNamespaceURI();
209 String localName = xmlElement.getLocalName();
210 return QName.create(namespace != null ? URI.create(namespace) : null, null, localName);
213 private static Node<?> toNodeWithSchema(final Element xmlElement, final DataSchemaNode schema, final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
214 checkQName(xmlElement, schema.getQName());
215 if (schema instanceof DataNodeContainer) {
216 return toCompositeNodeWithSchema(xmlElement, schema.getQName(), (DataNodeContainer) schema, codecProvider,schemaCtx);
217 } else if (schema instanceof LeafSchemaNode) {
218 return toSimpleNodeWithType(xmlElement, (LeafSchemaNode) schema, codecProvider,schemaCtx);
219 } else if (schema instanceof LeafListSchemaNode) {
220 return toSimpleNodeWithType(xmlElement, (LeafListSchemaNode) schema, codecProvider,schemaCtx);
225 private static Node<?> toNodeWithSchema(final Element xmlElement, final DataSchemaNode schema, final XmlCodecProvider codecProvider) {
226 return toNodeWithSchema(xmlElement, schema, codecProvider, null);
229 protected static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafSchemaNode schema,
230 final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
231 final TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(schema.getType());
232 final String text = xmlElement.getTextContent();
235 if (baseType instanceof InstanceIdentifierType) {
236 value = InstanceIdentifierForXmlCodec.deserialize(xmlElement, schemaCtx);
237 } else if (baseType instanceof IdentityrefTypeDefinition) {
238 value = InstanceIdentifierForXmlCodec.toIdentity(text, xmlElement, schemaCtx);
240 final TypeDefinitionAwareCodec<?, ?> codec = codecProvider.codecFor(schema.getType());
242 LOG.info("No codec for schema {}, falling back to text", schema);
245 value = codec.deserialize(text);
249 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
250 return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
253 private static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafListSchemaNode schema,
254 final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
257 if (schema.getType() instanceof InstanceIdentifierType) {
258 value = InstanceIdentifierForXmlCodec.deserialize(xmlElement, schemaCtx);
260 final TypeDefinitionAwareCodec<?, ?> codec = codecProvider.codecFor(schema.getType());
261 final String text = xmlElement.getTextContent();
264 LOG.info("No codec for schema {}, falling back to text", schema);
267 value = codec.deserialize(text);
271 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
272 return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
275 private static Node<?> toCompositeNodeWithSchema(final Element xmlElement, final QName qName, final DataNodeContainer schema,
276 final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
277 List<Node<?>> values = toDomNodes(xmlElement, Optional.fromNullable(schema.getChildNodes()),schemaCtx);
278 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
279 return ImmutableCompositeNode.create(qName, values, modifyAction.orNull());
282 public static Optional<ModifyAction> getModifyOperationFromAttributes(final Element xmlElement) {
283 Attr attributeNodeNS = xmlElement.getAttributeNodeNS(OPERATION_ATTRIBUTE_QNAME.getNamespace().toString(), OPERATION_ATTRIBUTE_QNAME.getLocalName());
284 if(attributeNodeNS == null) {
285 return Optional.absent();
288 ModifyAction action = ModifyAction.fromXmlValue(attributeNodeNS.getValue());
289 Preconditions.checkArgument(action.isOnElementPermitted(), "Unexpected operation %s on %s", action, xmlElement);
291 return Optional.of(action);
294 private static void checkQName(final Element xmlElement, final QName qName) {
295 checkState(Objects.equal(xmlElement.getNamespaceURI(), qName.getNamespace().toString()), "Not equal: %s to: %s for: %s and: %s", qName.getNamespace(), xmlElement.getNamespaceURI(), qName, xmlElement);
296 checkState(qName.getLocalName().equals(xmlElement.getLocalName()), "Not equal: %s to: %s for: %s and: %s", qName.getLocalName(), xmlElement.getLocalName(), qName, xmlElement);
299 public static final Optional<DataSchemaNode> findFirstSchema(final QName qname, final Iterable<DataSchemaNode> dataSchemaNode) {
300 if (dataSchemaNode != null && qname != null) {
301 for (DataSchemaNode dsn : dataSchemaNode) {
302 if (qname.isEqualWithoutRevision(dsn.getQName())) {
303 return Optional.<DataSchemaNode> of(dsn);
304 } else if (dsn instanceof ChoiceNode) {
305 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
306 Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
307 if (foundDsn != null && foundDsn.isPresent()) {
314 return Optional.absent();
317 public static Node<?> toDomNode(final Document doc) {
318 return toDomNode(doc.getDocumentElement());
321 private static Node<?> toDomNode(final Element element) {
322 QName qname = qNameFromElement(element);
324 ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
325 NodeList nodes = element.getChildNodes();
326 boolean isSimpleObject = true;
328 for (int i = 0; i < nodes.getLength(); i++) {
329 org.w3c.dom.Node child = nodes.item(i);
330 if (child instanceof Element) {
331 isSimpleObject = false;
332 values.add(toDomNode((Element) child));
334 if (isSimpleObject && child instanceof org.w3c.dom.Text) {
335 value = element.getTextContent();
336 if (!Strings.isNullOrEmpty(value)) {
337 isSimpleObject = true;
341 if (isSimpleObject) {
342 return new SimpleNodeTOImpl<>(qname, null, value);
344 return ImmutableCompositeNode.create(qname, values.build());
347 public static List<Node<?>> toDomNodes(final Element element, final Optional<? extends Iterable<DataSchemaNode>> context, final SchemaContext schemaCtx) {
348 return forEachChild(element.getChildNodes(),schemaCtx, new Function<ElementWithSchemaContext, Optional<Node<?>>>() {
351 public Optional<Node<?>> apply(final ElementWithSchemaContext input) {
352 if (context.isPresent()) {
353 QName partialQName = qNameFromElement(input.getElement());
354 Optional<DataSchemaNode> schemaNode = findFirstSchema(partialQName, context.get());
355 if (schemaNode.isPresent()) {
356 return Optional.<Node<?>> fromNullable(
357 toNodeWithSchema(input.getElement(), schemaNode.get(), XmlUtils.DEFAULT_XML_CODEC_PROVIDER, input.getSchemaContext()));
360 return Optional.<Node<?>> fromNullable(toDomNode(input.getElement()));
367 public static List<Node<?>> toDomNodes(final Element element, final Optional<? extends Iterable<DataSchemaNode>> context) {
368 return toDomNodes(element, context, null);
372 * Converts XML Document containing notification data from Netconf device to
373 * Data DOM Nodes. <br>
374 * By specification defined in <a
375 * href="http://tools.ietf.org/search/rfc6020#section-7.14">RFC 6020</a>
376 * there are xml elements containing notifications metadata, like eventTime
377 * or root notification element which specifies namespace for which is
378 * notification defined in yang model. Those elements MUST be stripped off
379 * notifications body. This method returns pure notification body which
380 * begins in element which is equal to notifications name defined in
381 * corresponding yang model. Rest of notification metadata are obfuscated,
382 * thus Data DOM contains only pure notification body.
385 * XML Document containing notification body
386 * @param notifications
387 * Notifications Definition Schema
388 * @return Data DOM Nodes containing xml notification body definition or
389 * <code>null</code> if there is no NotificationDefinition with
390 * Element with equal notification QName defined in XML Document.
392 public static CompositeNode notificationToDomNodes(final Document document,
393 final Optional<Set<NotificationDefinition>> notifications, final SchemaContext schemaCtx) {
394 if (notifications.isPresent() && (document != null) && (document.getDocumentElement() != null)) {
395 final NodeList originChildNodes = document.getDocumentElement().getChildNodes();
396 for (int i = 0; i < originChildNodes.getLength(); i++) {
397 org.w3c.dom.Node child = originChildNodes.item(i);
398 if (child instanceof Element) {
399 final Element childElement = (Element) child;
400 final QName partialQName = qNameFromElement(childElement);
401 final Optional<NotificationDefinition> notificationDef = findNotification(partialQName,
402 notifications.get());
403 if (notificationDef.isPresent()) {
404 final Iterable<DataSchemaNode> dataNodes = notificationDef.get().getChildNodes();
405 final List<Node<?>> domNodes = toDomNodes(childElement,
406 Optional.<Iterable<DataSchemaNode>> fromNullable(dataNodes),schemaCtx);
407 return ImmutableCompositeNode.create(notificationDef.get().getQName(), domNodes);
416 * Transforms XML Document representing Rpc output body into Composite Node structure based on Rpc definition
417 * within given Schema Context. The transformation is based on Rpc Definition which is defined in provided Schema Context.
418 * If Rpc Definition is missing from given Schema Context the method will return <code>null</code>
420 * @param document XML Document containing Output RPC message
421 * @param rpcName Rpc QName
422 * @param context Schema Context
423 * @return Rpc message in Composite Node data structures if Rpc definition is present within provided Schema Context, otherwise
424 * returns <code>null</code>
426 public static CompositeNode rpcReplyToDomNodes(final Document document, final QName rpcName,
427 final SchemaContext context) {
428 Preconditions.checkNotNull(document);
429 Preconditions.checkNotNull(rpcName);
430 Preconditions.checkNotNull(context);
432 Optional<RpcDefinition> rpcDefinition = findRpc(rpcName, context);
433 if (rpcDefinition.isPresent()) {
434 RpcDefinition rpc = rpcDefinition.get();
436 final Collection<DataSchemaNode> outputNode = rpc.getOutput() != null ? rpc.getOutput().getChildNodes() : null;
437 final Element rpcReplyElement = document.getDocumentElement();
438 final QName partialQName = qNameFromElement(rpcReplyElement);
440 if (RPC_REPLY_QNAME.equals(partialQName)) {
441 final List<Node<?>> domNodes = toDomNodes(rpcReplyElement, Optional.fromNullable(outputNode), context);
442 QName qName = rpc.getOutput() != null ? rpc.getOutput().getQName() : QName.cachedReference(QName.create(rpcName, "output"));
443 List<Node<?>> rpcOutNodes = Collections.<Node<?>>singletonList(ImmutableCompositeNode.create(
445 return ImmutableCompositeNode.create(rpcName, rpcOutNodes);
452 * Method searches given schema context for Rpc Definition with given QName.
453 * Returns Rpc Definition if is present within given Schema Context, otherwise returns Optional.absent().
455 * @param rpc Rpc QName
456 * @param context Schema Context
457 * @return Rpc Definition if is present within given Schema Context, otherwise returns Optional.absent().
459 private static Optional<RpcDefinition> findRpc(final QName rpc, final SchemaContext context) {
460 Preconditions.checkNotNull(rpc);
461 Preconditions.checkNotNull(context);
462 for (final RpcDefinition rpcDefinition : context.getOperations()) {
463 if ((rpcDefinition != null) && rpc.equals(rpcDefinition.getQName())) {
464 return Optional.of(rpcDefinition);
467 return Optional.absent();
470 public static CompositeNode notificationToDomNodes(final Document document,
471 final Optional<Set<NotificationDefinition>> notifications) {
472 return notificationToDomNodes(document, notifications,null);
475 private static Optional<NotificationDefinition> findNotification(final QName notifName,
476 final Set<NotificationDefinition> notifications) {
477 if ((notifName != null) && (notifications != null)) {
478 for (final NotificationDefinition notification : notifications) {
479 if ((notification != null) && notifName.isEqualWithoutRevision(notification.getQName())) {
480 return Optional.<NotificationDefinition>fromNullable(notification);
484 return Optional.<NotificationDefinition>absent();
487 private static final <T> List<T> forEachChild(final NodeList nodes, final SchemaContext schemaContext, final Function<ElementWithSchemaContext, Optional<T>> forBody) {
488 final int l = nodes.getLength();
490 return ImmutableList.of();
493 final List<T> list = new ArrayList<>(l);
494 for (int i = 0; i < l; i++) {
495 org.w3c.dom.Node child = nodes.item(i);
496 if (child instanceof Element) {
497 Optional<T> result = forBody.apply(new ElementWithSchemaContext((Element) child,schemaContext));
498 if (result.isPresent()) {
499 list.add(result.get());
503 return ImmutableList.copyOf(list);
506 public static final XmlCodecProvider defaultValueCodecProvider() {
507 return XmlUtils.DEFAULT_XML_CODEC_PROVIDER;