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;
13 import java.util.List;
14 import java.util.Map.Entry;
17 import javax.activation.UnsupportedDataTypeException;
18 import javax.xml.parsers.DocumentBuilder;
19 import javax.xml.parsers.DocumentBuilderFactory;
20 import javax.xml.parsers.ParserConfigurationException;
22 import org.opendaylight.yangtools.yang.common.QName;
23 import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
24 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
25 import org.opendaylight.yangtools.yang.data.api.Node;
26 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
27 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
28 import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
29 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
30 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
31 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
32 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
33 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
35 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
40 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
42 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45 import org.w3c.dom.Document;
46 import org.w3c.dom.Element;
47 import org.w3c.dom.NodeList;
49 import com.google.common.base.Function;
50 import com.google.common.base.Objects;
51 import com.google.common.base.Optional;
52 import com.google.common.base.Preconditions;
53 import com.google.common.base.Strings;
54 import com.google.common.collect.ImmutableList;
56 public class XmlDocumentUtils {
58 private static final XmlCodecProvider DEFAULT_XML_VALUE_CODEC_PROVIDER = new XmlCodecProvider() {
61 public TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codecFor(TypeDefinition<?> baseType) {
62 return TypeDefinitionAwareCodec.from(baseType);
66 private static final Logger logger = LoggerFactory.getLogger(XmlDocumentUtils.class);
68 public static Document toDocument(CompositeNode data, DataNodeContainer schema, XmlCodecProvider codecProvider)
69 throws UnsupportedDataTypeException {
70 Preconditions.checkNotNull(data);
71 Preconditions.checkNotNull(schema);
73 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
76 DocumentBuilder bob = dbf.newDocumentBuilder();
77 doc = bob.newDocument();
78 } catch (ParserConfigurationException e) {
82 if (schema instanceof ContainerSchemaNode || schema instanceof ListSchemaNode) {
83 doc.appendChild(createXmlRootElement(doc, data, (SchemaNode) schema, codecProvider));
86 throw new UnsupportedDataTypeException(
87 "Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
91 private static Element createXmlRootElement(Document doc, Node<?> data, SchemaNode schema,
92 XmlCodecProvider codecProvider) throws UnsupportedDataTypeException {
93 Element itemEl = createElementFor(doc, data);
94 if (data instanceof SimpleNode<?>) {
95 if (schema instanceof LeafListSchemaNode) {
96 writeValueByType(itemEl, (SimpleNode<?>) data, ((LeafListSchemaNode) schema).getType(),
97 (DataSchemaNode) schema, codecProvider);
98 } else if (schema instanceof LeafSchemaNode) {
99 writeValueByType(itemEl, (SimpleNode<?>) data, ((LeafSchemaNode) schema).getType(),
100 (DataSchemaNode) schema, codecProvider);
102 Object value = data.getValue();
104 itemEl.setTextContent(String.valueOf(value));
107 } else { // CompositeNode
108 for (Node<?> child : ((CompositeNode) data).getChildren()) {
109 DataSchemaNode childSchema = null;
110 if (schema != null) {
111 childSchema = findFirstSchemaForNode(child, ((DataNodeContainer) schema).getChildNodes());
112 if (logger.isDebugEnabled()) {
113 if (childSchema == null) {
114 logger.debug("Probably the data node \""
115 + ((child == null) ? "" : child.getNodeType().getLocalName())
116 + "\" is not conform to schema");
120 itemEl.appendChild(createXmlRootElement(doc, child, childSchema, codecProvider));
126 private static Element createElementFor(Document doc, Node<?> data) {
127 QName dataType = data.getNodeType();
129 if (dataType.getNamespace() != null) {
130 ret = doc.createElementNS(dataType.getNamespace().toString(), dataType.getLocalName());
132 ret = doc.createElementNS(null, dataType.getLocalName());
134 if (data instanceof AttributesContainer && ((AttributesContainer) data).getAttributes() != null) {
135 for (Entry<QName, String> attribute : ((AttributesContainer) data).getAttributes().entrySet()) {
136 ret.setAttributeNS(attribute.getKey().getNamespace().toString(), attribute.getKey().getLocalName(),
137 attribute.getValue());
144 public static void writeValueByType(Element element, SimpleNode<?> node, TypeDefinition<?> type,
145 DataSchemaNode schema, XmlCodecProvider codecProvider) {
147 TypeDefinition<?> baseType = resolveBaseTypeFrom(type);
149 if (baseType instanceof IdentityrefTypeDefinition) {
150 if (node.getValue() instanceof QName) {
151 QName value = (QName) node.getValue();
153 if (value.getPrefix() != null && !value.getPrefix().isEmpty()) {
154 prefix = value.getPrefix();
156 element.setAttribute("xmlns:" + prefix, value.getNamespace().toString());
157 element.setTextContent(prefix + ":" + value.getLocalName());
159 Object value = node.getValue();
160 logger.debug("Value of {}:{} is not instance of QName but is {}", baseType.getQName().getNamespace(), //
161 baseType.getQName().getLocalName(), //
162 value != null ? value.getClass() : "null");
164 element.setTextContent(String.valueOf(value));
168 if (node.getValue() != null) {
169 final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
172 final String text = codec.serialize(node.getValue());
173 element.setTextContent(text);
174 } catch (ClassCastException e) {
175 logger.error("Provided node did not have type required by mapping. Using stream instead.", e);
176 element.setTextContent(String.valueOf(node.getValue()));
179 logger.error("Failed to find codec for {}, falling back to using stream", baseType);
180 element.setTextContent(String.valueOf(node.getValue()));
186 public final static TypeDefinition<?> resolveBaseTypeFrom(TypeDefinition<?> type) {
187 TypeDefinition<?> superType = type;
188 while (superType.getBaseType() != null) {
189 superType = superType.getBaseType();
194 private static final DataSchemaNode findFirstSchemaForNode(Node<?> node, Set<DataSchemaNode> dataSchemaNode) {
195 if (dataSchemaNode != null && node != null) {
196 for (DataSchemaNode dsn : dataSchemaNode) {
197 if (node.getNodeType().getLocalName().equals(dsn.getQName().getLocalName())) {
199 } else if (dsn instanceof ChoiceNode) {
200 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
201 DataSchemaNode foundDsn = findFirstSchemaForNode(node, choiceCase.getChildNodes());
202 if (foundDsn != null) {
212 public static Node<?> toDomNode(Element xmlElement, Optional<DataSchemaNode> schema,
213 Optional<XmlCodecProvider> codecProvider) {
214 if (schema.isPresent()) {
215 return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(DEFAULT_XML_VALUE_CODEC_PROVIDER));
217 return toDomNode(xmlElement);
220 public static CompositeNode fromElement(Element xmlElement) {
221 CompositeNodeBuilder<ImmutableCompositeNode> node = ImmutableCompositeNode.builder();
222 node.setQName(qNameFromElement(xmlElement));
224 return node.toInstance();
227 private static QName qNameFromElement(Element xmlElement) {
228 String namespace = xmlElement.getNamespaceURI();
229 String localName = xmlElement.getLocalName();
230 return QName.create(namespace != null ? URI.create(namespace) : null, null, localName);
233 private static Node<?> toNodeWithSchema(Element xmlElement, DataSchemaNode schema, XmlCodecProvider codecProvider) {
234 checkQName(xmlElement, schema.getQName());
235 if (schema instanceof DataNodeContainer) {
236 return toCompositeNodeWithSchema(xmlElement, schema.getQName(), (DataNodeContainer) schema, codecProvider);
237 } else if (schema instanceof LeafSchemaNode) {
238 return toSimpleNodeWithType(xmlElement, (LeafSchemaNode) schema, codecProvider);
239 } else if (schema instanceof LeafListSchemaNode) {
240 return toSimpleNodeWithType(xmlElement, (LeafListSchemaNode) schema, codecProvider);
246 private static Node<?> toSimpleNodeWithType(Element xmlElement, LeafSchemaNode schema,
247 XmlCodecProvider codecProvider) {
248 TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
249 String text = xmlElement.getTextContent();
252 value = codec.deserialize(text);
255 value = xmlElement.getTextContent();
257 return new SimpleNodeTOImpl<Object>(schema.getQName(), null, value);
260 private static Node<?> toSimpleNodeWithType(Element xmlElement, LeafListSchemaNode schema,
261 XmlCodecProvider codecProvider) {
262 TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
263 String text = xmlElement.getTextContent();
266 value = codec.deserialize(text);
269 value = xmlElement.getTextContent();
271 return new SimpleNodeTOImpl<Object>(schema.getQName(), null, value);
274 private static Node<?> toCompositeNodeWithSchema(Element xmlElement, QName qName, DataNodeContainer schema,
275 XmlCodecProvider codecProvider) {
276 List<Node<?>> values = toDomNodes(xmlElement, Optional.fromNullable(schema.getChildNodes()));
277 return ImmutableCompositeNode.create(qName, values);
280 private static void checkQName(Element xmlElement, QName qName) {
281 checkState(Objects.equal(xmlElement.getNamespaceURI(), qName.getNamespace().toString()));
282 checkState(qName.getLocalName().equals(xmlElement.getLocalName()));
285 private static final Optional<DataSchemaNode> findFirstSchema(QName qname, Set<DataSchemaNode> dataSchemaNode) {
286 if (dataSchemaNode != null && !dataSchemaNode.isEmpty() && qname != null) {
287 for (DataSchemaNode dsn : dataSchemaNode) {
288 if (qname.isEqualWithoutRevision(dsn.getQName())) {
289 return Optional.<DataSchemaNode> of(dsn);
290 } else if (dsn instanceof ChoiceNode) {
291 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
292 Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
293 if (foundDsn != null) {
300 return Optional.absent();
303 public static Node<?> toDomNode(Document doc) {
304 return toDomNode(doc.getDocumentElement());
307 private static Node<?> toDomNode(Element element) {
308 QName qname = qNameFromElement(element);
310 ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
311 NodeList nodes = element.getChildNodes();
312 boolean isSimpleObject = true;
314 for (int i = 0; i < nodes.getLength(); i++) {
315 org.w3c.dom.Node child = nodes.item(i);
316 if (child instanceof Element) {
317 isSimpleObject = false;
318 values.add(toDomNode((Element) child));
320 if (isSimpleObject && child instanceof org.w3c.dom.Text) {
321 value = element.getTextContent();
322 if (!Strings.isNullOrEmpty(value)) {
323 isSimpleObject = true;
327 if (isSimpleObject) {
328 return new SimpleNodeTOImpl<>(qname, null, value);
330 return ImmutableCompositeNode.create(qname, values.build());
333 public static List<Node<?>> toDomNodes(final Element element, final Optional<Set<DataSchemaNode>> context) {
334 return forEachChild(element.getChildNodes(), new Function<Element, Optional<Node<?>>>() {
337 public Optional<Node<?>> apply(Element input) {
338 if (context.isPresent()) {
339 QName partialQName = qNameFromElement(input);
340 Optional<DataSchemaNode> schemaNode = findFirstSchema(partialQName, context.get());
341 if (schemaNode.isPresent()) {
342 return Optional.<Node<?>> fromNullable(//
343 toNodeWithSchema(input, schemaNode.get(), DEFAULT_XML_VALUE_CODEC_PROVIDER));
346 return Optional.<Node<?>> fromNullable(toDomNode(element));
354 * Converts XML Document containing notification data from Netconf device to
355 * Data DOM Nodes. <br>
356 * By specification defined in <a
357 * href="http://tools.ietf.org/search/rfc6020#section-7.14">RFC 6020</a>
358 * there are xml elements containing notifications metadata, like eventTime
359 * or root notification element which specifies namespace for which is
360 * notification defined in yang model. Those elements MUST be stripped off
361 * notifications body. This method returns pure notification body which
362 * begins in element which is equal to notifications name defined in
363 * corresponding yang model. Rest of notification metadata are obfuscated,
364 * thus Data DOM contains only pure notification body.
367 * XML Document containing notification body
368 * @param notifications
369 * Notifications Definition Schema
370 * @return Data DOM Nodes containing xml notification body definition or
371 * <code>null</code> if there is no NotificationDefinition with
372 * Element with equal notification QName defined in XML Document.
374 public static CompositeNode notificationToDomNodes(final Document document,
375 final Optional<Set<NotificationDefinition>> notifications) {
376 if (notifications.isPresent() && (document != null) && (document.getDocumentElement() != null)) {
377 final NodeList originChildNodes = document.getDocumentElement().getChildNodes();
379 for (int i = 0; i < originChildNodes.getLength(); i++) {
380 org.w3c.dom.Node child = originChildNodes.item(i);
381 if (child instanceof Element) {
382 final Element childElement = (Element) child;
383 final QName partialQName = qNameFromElement(childElement);
384 final Optional<NotificationDefinition> notificationDef = findNotification(partialQName,
385 notifications.get());
386 if (notificationDef.isPresent()) {
387 final Set<DataSchemaNode> dataNodes = notificationDef.get().getChildNodes();
388 final List<Node<?>> domNodes = toDomNodes(childElement,
389 Optional.<Set<DataSchemaNode>> fromNullable(dataNodes));
390 return ImmutableCompositeNode.create(partialQName, domNodes);
398 private static Optional<NotificationDefinition> findNotification(final QName notifName,
399 final Set<NotificationDefinition> notifications) {
400 if ((notifName != null) && (notifications != null)) {
401 for (final NotificationDefinition notification : notifications) {
402 if ((notification != null) && notifName.isEqualWithoutRevision(notification.getQName())) {
403 return Optional.<NotificationDefinition>fromNullable(notification);
407 return Optional.<NotificationDefinition>absent();
410 private static final <T> List<T> forEachChild(NodeList nodes, Function<Element, Optional<T>> forBody) {
411 ImmutableList.Builder<T> ret = ImmutableList.<T> builder();
412 for (int i = 0; i < nodes.getLength(); i++) {
413 org.w3c.dom.Node child = nodes.item(i);
414 if (child instanceof Element) {
415 Optional<T> result = forBody.apply((Element) child);
416 if (result.isPresent()) {
417 ret.add(result.get());
424 public static final XmlCodecProvider defaultValueCodecProvider() {
425 return DEFAULT_XML_VALUE_CODEC_PROVIDER;