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 Object value = resolveValueFromSchemaType(xmlElement, schema, schema.getType(), codecProvider, schemaCtx);
232 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
233 return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
236 private static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafListSchemaNode schema,
237 final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
238 final Object value = resolveValueFromSchemaType(xmlElement, schema, schema.getType(), codecProvider, schemaCtx);
239 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
240 return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
243 private static Object resolveValueFromSchemaType(final Element xmlElement, final DataSchemaNode schema, final TypeDefinition<?> type,
244 final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
245 final TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
246 final String text = xmlElement.getTextContent();
249 if (baseType instanceof InstanceIdentifierType) {
250 value = InstanceIdentifierForXmlCodec.deserialize(xmlElement, schemaCtx);
251 } else if (baseType instanceof IdentityrefTypeDefinition) {
252 value = InstanceIdentifierForXmlCodec.toIdentity(text, xmlElement, schemaCtx);
254 final TypeDefinitionAwareCodec<?, ?> codec = codecProvider.codecFor(type);
256 LOG.info("No codec for schema {}, falling back to text", schema);
259 value = codec.deserialize(text);
265 private static Node<?> toCompositeNodeWithSchema(final Element xmlElement, final QName qName, final DataNodeContainer schema,
266 final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
267 List<Node<?>> values = toDomNodes(xmlElement, Optional.fromNullable(schema.getChildNodes()),schemaCtx);
268 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
269 return ImmutableCompositeNode.create(qName, values, modifyAction.orNull());
272 public static Optional<ModifyAction> getModifyOperationFromAttributes(final Element xmlElement) {
273 Attr attributeNodeNS = xmlElement.getAttributeNodeNS(OPERATION_ATTRIBUTE_QNAME.getNamespace().toString(), OPERATION_ATTRIBUTE_QNAME.getLocalName());
274 if(attributeNodeNS == null) {
275 return Optional.absent();
278 ModifyAction action = ModifyAction.fromXmlValue(attributeNodeNS.getValue());
279 Preconditions.checkArgument(action.isOnElementPermitted(), "Unexpected operation %s on %s", action, xmlElement);
281 return Optional.of(action);
284 private static void checkQName(final Element xmlElement, final QName qName) {
285 checkState(Objects.equal(xmlElement.getNamespaceURI(), qName.getNamespace().toString()), "Not equal: %s to: %s for: %s and: %s", qName.getNamespace(), xmlElement.getNamespaceURI(), qName, xmlElement);
286 checkState(qName.getLocalName().equals(xmlElement.getLocalName()), "Not equal: %s to: %s for: %s and: %s", qName.getLocalName(), xmlElement.getLocalName(), qName, xmlElement);
289 public static final Optional<DataSchemaNode> findFirstSchema(final QName qname, final Iterable<DataSchemaNode> dataSchemaNode) {
290 if (dataSchemaNode != null && qname != null) {
291 for (DataSchemaNode dsn : dataSchemaNode) {
292 if (qname.isEqualWithoutRevision(dsn.getQName())) {
293 return Optional.<DataSchemaNode> of(dsn);
294 } else if (dsn instanceof ChoiceNode) {
295 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
296 Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
297 if (foundDsn != null && foundDsn.isPresent()) {
304 return Optional.absent();
307 public static Node<?> toDomNode(final Document doc) {
308 return toDomNode(doc.getDocumentElement());
311 private static Node<?> toDomNode(final Element element) {
312 QName qname = qNameFromElement(element);
314 ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
315 NodeList nodes = element.getChildNodes();
316 boolean isSimpleObject = true;
318 for (int i = 0; i < nodes.getLength(); i++) {
319 org.w3c.dom.Node child = nodes.item(i);
320 if (child instanceof Element) {
321 isSimpleObject = false;
322 values.add(toDomNode((Element) child));
324 if (isSimpleObject && child instanceof org.w3c.dom.Text) {
325 value = element.getTextContent();
326 if (!Strings.isNullOrEmpty(value)) {
327 isSimpleObject = true;
331 if (isSimpleObject) {
332 return new SimpleNodeTOImpl<>(qname, null, value);
334 return ImmutableCompositeNode.create(qname, values.build());
337 public static List<Node<?>> toDomNodes(final Element element, final Optional<? extends Iterable<DataSchemaNode>> context, final SchemaContext schemaCtx) {
338 return forEachChild(element.getChildNodes(),schemaCtx, new Function<ElementWithSchemaContext, Optional<Node<?>>>() {
341 public Optional<Node<?>> apply(final ElementWithSchemaContext input) {
342 if (context.isPresent()) {
343 QName partialQName = qNameFromElement(input.getElement());
344 Optional<DataSchemaNode> schemaNode = findFirstSchema(partialQName, context.get());
345 if (schemaNode.isPresent()) {
346 return Optional.<Node<?>> fromNullable(
347 toNodeWithSchema(input.getElement(), schemaNode.get(), XmlUtils.DEFAULT_XML_CODEC_PROVIDER, input.getSchemaContext()));
350 return Optional.<Node<?>> fromNullable(toDomNode(input.getElement()));
357 public static List<Node<?>> toDomNodes(final Element element, final Optional<? extends Iterable<DataSchemaNode>> context) {
358 return toDomNodes(element, context, null);
362 * Converts XML Document containing notification data from Netconf device to
363 * Data DOM Nodes. <br>
364 * By specification defined in <a
365 * href="http://tools.ietf.org/search/rfc6020#section-7.14">RFC 6020</a>
366 * there are xml elements containing notifications metadata, like eventTime
367 * or root notification element which specifies namespace for which is
368 * notification defined in yang model. Those elements MUST be stripped off
369 * notifications body. This method returns pure notification body which
370 * begins in element which is equal to notifications name defined in
371 * corresponding yang model. Rest of notification metadata are obfuscated,
372 * thus Data DOM contains only pure notification body.
375 * XML Document containing notification body
376 * @param notifications
377 * Notifications Definition Schema
378 * @return Data DOM Nodes containing xml notification body definition or
379 * <code>null</code> if there is no NotificationDefinition with
380 * Element with equal notification QName defined in XML Document.
382 public static CompositeNode notificationToDomNodes(final Document document,
383 final Optional<Set<NotificationDefinition>> notifications, final SchemaContext schemaCtx) {
384 if (notifications.isPresent() && (document != null) && (document.getDocumentElement() != null)) {
385 final NodeList originChildNodes = document.getDocumentElement().getChildNodes();
386 for (int i = 0; i < originChildNodes.getLength(); i++) {
387 org.w3c.dom.Node child = originChildNodes.item(i);
388 if (child instanceof Element) {
389 final Element childElement = (Element) child;
390 final QName partialQName = qNameFromElement(childElement);
391 final Optional<NotificationDefinition> notificationDef = findNotification(partialQName,
392 notifications.get());
393 if (notificationDef.isPresent()) {
394 final Iterable<DataSchemaNode> dataNodes = notificationDef.get().getChildNodes();
395 final List<Node<?>> domNodes = toDomNodes(childElement,
396 Optional.<Iterable<DataSchemaNode>> fromNullable(dataNodes),schemaCtx);
397 return ImmutableCompositeNode.create(notificationDef.get().getQName(), domNodes);
406 * Transforms XML Document representing Rpc output body into Composite Node structure based on Rpc definition
407 * within given Schema Context. The transformation is based on Rpc Definition which is defined in provided Schema Context.
408 * If Rpc Definition is missing from given Schema Context the method will return <code>null</code>
410 * @param document XML Document containing Output RPC message
411 * @param rpcName Rpc QName
412 * @param context Schema Context
413 * @return Rpc message in Composite Node data structures if Rpc definition is present within provided Schema Context, otherwise
414 * returns <code>null</code>
416 public static CompositeNode rpcReplyToDomNodes(final Document document, final QName rpcName,
417 final SchemaContext context) {
418 Preconditions.checkNotNull(document);
419 Preconditions.checkNotNull(rpcName);
420 Preconditions.checkNotNull(context);
422 Optional<RpcDefinition> rpcDefinition = findRpc(rpcName, context);
423 if (rpcDefinition.isPresent()) {
424 RpcDefinition rpc = rpcDefinition.get();
426 final Collection<DataSchemaNode> outputNode = rpc.getOutput() != null ? rpc.getOutput().getChildNodes() : null;
427 final Element rpcReplyElement = document.getDocumentElement();
428 final QName partialQName = qNameFromElement(rpcReplyElement);
430 if (RPC_REPLY_QNAME.equals(partialQName)) {
431 final List<Node<?>> domNodes = toDomNodes(rpcReplyElement, Optional.fromNullable(outputNode), context);
432 QName qName = rpc.getOutput() != null ? rpc.getOutput().getQName() : QName.cachedReference(QName.create(rpcName, "output"));
433 List<Node<?>> rpcOutNodes = Collections.<Node<?>>singletonList(ImmutableCompositeNode.create(
435 return ImmutableCompositeNode.create(rpcName, rpcOutNodes);
442 * Method searches given schema context for Rpc Definition with given QName.
443 * Returns Rpc Definition if is present within given Schema Context, otherwise returns Optional.absent().
445 * @param rpc Rpc QName
446 * @param context Schema Context
447 * @return Rpc Definition if is present within given Schema Context, otherwise returns Optional.absent().
449 private static Optional<RpcDefinition> findRpc(final QName rpc, final SchemaContext context) {
450 Preconditions.checkNotNull(rpc);
451 Preconditions.checkNotNull(context);
452 for (final RpcDefinition rpcDefinition : context.getOperations()) {
453 if ((rpcDefinition != null) && rpc.equals(rpcDefinition.getQName())) {
454 return Optional.of(rpcDefinition);
457 return Optional.absent();
460 public static CompositeNode notificationToDomNodes(final Document document,
461 final Optional<Set<NotificationDefinition>> notifications) {
462 return notificationToDomNodes(document, notifications,null);
465 private static Optional<NotificationDefinition> findNotification(final QName notifName,
466 final Set<NotificationDefinition> notifications) {
467 if ((notifName != null) && (notifications != null)) {
468 for (final NotificationDefinition notification : notifications) {
469 if ((notification != null) && notifName.isEqualWithoutRevision(notification.getQName())) {
470 return Optional.<NotificationDefinition>fromNullable(notification);
474 return Optional.<NotificationDefinition>absent();
477 private static final <T> List<T> forEachChild(final NodeList nodes, final SchemaContext schemaContext, final Function<ElementWithSchemaContext, Optional<T>> forBody) {
478 final int l = nodes.getLength();
480 return ImmutableList.of();
483 final List<T> list = new ArrayList<>(l);
484 for (int i = 0; i < l; i++) {
485 org.w3c.dom.Node child = nodes.item(i);
486 if (child instanceof Element) {
487 Optional<T> result = forBody.apply(new ElementWithSchemaContext((Element) child,schemaContext));
488 if (result.isPresent()) {
489 list.add(result.get());
493 return ImmutableList.copyOf(list);
496 public static final XmlCodecProvider defaultValueCodecProvider() {
497 return XmlUtils.DEFAULT_XML_CODEC_PROVIDER;