Merge "added feature topology manager shell"
[controller.git] / opendaylight / md-sal / sal-remoterpc-connector / src / main / java / org / opendaylight / controller / remote / rpc / utils / XmlDocumentUtils.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.remote.rpc.utils;
9
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;
42
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;
51 import java.net.URI;
52 import java.util.ArrayList;
53 import java.util.Collection;
54 import java.util.List;
55
56 import static com.google.common.base.Preconditions.checkState;
57
58 public class XmlDocumentUtils {
59   private static class ElementWithSchemaContext {
60     Element element;
61     SchemaContext schemaContext;
62
63     ElementWithSchemaContext(final Element element,final SchemaContext schemaContext) {
64       this.schemaContext = schemaContext;
65       this.element = element;
66     }
67
68     Element getElement() {
69       return element;
70     }
71
72     SchemaContext getSchemaContext() {
73       return schemaContext;
74     }
75   }
76
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();
80
81   /**
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.
86    *
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
92    */
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);
97
98     if (!(schema instanceof ContainerSchemaNode || schema instanceof ListSchemaNode)) {
99       throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
100     }
101
102     final DOMResult result = new DOMResult(getDocument());
103     try {
104       final XMLStreamWriter writer = FACTORY.createXMLStreamWriter(result);
105       XmlStreamUtils.create(codecProvider).writeDocument(writer, data, (SchemaNode)schema);
106       writer.close();
107       return (Document)result.getNode();
108     } catch (XMLStreamException e) {
109       logger.error("Failed to serialize data {}", data, e);
110       return null;
111     }
112   }
113
114   public static Document getDocument() {
115     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
116     Document doc = null;
117     try {
118       DocumentBuilder bob = dbf.newDocumentBuilder();
119       doc = bob.newDocument();
120     } catch (ParserConfigurationException e) {
121       throw new RuntimeException(e);
122     }
123     return doc;
124   }
125
126
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);
131   }
132
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);
141     }
142     return null;
143   }
144
145
146
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();
151     Object value = null;
152     if (codec != null) {
153       logger.debug("toSimpleNodeWithType: found codec, deserializing text {}", text);
154       value = codec.deserialize(text);
155     }
156
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);
161
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);
165
166     }
167
168     if (value == null) {
169       logger.debug("toSimpleNodeWithType: no type found for element, returning just the text string value of element {}", xmlElement);
170       value = xmlElement.getTextContent();
171     }
172
173     Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
174     return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
175   }
176
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();
181     Object value = null;
182     if (codec != null) {
183       logger.debug("toSimpleNodeWithType: found codec, deserializing text {}", text);
184       value = codec.deserialize(text);
185     }
186
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);
190     }
191
192     if (value == null) {
193       logger.debug("toSimpleNodeWithType: no type found for element, returning just the text string value of element {}", xmlElement);
194       value = xmlElement.getTextContent();
195     }
196
197     Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
198     return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
199   }
200
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());
206   }
207
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();
212     }
213
214     ModifyAction action = ModifyAction.fromXmlValue(attributeNodeNS.getValue());
215     Preconditions.checkArgument(action.isOnElementPermitted(), "Unexpected operation %s on %s", action, xmlElement);
216
217     return Optional.of(action);
218   }
219
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()));
223   }
224
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()) {
234               return foundDsn;
235             }
236           }
237         }
238       }
239     }
240     return Optional.absent();
241   }
242
243   private static Node<?> toDomNode(Element element) {
244     QName qname = qNameFromElement(element);
245
246     ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
247     NodeList nodes = element.getChildNodes();
248     boolean isSimpleObject = true;
249     String value = null;
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));
255       }
256       if (isSimpleObject && child instanceof org.w3c.dom.Text) {
257         value = element.getTextContent();
258         if (!Strings.isNullOrEmpty(value)) {
259           isSimpleObject = true;
260         }
261       }
262     }
263     if (isSimpleObject) {
264       return new SimpleNodeTOImpl<>(qname, null, value);
265     }
266     return ImmutableCompositeNode.create(qname, values.build());
267   }
268
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<?>>>() {
271
272       @Override
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()));
280           }
281         }
282         return Optional.<Node<?>> fromNullable(toDomNode(input.getElement()));
283       }
284
285     });
286
287   }
288
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();
291     if (l == 0) {
292       return ImmutableList.of();
293     }
294
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());
302         }
303       }
304     }
305     return ImmutableList.copyOf(list);
306   }
307
308   public static final XmlCodecProvider defaultValueCodecProvider() {
309     return XmlUtils.DEFAULT_XML_CODEC_PROVIDER;
310   }
311 }