Mass migrate fields to use Immutable collections
[yangtools.git] / yang / yang-data-codec-xml / src / main / java / org / opendaylight / yangtools / yang / data / codec / xml / XmlParserStream.java
1 /*
2  * Copyright (c) 2016 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.yangtools.yang.data.codec.xml;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
13 import static org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter.TRANSFORMER_FACTORY;
14
15 import com.google.common.annotations.Beta;
16 import com.google.common.collect.ImmutableMap;
17 import java.io.Closeable;
18 import java.io.Flushable;
19 import java.io.IOException;
20 import java.net.URI;
21 import java.net.URISyntaxException;
22 import java.util.AbstractMap.SimpleImmutableEntry;
23 import java.util.Deque;
24 import java.util.HashSet;
25 import java.util.LinkedHashMap;
26 import java.util.Map;
27 import java.util.Map.Entry;
28 import java.util.Set;
29 import javax.annotation.concurrent.NotThreadSafe;
30 import javax.xml.XMLConstants;
31 import javax.xml.namespace.NamespaceContext;
32 import javax.xml.parsers.ParserConfigurationException;
33 import javax.xml.stream.Location;
34 import javax.xml.stream.XMLStreamConstants;
35 import javax.xml.stream.XMLStreamException;
36 import javax.xml.stream.XMLStreamReader;
37 import javax.xml.stream.util.StreamReaderDelegate;
38 import javax.xml.transform.TransformerException;
39 import javax.xml.transform.dom.DOMResult;
40 import javax.xml.transform.dom.DOMSource;
41 import javax.xml.transform.stax.StAXSource;
42 import org.opendaylight.yangtools.odlext.model.api.YangModeledAnyXmlSchemaNode;
43 import org.opendaylight.yangtools.yang.common.QName;
44 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
45 import org.opendaylight.yangtools.yang.data.util.AbstractNodeDataWithSchema;
46 import org.opendaylight.yangtools.yang.data.util.AnyXmlNodeDataWithSchema;
47 import org.opendaylight.yangtools.yang.data.util.CompositeNodeDataWithSchema;
48 import org.opendaylight.yangtools.yang.data.util.ContainerNodeDataWithSchema;
49 import org.opendaylight.yangtools.yang.data.util.LeafListEntryNodeDataWithSchema;
50 import org.opendaylight.yangtools.yang.data.util.LeafListNodeDataWithSchema;
51 import org.opendaylight.yangtools.yang.data.util.LeafNodeDataWithSchema;
52 import org.opendaylight.yangtools.yang.data.util.ListEntryNodeDataWithSchema;
53 import org.opendaylight.yangtools.yang.data.util.ListNodeDataWithSchema;
54 import org.opendaylight.yangtools.yang.data.util.ParserStreamUtils;
55 import org.opendaylight.yangtools.yang.data.util.RpcAsContainer;
56 import org.opendaylight.yangtools.yang.data.util.SimpleNodeDataWithSchema;
57 import org.opendaylight.yangtools.yang.data.util.YangModeledAnyXmlNodeDataWithSchema;
58 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
65 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
66 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
68 import org.w3c.dom.Document;
69 import org.xml.sax.SAXException;
70
71 /**
72  * This class provides functionality for parsing an XML source containing YANG-modeled data. It disallows multiple
73  * instances of the same element except for leaf-list and list entries. It also expects that the YANG-modeled data in
74  * the XML source are wrapped in a root element.
75  */
76 @Beta
77 @NotThreadSafe
78 public final class XmlParserStream implements Closeable, Flushable {
79
80     private static final String XML_STANDARD_VERSION = "1.0";
81
82     private final NormalizedNodeStreamWriter writer;
83     private final XmlCodecFactory codecs;
84     private final DataSchemaNode parentNode;
85     private final boolean strictParsing;
86
87     private XmlParserStream(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
88             final DataSchemaNode parentNode, final boolean strictParsing) {
89         this.writer = requireNonNull(writer);
90         this.codecs = requireNonNull(codecs);
91         this.parentNode = parentNode;
92         this.strictParsing = strictParsing;
93     }
94
95     /**
96      * Construct a new {@link XmlParserStream} with strict parsing mode switched on.
97      *
98      * @param writer Output writer
99      * @param codecs Shared codecs
100      * @param parentNode Parent root node
101      * @return A new stream instance
102      */
103     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
104             final SchemaNode parentNode) {
105         return create(writer, codecs, parentNode, true);
106     }
107
108     /**
109      * Construct a new {@link XmlParserStream}.
110      *
111      * @param writer Output writer
112      * @param codecs Shared codecs
113      * @param parentNode Parent root node
114      * @param strictParsing parsing mode
115      *            if set to true, the parser will throw an exception if it encounters unknown child nodes
116      *            (nodes, that are not defined in the provided SchemaContext) in containers and lists
117      *            if set to false, the parser will skip unknown child nodes
118      * @return A new stream instance
119      */
120     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
121             final SchemaNode parentNode, final boolean strictParsing) {
122         if (parentNode instanceof RpcDefinition) {
123             return new XmlParserStream(writer, codecs, new RpcAsContainer((RpcDefinition) parentNode), strictParsing);
124         }
125         checkArgument(parentNode instanceof DataSchemaNode, "Instance of DataSchemaNode class awaited.");
126         return new XmlParserStream(writer, codecs, (DataSchemaNode) parentNode, strictParsing);
127     }
128
129     /**
130      * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
131      * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
132      * maintain a {@link XmlCodecFactory} to match the current {@link SchemaContext}.
133      */
134     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
135             final SchemaNode parentNode) {
136         return create(writer, schemaContext, parentNode, true);
137     }
138
139     /**
140      * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
141      * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
142      * maintain a {@link XmlCodecFactory} to match the current {@link SchemaContext}.
143      */
144     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
145             final SchemaNode parentNode, final boolean strictParsing) {
146         return create(writer, XmlCodecFactory.create(schemaContext), parentNode, strictParsing);
147     }
148
149     /**
150      * This method parses the XML source and emits node events into a NormalizedNodeStreamWriter based on the
151      * YANG-modeled data contained in the XML source.
152      *
153      * @param reader
154      *              StAX reader which is to used to walk through the XML source
155      * @return
156      *              instance of XmlParserStream
157      * @throws XMLStreamException
158      *              if a well-formedness error or an unexpected processing condition occurs while parsing the XML
159      * @throws URISyntaxException
160      *              if the namespace URI of an XML element contains a syntax error
161      * @throws IOException
162      *              if an error occurs while parsing the value of an anyxml node
163      * @throws ParserConfigurationException
164      *              if an error occurs while parsing the value of an anyxml node
165      * @throws SAXException
166      *              if an error occurs while parsing the value of an anyxml node
167      */
168     // FIXME: 3.0.0 remove ParserConfigurationException
169     public XmlParserStream parse(final XMLStreamReader reader) throws XMLStreamException, URISyntaxException,
170             IOException, ParserConfigurationException, SAXException {
171         if (reader.hasNext()) {
172             reader.nextTag();
173             final AbstractNodeDataWithSchema nodeDataWithSchema;
174             if (parentNode instanceof ContainerSchemaNode) {
175                 nodeDataWithSchema = new ContainerNodeDataWithSchema(parentNode);
176             } else if (parentNode instanceof ListSchemaNode) {
177                 nodeDataWithSchema = new ListNodeDataWithSchema(parentNode);
178             } else if (parentNode instanceof YangModeledAnyXmlSchemaNode) {
179                 nodeDataWithSchema = new YangModeledAnyXmlNodeDataWithSchema((YangModeledAnyXmlSchemaNode) parentNode);
180             } else if (parentNode instanceof AnyXmlSchemaNode) {
181                 nodeDataWithSchema = new AnyXmlNodeDataWithSchema(parentNode);
182             } else if (parentNode instanceof LeafSchemaNode) {
183                 nodeDataWithSchema = new LeafNodeDataWithSchema(parentNode);
184             } else if (parentNode instanceof LeafListSchemaNode) {
185                 nodeDataWithSchema = new LeafListNodeDataWithSchema(parentNode);
186             } else {
187                 throw new IllegalStateException("Unsupported schema node type " + parentNode.getClass() + ".");
188             }
189
190             read(reader, nodeDataWithSchema, reader.getLocalName());
191             nodeDataWithSchema.write(writer);
192         }
193
194         return this;
195     }
196
197     /**
198      * This method traverses a {@link DOMSource} and emits node events into a NormalizedNodeStreamWriter based on the
199      * YANG-modeled data contained in the source.
200      *
201      * @param src
202      *              {@link DOMSource} to be traversed
203      * @return
204      *              instance of XmlParserStream
205      * @throws XMLStreamException
206      *              if a well-formedness error or an unexpected processing condition occurs while parsing the XML
207      * @throws URISyntaxException
208      *              if the namespace URI of an XML element contains a syntax error
209      * @throws IOException
210      *              if an error occurs while parsing the value of an anyxml node
211      * @throws ParserConfigurationException
212      *              if an error occurs while parsing the value of an anyxml node
213      * @throws SAXException
214      *              if an error occurs while parsing the value of an anyxml node
215      */
216     @Beta
217     // FIXME: 3.0.0 remove ParserConfigurationException
218     public XmlParserStream traverse(final DOMSource src) throws XMLStreamException, URISyntaxException,
219         IOException, ParserConfigurationException, SAXException {
220         return parse(new DOMSourceXMLStreamReader(src));
221     }
222
223     private static ImmutableMap<QName, String> getElementAttributes(final XMLStreamReader in) {
224         checkState(in.isStartElement(), "Attributes can be extracted only from START_ELEMENT.");
225         final Map<QName, String> attributes = new LinkedHashMap<>();
226
227         for (int attrIndex = 0; attrIndex < in.getAttributeCount(); attrIndex++) {
228             String attributeNS = in.getAttributeNamespace(attrIndex);
229
230             if (attributeNS == null) {
231                 attributeNS = "";
232             }
233
234             // Skip namespace definitions
235             if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attributeNS)) {
236                 continue;
237             }
238
239             final QName qName = QName.create(URI.create(attributeNS), in.getAttributeLocalName(attrIndex));
240             attributes.put(qName, in.getAttributeValue(attrIndex));
241         }
242
243         return ImmutableMap.copyOf(attributes);
244     }
245
246     private static Document readAnyXmlValue(final XMLStreamReader in) throws XMLStreamException {
247         // Underlying reader might return null when asked for version, however when such reader is plugged into
248         // Stax -> DOM transformer, it fails with NPE due to null version. Use default xml version in such case.
249         final XMLStreamReader inWrapper;
250         if (in.getVersion() == null) {
251             inWrapper = new StreamReaderDelegate(in) {
252                 @Override
253                 public String getVersion() {
254                     final String ver = super.getVersion();
255                     return ver != null ? ver : XML_STANDARD_VERSION;
256                 }
257             };
258         } else {
259             inWrapper = in;
260         }
261
262         final DOMResult result = new DOMResult();
263         try {
264             TRANSFORMER_FACTORY.newTransformer().transform(new StAXSource(inWrapper), result);
265         } catch (final TransformerException e) {
266             throw new XMLStreamException("Unable to read anyxml value", e);
267         }
268         return (Document) result.getNode();
269     }
270
271     private void read(final XMLStreamReader in, final AbstractNodeDataWithSchema parent, final String rootElement)
272             throws XMLStreamException, URISyntaxException {
273         if (!in.hasNext()) {
274             return;
275         }
276
277         if (parent instanceof LeafNodeDataWithSchema || parent instanceof LeafListEntryNodeDataWithSchema) {
278             parent.setAttributes(getElementAttributes(in));
279             setValue(parent, in.getElementText().trim(), in.getNamespaceContext());
280             if (isNextEndDocument(in)) {
281                 return;
282             }
283
284             if (!isAtElement(in)) {
285                 in.nextTag();
286             }
287             return;
288         }
289
290         if (parent instanceof ListEntryNodeDataWithSchema || parent instanceof ContainerNodeDataWithSchema) {
291             parent.setAttributes(getElementAttributes(in));
292         }
293
294         if (parent instanceof LeafListNodeDataWithSchema || parent instanceof ListNodeDataWithSchema) {
295             String xmlElementName = in.getLocalName();
296             while (xmlElementName.equals(parent.getSchema().getQName().getLocalName())) {
297                 read(in, newEntryNode(parent), rootElement);
298                 if (in.getEventType() == XMLStreamConstants.END_DOCUMENT
299                         || in.getEventType() == XMLStreamConstants.END_ELEMENT) {
300                     break;
301                 }
302                 xmlElementName = in.getLocalName();
303             }
304
305             return;
306         }
307
308         if (parent instanceof AnyXmlNodeDataWithSchema) {
309             setValue(parent, readAnyXmlValue(in), in.getNamespaceContext());
310             if (isNextEndDocument(in)) {
311                 return;
312             }
313
314             if (!isAtElement(in)) {
315                 in.nextTag();
316             }
317
318             return;
319         }
320
321         if (parent instanceof YangModeledAnyXmlSchemaNode) {
322             parent.setAttributes(getElementAttributes(in));
323         }
324
325         switch (in.nextTag()) {
326             case XMLStreamConstants.START_ELEMENT:
327                 // FIXME: why do we even need this tracker? either document it or remove it
328                 final Set<Entry<String, String>> namesakes = new HashSet<>();
329                 while (in.hasNext()) {
330                     final String xmlElementName = in.getLocalName();
331
332                     DataSchemaNode parentSchema = parent.getSchema();
333
334                     final String parentSchemaName = parentSchema.getQName().getLocalName();
335                     if (parentSchemaName.equals(xmlElementName)
336                             && in.getEventType() == XMLStreamConstants.END_ELEMENT) {
337                         if (isNextEndDocument(in)) {
338                             break;
339                         }
340
341                         if (!isAtElement(in)) {
342                             in.nextTag();
343                         }
344                         break;
345                     }
346
347                     if (in.isEndElement() && rootElement.equals(xmlElementName)) {
348                         break;
349                     }
350
351                     if (parentSchema instanceof YangModeledAnyXmlSchemaNode) {
352                         parentSchema = ((YangModeledAnyXmlSchemaNode) parentSchema).getSchemaOfAnyXmlData();
353                     }
354
355                     final String xmlElementNamespace = in.getNamespaceURI();
356                     if (!namesakes.add(new SimpleImmutableEntry<>(xmlElementNamespace, xmlElementName))) {
357                         final Location loc = in.getLocation();
358                         throw new IllegalStateException(String.format(
359                                 "Duplicate namespace \"%s\" element \"%s\" in XML input at: line %s column %s",
360                                 xmlElementNamespace, xmlElementName, loc.getLineNumber(), loc.getColumnNumber()));
361                     }
362
363                     final Deque<DataSchemaNode> childDataSchemaNodes =
364                             ParserStreamUtils.findSchemaNodeByNameAndNamespace(parentSchema, xmlElementName,
365                                     new URI(xmlElementNamespace));
366
367                     if (childDataSchemaNodes.isEmpty()) {
368                         checkState(!strictParsing, "Schema for node with name %s and namespace %s does not exist at %s",
369                             xmlElementName, xmlElementNamespace, parentSchema.getPath());
370                         skipUnknownNode(in);
371                         continue;
372                     }
373
374                     read(in, ((CompositeNodeDataWithSchema) parent).addChild(childDataSchemaNodes), rootElement);
375                 }
376                 break;
377             case XMLStreamConstants.END_ELEMENT:
378                 if (isNextEndDocument(in)) {
379                     break;
380                 }
381
382                 if (!isAtElement(in)) {
383                     in.nextTag();
384                 }
385                 break;
386             default:
387                 break;
388         }
389     }
390
391     private static boolean isNextEndDocument(final XMLStreamReader in) throws XMLStreamException {
392         return !in.hasNext() || in.next() == XMLStreamConstants.END_DOCUMENT;
393     }
394
395     private static boolean isAtElement(final XMLStreamReader in) {
396         return in.getEventType() == XMLStreamConstants.START_ELEMENT
397                 || in.getEventType() == XMLStreamConstants.END_ELEMENT;
398     }
399
400     private static void skipUnknownNode(final XMLStreamReader in) throws XMLStreamException {
401         // in case when the unknown node and at least one of its descendant nodes have the same name
402         // we cannot properly reach the end just by checking if the current node is an end element and has the same name
403         // as the root unknown element. therefore we ignore the names completely and just track the level of nesting
404         int levelOfNesting = 0;
405         while (in.hasNext()) {
406             // in case there are text characters in an element, we cannot skip them by calling nextTag()
407             // therefore we skip them by calling next(), and then proceed to next element
408             in.next();
409             if (!isAtElement(in)) {
410                 in.nextTag();
411             }
412             if (in.isStartElement()) {
413                 levelOfNesting++;
414             }
415
416             if (in.isEndElement()) {
417                 if (levelOfNesting == 0) {
418                     break;
419                 }
420
421                 levelOfNesting--;
422             }
423         }
424
425         in.nextTag();
426     }
427
428
429     private void setValue(final AbstractNodeDataWithSchema parent, final Object value,
430             final NamespaceContext nsContext) {
431         checkArgument(parent instanceof SimpleNodeDataWithSchema, "Node %s is not a simple type",
432                 parent.getSchema().getQName());
433         final SimpleNodeDataWithSchema parentSimpleNode = (SimpleNodeDataWithSchema) parent;
434         checkArgument(parentSimpleNode.getValue() == null, "Node '%s' has already set its value to '%s'",
435                 parentSimpleNode.getSchema().getQName(), parentSimpleNode.getValue());
436
437         parentSimpleNode.setValue(translateValueByType(value, parentSimpleNode.getSchema(), nsContext));
438     }
439
440     private Object translateValueByType(final Object value, final DataSchemaNode node,
441             final NamespaceContext namespaceCtx) {
442         if (node instanceof AnyXmlSchemaNode) {
443
444             checkArgument(value instanceof Document);
445             /*
446              *  FIXME: Figure out some YANG extension dispatch, which will
447              *  reuse JSON parsing or XML parsing - anyxml is not well-defined in
448              * JSON.
449              */
450             return new DOMSource(((Document) value).getDocumentElement());
451         }
452
453         checkArgument(node instanceof TypedDataSchemaNode);
454         checkArgument(value instanceof String);
455         return codecs.codecFor((TypedDataSchemaNode) node).parseValue(namespaceCtx, (String) value);
456     }
457
458     private static AbstractNodeDataWithSchema newEntryNode(final AbstractNodeDataWithSchema parent) {
459         final AbstractNodeDataWithSchema newChild;
460         if (parent instanceof ListNodeDataWithSchema) {
461             newChild = new ListEntryNodeDataWithSchema(parent.getSchema());
462         } else {
463             newChild = new LeafListEntryNodeDataWithSchema(parent.getSchema());
464         }
465         ((CompositeNodeDataWithSchema) parent).addChild(newChild);
466         return newChild;
467     }
468
469     @Override
470     public void close() throws IOException {
471         writer.flush();
472         writer.close();
473     }
474
475     @Override
476     public void flush() throws IOException {
477         writer.flush();
478     }
479 }