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.Collection;
14 import java.util.HashMap;
15 import java.util.List;
17 import java.util.Map.Entry;
18 import java.util.Random;
21 import javax.activation.UnsupportedDataTypeException;
22 import javax.xml.parsers.DocumentBuilder;
23 import javax.xml.parsers.DocumentBuilderFactory;
24 import javax.xml.parsers.ParserConfigurationException;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
28 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
29 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
31 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
32 import org.opendaylight.yangtools.yang.data.api.Node;
33 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
34 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
35 import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
36 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
37 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
38 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
39 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
40 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
42 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
47 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
49 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
50 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.w3c.dom.Document;
54 import org.w3c.dom.Element;
55 import org.w3c.dom.NodeList;
57 import com.google.common.base.Function;
58 import com.google.common.base.Objects;
59 import com.google.common.base.Optional;
60 import com.google.common.base.Preconditions;
61 import com.google.common.base.Strings;
62 import com.google.common.collect.ImmutableList;
64 public class XmlDocumentUtils {
66 private static final XmlCodecProvider DEFAULT_XML_VALUE_CODEC_PROVIDER = new XmlCodecProvider() {
69 public TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codecFor(TypeDefinition<?> baseType) {
70 return TypeDefinitionAwareCodec.from(baseType);
74 private static final Logger logger = LoggerFactory.getLogger(XmlDocumentUtils.class);
76 public static Document toDocument(CompositeNode data, DataNodeContainer schema, XmlCodecProvider codecProvider)
77 throws UnsupportedDataTypeException {
78 Preconditions.checkNotNull(data);
79 Preconditions.checkNotNull(schema);
81 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
84 DocumentBuilder bob = dbf.newDocumentBuilder();
85 doc = bob.newDocument();
86 } catch (ParserConfigurationException e) {
90 if (schema instanceof ContainerSchemaNode || schema instanceof ListSchemaNode) {
91 doc.appendChild(createXmlRootElement(doc, data, (SchemaNode) schema, codecProvider));
94 throw new UnsupportedDataTypeException(
95 "Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
99 private static Element createXmlRootElement(Document doc, Node<?> data, SchemaNode schema,
100 XmlCodecProvider codecProvider) throws UnsupportedDataTypeException {
101 Element itemEl = createElementFor(doc, data);
102 if (data instanceof SimpleNode<?>) {
103 if (schema instanceof LeafListSchemaNode) {
104 writeValueByType(itemEl, (SimpleNode<?>) data, ((LeafListSchemaNode) schema).getType(),
105 (DataSchemaNode) schema, codecProvider);
106 } else if (schema instanceof LeafSchemaNode) {
107 writeValueByType(itemEl, (SimpleNode<?>) data, ((LeafSchemaNode) schema).getType(),
108 (DataSchemaNode) schema, codecProvider);
110 Object value = data.getValue();
112 itemEl.setTextContent(String.valueOf(value));
115 } else { // CompositeNode
116 for (Node<?> child : ((CompositeNode) data).getChildren()) {
117 DataSchemaNode childSchema = null;
118 if (schema != null) {
119 childSchema = findFirstSchemaForNode(child, ((DataNodeContainer) schema).getChildNodes());
120 if (logger.isDebugEnabled()) {
121 if (childSchema == null) {
122 logger.debug("Probably the data node \""
123 + ((child == null) ? "" : child.getNodeType().getLocalName())
124 + "\" is not conform to schema");
128 itemEl.appendChild(createXmlRootElement(doc, child, childSchema, codecProvider));
134 private static Element createElementFor(Document doc, Node<?> data) {
135 QName dataType = data.getNodeType();
137 if (dataType.getNamespace() != null) {
138 ret = doc.createElementNS(dataType.getNamespace().toString(), dataType.getLocalName());
140 ret = doc.createElementNS(null, dataType.getLocalName());
142 if (data instanceof AttributesContainer && ((AttributesContainer) data).getAttributes() != null) {
143 for (Entry<QName, String> attribute : ((AttributesContainer) data).getAttributes().entrySet()) {
144 ret.setAttributeNS(attribute.getKey().getNamespace().toString(), attribute.getKey().getLocalName(),
145 attribute.getValue());
152 public static void writeValueByType(Element element, SimpleNode<?> node, TypeDefinition<?> type,
153 DataSchemaNode schema, XmlCodecProvider codecProvider) {
154 TypeDefinition<?> baseType = resolveBaseTypeFrom(type);
156 if (baseType instanceof IdentityrefTypeDefinition) {
157 if (node.getValue() instanceof QName) {
158 QName value = (QName) node.getValue();
160 if (value.getPrefix() != null && !value.getPrefix().isEmpty()) {
161 prefix = value.getPrefix();
163 element.setAttribute("xmlns:" + prefix, value.getNamespace().toString());
164 element.setTextContent(prefix + ":" + value.getLocalName());
166 Object value = node.getValue();
167 logger.debug("Value of {}:{} is not instance of QName but is {}", baseType.getQName().getNamespace(),
168 baseType.getQName().getLocalName(), value != null ? value.getClass() : "null");
170 element.setTextContent(String.valueOf(value));
173 } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
174 if (node.getValue() instanceof InstanceIdentifier) {
175 // Map< key = namespace, value = prefix>
176 Map<String, String> prefixes = new HashMap<>();
177 InstanceIdentifier instanceIdentifier = (InstanceIdentifier) node.getValue();
178 StringBuilder textContent = new StringBuilder();
179 for (PathArgument pathArgument : instanceIdentifier.getPath()) {
180 textContent.append("/");
181 writeIdentifierWithNamespacePrefix(element, textContent, pathArgument.getNodeType(), prefixes);
182 if (pathArgument instanceof NodeIdentifierWithPredicates) {
183 Map<QName, Object> predicates = ((NodeIdentifierWithPredicates) pathArgument).getKeyValues();
185 for (QName keyValue : predicates.keySet()) {
186 String predicateValue = String.valueOf(predicates.get(keyValue));
187 textContent.append("[");
188 writeIdentifierWithNamespacePrefix(element, textContent, keyValue, prefixes);
189 textContent.append("='");
190 textContent.append(predicateValue);
191 textContent.append("'");
192 textContent.append("]");
196 element.setTextContent(textContent.toString());
199 Object value = node.getValue();
200 logger.debug("Value of {}:{} is not instance of InstanceIdentifier but is {}", baseType.getQName()
202 baseType.getQName().getLocalName(), value != null ? value.getClass() : "null");
204 element.setTextContent(String.valueOf(value));
208 if (node.getValue() != null) {
209 final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
212 final String text = codec.serialize(node.getValue());
213 element.setTextContent(text);
214 } catch (ClassCastException e) {
215 logger.error("Provided node did not have type required by mapping. Using stream instead.", e);
216 element.setTextContent(String.valueOf(node.getValue()));
219 logger.error("Failed to find codec for {}, falling back to using stream", baseType);
220 element.setTextContent(String.valueOf(node.getValue()));
226 private static void writeIdentifierWithNamespacePrefix(Element element, StringBuilder textContent, QName qName,
227 Map<String, String> prefixes) {
228 String namespace = qName.getNamespace().toString();
229 String prefix = prefixes.get(namespace);
230 if (prefix == null) {
231 prefix = qName.getPrefix();
232 if (prefix == null || prefix.isEmpty() || prefixes.containsValue(prefix)) {
233 prefix = generateNewPrefix(prefixes.values());
237 element.setAttribute("xmlns:" + prefix, namespace.toString());
238 textContent.append(prefix);
239 prefixes.put(namespace, prefix);
241 textContent.append(":");
242 textContent.append(qName.getLocalName());
245 private static String generateNewPrefix(Collection<String> prefixes) {
246 StringBuilder result = null;
247 Random random = new Random();
249 result = new StringBuilder();
250 for (int i = 0; i < 4; i++) {
251 int randomNumber = 0x61 + (Math.abs(random.nextInt()) % 26);
252 result.append(Character.toChars(randomNumber));
254 } while (prefixes.contains(result.toString()));
256 return result.toString();
259 public final static TypeDefinition<?> resolveBaseTypeFrom(TypeDefinition<?> type) {
260 TypeDefinition<?> superType = type;
261 while (superType.getBaseType() != null) {
262 superType = superType.getBaseType();
267 private static final DataSchemaNode findFirstSchemaForNode(Node<?> node, Set<DataSchemaNode> dataSchemaNode) {
268 if (dataSchemaNode != null && node != null) {
269 for (DataSchemaNode dsn : dataSchemaNode) {
270 if (node.getNodeType().getLocalName().equals(dsn.getQName().getLocalName())) {
272 } else if (dsn instanceof ChoiceNode) {
273 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
274 DataSchemaNode foundDsn = findFirstSchemaForNode(node, choiceCase.getChildNodes());
275 if (foundDsn != null) {
285 public static Node<?> toDomNode(Element xmlElement, Optional<DataSchemaNode> schema,
286 Optional<XmlCodecProvider> codecProvider) {
287 if (schema.isPresent()) {
288 return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(DEFAULT_XML_VALUE_CODEC_PROVIDER));
290 return toDomNode(xmlElement);
293 public static CompositeNode fromElement(Element xmlElement) {
294 CompositeNodeBuilder<ImmutableCompositeNode> node = ImmutableCompositeNode.builder();
295 node.setQName(qNameFromElement(xmlElement));
297 return node.toInstance();
300 private static QName qNameFromElement(Element xmlElement) {
301 String namespace = xmlElement.getNamespaceURI();
302 String localName = xmlElement.getLocalName();
303 return QName.create(namespace != null ? URI.create(namespace) : null, null, localName);
306 private static Node<?> toNodeWithSchema(Element xmlElement, DataSchemaNode schema, XmlCodecProvider codecProvider) {
307 checkQName(xmlElement, schema.getQName());
308 if (schema instanceof DataNodeContainer) {
309 return toCompositeNodeWithSchema(xmlElement, schema.getQName(), (DataNodeContainer) schema, codecProvider);
310 } else if (schema instanceof LeafSchemaNode) {
311 return toSimpleNodeWithType(xmlElement, (LeafSchemaNode) schema, codecProvider);
312 } else if (schema instanceof LeafListSchemaNode) {
313 return toSimpleNodeWithType(xmlElement, (LeafListSchemaNode) schema, codecProvider);
319 private static Node<?> toSimpleNodeWithType(Element xmlElement, LeafSchemaNode schema,
320 XmlCodecProvider codecProvider) {
321 TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
322 String text = xmlElement.getTextContent();
325 value = codec.deserialize(text);
328 value = xmlElement.getTextContent();
330 return new SimpleNodeTOImpl<Object>(schema.getQName(), null, value);
333 private static Node<?> toSimpleNodeWithType(Element xmlElement, LeafListSchemaNode schema,
334 XmlCodecProvider codecProvider) {
335 TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
336 String text = xmlElement.getTextContent();
339 value = codec.deserialize(text);
342 value = xmlElement.getTextContent();
344 return new SimpleNodeTOImpl<Object>(schema.getQName(), null, value);
347 private static Node<?> toCompositeNodeWithSchema(Element xmlElement, QName qName, DataNodeContainer schema,
348 XmlCodecProvider codecProvider) {
349 List<Node<?>> values = toDomNodes(xmlElement, Optional.fromNullable(schema.getChildNodes()));
350 return ImmutableCompositeNode.create(qName, values);
353 private static void checkQName(Element xmlElement, QName qName) {
354 checkState(Objects.equal(xmlElement.getNamespaceURI(), qName.getNamespace().toString()));
355 checkState(qName.getLocalName().equals(xmlElement.getLocalName()));
358 private static final Optional<DataSchemaNode> findFirstSchema(QName qname, Set<DataSchemaNode> dataSchemaNode) {
359 if (dataSchemaNode != null && !dataSchemaNode.isEmpty() && qname != null) {
360 for (DataSchemaNode dsn : dataSchemaNode) {
361 if (qname.isEqualWithoutRevision(dsn.getQName())) {
362 return Optional.<DataSchemaNode> of(dsn);
363 } else if (dsn instanceof ChoiceNode) {
364 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
365 Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
366 if (foundDsn != null) {
373 return Optional.absent();
376 public static Node<?> toDomNode(Document doc) {
377 return toDomNode(doc.getDocumentElement());
380 private static Node<?> toDomNode(Element element) {
381 QName qname = qNameFromElement(element);
383 ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
384 NodeList nodes = element.getChildNodes();
385 boolean isSimpleObject = true;
387 for (int i = 0; i < nodes.getLength(); i++) {
388 org.w3c.dom.Node child = nodes.item(i);
389 if (child instanceof Element) {
390 isSimpleObject = false;
391 values.add(toDomNode((Element) child));
393 if (isSimpleObject && child instanceof org.w3c.dom.Text) {
394 value = element.getTextContent();
395 if (!Strings.isNullOrEmpty(value)) {
396 isSimpleObject = true;
400 if (isSimpleObject) {
401 return new SimpleNodeTOImpl<>(qname, null, value);
403 return ImmutableCompositeNode.create(qname, values.build());
406 public static List<Node<?>> toDomNodes(final Element element, final Optional<Set<DataSchemaNode>> context) {
407 return forEachChild(element.getChildNodes(), new Function<Element, Optional<Node<?>>>() {
410 public Optional<Node<?>> apply(Element input) {
411 if (context.isPresent()) {
412 QName partialQName = qNameFromElement(input);
413 Optional<DataSchemaNode> schemaNode = findFirstSchema(partialQName, context.get());
414 if (schemaNode.isPresent()) {
415 return Optional.<Node<?>> fromNullable(//
416 toNodeWithSchema(input, schemaNode.get(), DEFAULT_XML_VALUE_CODEC_PROVIDER));
419 return Optional.<Node<?>> fromNullable(toDomNode(input));
427 * Converts XML Document containing notification data from Netconf device to
428 * Data DOM Nodes. <br>
429 * By specification defined in <a
430 * href="http://tools.ietf.org/search/rfc6020#section-7.14">RFC 6020</a>
431 * there are xml elements containing notifications metadata, like eventTime
432 * or root notification element which specifies namespace for which is
433 * notification defined in yang model. Those elements MUST be stripped off
434 * notifications body. This method returns pure notification body which
435 * begins in element which is equal to notifications name defined in
436 * corresponding yang model. Rest of notification metadata are obfuscated,
437 * thus Data DOM contains only pure notification body.
440 * XML Document containing notification body
441 * @param notifications
442 * Notifications Definition Schema
443 * @return Data DOM Nodes containing xml notification body definition or
444 * <code>null</code> if there is no NotificationDefinition with
445 * Element with equal notification QName defined in XML Document.
447 public static CompositeNode notificationToDomNodes(final Document document,
448 final Optional<Set<NotificationDefinition>> notifications) {
449 if (notifications.isPresent() && (document != null) && (document.getDocumentElement() != null)) {
450 final NodeList originChildNodes = document.getDocumentElement().getChildNodes();
452 for (int i = 0; i < originChildNodes.getLength(); i++) {
453 org.w3c.dom.Node child = originChildNodes.item(i);
454 if (child instanceof Element) {
455 final Element childElement = (Element) child;
456 final QName partialQName = qNameFromElement(childElement);
457 final Optional<NotificationDefinition> notificationDef = findNotification(partialQName,
458 notifications.get());
459 if (notificationDef.isPresent()) {
460 final Set<DataSchemaNode> dataNodes = notificationDef.get().getChildNodes();
461 final List<Node<?>> domNodes = toDomNodes(childElement,
462 Optional.<Set<DataSchemaNode>> fromNullable(dataNodes));
463 return ImmutableCompositeNode.create(notificationDef.get().getQName(), domNodes);
471 private static Optional<NotificationDefinition> findNotification(final QName notifName,
472 final Set<NotificationDefinition> notifications) {
473 if ((notifName != null) && (notifications != null)) {
474 for (final NotificationDefinition notification : notifications) {
475 if ((notification != null) && notifName.isEqualWithoutRevision(notification.getQName())) {
476 return Optional.<NotificationDefinition>fromNullable(notification);
480 return Optional.<NotificationDefinition>absent();
483 private static final <T> List<T> forEachChild(NodeList nodes, Function<Element, Optional<T>> forBody) {
484 ImmutableList.Builder<T> ret = ImmutableList.<T> builder();
485 for (int i = 0; i < nodes.getLength(); i++) {
486 org.w3c.dom.Node child = nodes.item(i);
487 if (child instanceof Element) {
488 Optional<T> result = forBody.apply((Element) child);
489 if (result.isPresent()) {
490 ret.add(result.get());
497 public static final XmlCodecProvider defaultValueCodecProvider() {
498 return DEFAULT_XML_VALUE_CODEC_PROVIDER;