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.controller.remote.rpc.utils;
10 import com.google.common.base.Function;
11 import com.google.common.base.Objects;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Strings;
15 import com.google.common.collect.ImmutableList;
16 import org.opendaylight.yangtools.yang.common.QName;
17 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
18 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
19 import org.opendaylight.yangtools.yang.data.api.Node;
20 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
21 import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
22 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
23 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlCodecProvider;
24 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
25 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
26 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
27 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
28 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
33 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
35 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import org.w3c.dom.Attr;
39 import org.w3c.dom.Document;
40 import org.w3c.dom.Element;
41 import org.w3c.dom.NodeList;
43 import javax.activation.UnsupportedDataTypeException;
44 import javax.xml.parsers.DocumentBuilder;
45 import javax.xml.parsers.DocumentBuilderFactory;
46 import javax.xml.parsers.ParserConfigurationException;
47 import javax.xml.stream.XMLOutputFactory;
48 import javax.xml.stream.XMLStreamException;
49 import javax.xml.stream.XMLStreamWriter;
50 import javax.xml.transform.dom.DOMResult;
52 import java.util.ArrayList;
53 import java.util.Collection;
54 import java.util.List;
56 import static com.google.common.base.Preconditions.checkState;
58 public class XmlDocumentUtils {
59 private static class ElementWithSchemaContext {
61 SchemaContext schemaContext;
63 ElementWithSchemaContext(final Element element,final SchemaContext schemaContext) {
64 this.schemaContext = schemaContext;
65 this.element = element;
68 Element getElement() {
72 SchemaContext getSchemaContext() {
77 public static final QName OPERATION_ATTRIBUTE_QNAME = QName.create(URI.create("urn:ietf:params:xml:ns:netconf:base:1.0"), null, "operation");
78 private static final Logger logger = LoggerFactory.getLogger(XmlDocumentUtils.class);
79 private static final XMLOutputFactory FACTORY = XMLOutputFactory.newFactory();
82 * Converts Data DOM structure to XML Document for specified XML Codec Provider and corresponding
83 * Data Node Container schema. The CompositeNode data parameter enters as root of Data DOM tree and will
84 * be transformed to root in XML Document. Each element of Data DOM tree is compared against specified Data
85 * Node Container Schema and transformed accordingly.
87 * @param data Data DOM root element
88 * @param schema Data Node Container Schema
89 * @param codecProvider XML Codec Provider
90 * @return new instance of XML Document
91 * @throws javax.activation.UnsupportedDataTypeException
93 public static Document toDocument(final CompositeNode data, final DataNodeContainer schema, final XmlCodecProvider codecProvider)
94 throws UnsupportedDataTypeException {
95 Preconditions.checkNotNull(data);
96 Preconditions.checkNotNull(schema);
98 if (!(schema instanceof ContainerSchemaNode || schema instanceof ListSchemaNode)) {
99 throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
102 final DOMResult result = new DOMResult(getDocument());
104 final XMLStreamWriter writer = FACTORY.createXMLStreamWriter(result);
105 XmlStreamUtils.create(codecProvider).writeDocument(writer, data, (SchemaNode)schema);
107 return (Document)result.getNode();
108 } catch (XMLStreamException e) {
109 logger.error("Failed to serialize data {}", data, e);
114 public static Document getDocument() {
115 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
118 DocumentBuilder bob = dbf.newDocumentBuilder();
119 doc = bob.newDocument();
120 } catch (ParserConfigurationException e) {
121 throw new RuntimeException(e);
127 public static QName qNameFromElement(final Element xmlElement) {
128 String namespace = xmlElement.getNamespaceURI();
129 String localName = xmlElement.getLocalName();
130 return QName.create(namespace != null ? URI.create(namespace) : null, null, localName);
133 private static Node<?> toNodeWithSchema(final Element xmlElement, final DataSchemaNode schema, final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
134 checkQName(xmlElement, schema.getQName());
135 if (schema instanceof DataNodeContainer) {
136 return toCompositeNodeWithSchema(xmlElement, schema.getQName(), (DataNodeContainer) schema, schemaCtx);
137 } else if (schema instanceof LeafSchemaNode) {
138 return toSimpleNodeWithType(xmlElement, (LeafSchemaNode) schema, codecProvider,schemaCtx);
139 } else if (schema instanceof LeafListSchemaNode) {
140 return toSimpleNodeWithType(xmlElement, (LeafListSchemaNode) schema, codecProvider,schemaCtx);
147 private static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafSchemaNode schema,
148 final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
149 TypeDefinitionAwareCodec<? extends Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
150 String text = xmlElement.getTextContent();
153 logger.debug("toSimpleNodeWithType: found codec, deserializing text {}", text);
154 value = codec.deserialize(text);
157 final TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(schema.getType());
158 if (baseType instanceof org.opendaylight.yangtools.yang.model.util.InstanceIdentifier) {
159 logger.debug("toSimpleNodeWithType: base type of node is instance identifier, deserializing element", xmlElement);
160 value = InstanceIdentifierForXmlCodec.deserialize(xmlElement,schemaCtx);
162 } else if(baseType instanceof IdentityrefTypeDefinition){
163 logger.debug("toSimpleNodeWithType: base type of node is IdentityrefTypeDefinition, deserializing element", xmlElement);
164 value = InstanceIdentifierForXmlCodec.toIdentity(xmlElement.getTextContent(), xmlElement, schemaCtx);
169 logger.debug("toSimpleNodeWithType: no type found for element, returning just the text string value of element {}", xmlElement);
170 value = xmlElement.getTextContent();
173 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
174 return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
177 private static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafListSchemaNode schema,
178 final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
179 TypeDefinitionAwareCodec<? extends Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
180 String text = xmlElement.getTextContent();
183 logger.debug("toSimpleNodeWithType: found codec, deserializing text {}", text);
184 value = codec.deserialize(text);
187 if (schema.getType() instanceof org.opendaylight.yangtools.yang.model.util.InstanceIdentifier) {
188 logger.debug("toSimpleNodeWithType: base type of node is instance identifier, deserializing element", xmlElement);
189 value = InstanceIdentifierForXmlCodec.deserialize(xmlElement,schemaCtx);
193 logger.debug("toSimpleNodeWithType: no type found for element, returning just the text string value of element {}", xmlElement);
194 value = xmlElement.getTextContent();
197 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
198 return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
201 private static Node<?> toCompositeNodeWithSchema(final Element xmlElement, final QName qName, final DataNodeContainer schema,
202 final SchemaContext schemaCtx) {
203 List<Node<?>> values = toDomNodes(xmlElement, Optional.fromNullable(schema.getChildNodes()),schemaCtx);
204 Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
205 return ImmutableCompositeNode.create(qName, values, modifyAction.orNull());
208 private static Optional<ModifyAction> getModifyOperationFromAttributes(final Element xmlElement) {
209 Attr attributeNodeNS = xmlElement.getAttributeNodeNS(OPERATION_ATTRIBUTE_QNAME.getNamespace().toString(), OPERATION_ATTRIBUTE_QNAME.getLocalName());
210 if(attributeNodeNS == null) {
211 return Optional.absent();
214 ModifyAction action = ModifyAction.fromXmlValue(attributeNodeNS.getValue());
215 Preconditions.checkArgument(action.isOnElementPermitted(), "Unexpected operation %s on %s", action, xmlElement);
217 return Optional.of(action);
220 private static void checkQName(final Element xmlElement, final QName qName) {
221 checkState(Objects.equal(xmlElement.getNamespaceURI(), qName.getNamespace().toString()));
222 checkState(qName.getLocalName().equals(xmlElement.getLocalName()));
225 public static final Optional<DataSchemaNode> findFirstSchema(final QName qname, final Collection<DataSchemaNode> dataSchemaNode) {
226 if (dataSchemaNode != null && !dataSchemaNode.isEmpty() && qname != null) {
227 for (DataSchemaNode dsn : dataSchemaNode) {
228 if (qname.isEqualWithoutRevision(dsn.getQName())) {
229 return Optional.<DataSchemaNode> of(dsn);
230 } else if (dsn instanceof ChoiceNode) {
231 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
232 Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
233 if (foundDsn != null && foundDsn.isPresent()) {
240 return Optional.absent();
243 private static Node<?> toDomNode(Element element) {
244 QName qname = qNameFromElement(element);
246 ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
247 NodeList nodes = element.getChildNodes();
248 boolean isSimpleObject = true;
250 for (int i = 0; i < nodes.getLength(); i++) {
251 org.w3c.dom.Node child = nodes.item(i);
252 if (child instanceof Element) {
253 isSimpleObject = false;
254 values.add(toDomNode((Element) child));
256 if (isSimpleObject && child instanceof org.w3c.dom.Text) {
257 value = element.getTextContent();
258 if (!Strings.isNullOrEmpty(value)) {
259 isSimpleObject = true;
263 if (isSimpleObject) {
264 return new SimpleNodeTOImpl<>(qname, null, value);
266 return ImmutableCompositeNode.create(qname, values.build());
269 public static List<Node<?>> toDomNodes(final Element element, final Optional<Collection<DataSchemaNode>> context,SchemaContext schemaCtx) {
270 return forEachChild(element.getChildNodes(),schemaCtx, new Function<ElementWithSchemaContext, Optional<Node<?>>>() {
273 public Optional<Node<?>> apply(ElementWithSchemaContext input) {
274 if (context.isPresent()) {
275 QName partialQName = qNameFromElement(input.getElement());
276 Optional<DataSchemaNode> schemaNode = XmlDocumentUtils.findFirstSchema(partialQName, context.get());
277 if (schemaNode.isPresent()) {
278 return Optional.<Node<?>> fromNullable(//
279 toNodeWithSchema(input.getElement(), schemaNode.get(), XmlDocumentUtils.defaultValueCodecProvider(),input.getSchemaContext()));
282 return Optional.<Node<?>> fromNullable(toDomNode(input.getElement()));
289 private static final <T> List<T> forEachChild(final NodeList nodes, final SchemaContext schemaContext, final Function<ElementWithSchemaContext, Optional<T>> forBody) {
290 final int l = nodes.getLength();
292 return ImmutableList.of();
295 final List<T> list = new ArrayList<>(l);
296 for (int i = 0; i < l; i++) {
297 org.w3c.dom.Node child = nodes.item(i);
298 if (child instanceof Element) {
299 Optional<T> result = forBody.apply(new ElementWithSchemaContext((Element) child,schemaContext));
300 if (result.isPresent()) {
301 list.add(result.get());
305 return ImmutableList.copyOf(list);
308 public static final XmlCodecProvider defaultValueCodecProvider() {
309 return XmlUtils.DEFAULT_XML_CODEC_PROVIDER;