471f29ba300c4dc4dc6b3f5940c3d68c6a23f851
[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 com.google.common.base.Verify.verify;
13 import static java.util.Objects.requireNonNull;
14
15 import com.google.common.annotations.Beta;
16 import com.google.common.base.Strings;
17 import com.google.common.collect.ImmutableMap;
18 import java.io.Closeable;
19 import java.io.Flushable;
20 import java.io.IOException;
21 import java.net.URI;
22 import java.net.URISyntaxException;
23 import java.util.AbstractMap.SimpleImmutableEntry;
24 import java.util.Deque;
25 import java.util.HashSet;
26 import java.util.LinkedHashMap;
27 import java.util.Map;
28 import java.util.Map.Entry;
29 import java.util.Optional;
30 import java.util.Set;
31 import javax.xml.XMLConstants;
32 import javax.xml.namespace.NamespaceContext;
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.TransformerFactory;
40 import javax.xml.transform.TransformerFactoryConfigurationError;
41 import javax.xml.transform.dom.DOMResult;
42 import javax.xml.transform.dom.DOMSource;
43 import javax.xml.transform.stax.StAXSource;
44 import org.opendaylight.yangtools.odlext.model.api.YangModeledAnyXmlSchemaNode;
45 import org.opendaylight.yangtools.rfc7952.model.api.AnnotationSchemaNode;
46 import org.opendaylight.yangtools.yang.common.QName;
47 import org.opendaylight.yangtools.yang.common.QNameModule;
48 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
49 import org.opendaylight.yangtools.yang.data.util.AbstractNodeDataWithSchema;
50 import org.opendaylight.yangtools.yang.data.util.AnyXmlNodeDataWithSchema;
51 import org.opendaylight.yangtools.yang.data.util.CompositeNodeDataWithSchema;
52 import org.opendaylight.yangtools.yang.data.util.ContainerNodeDataWithSchema;
53 import org.opendaylight.yangtools.yang.data.util.LeafListEntryNodeDataWithSchema;
54 import org.opendaylight.yangtools.yang.data.util.LeafListNodeDataWithSchema;
55 import org.opendaylight.yangtools.yang.data.util.LeafNodeDataWithSchema;
56 import org.opendaylight.yangtools.yang.data.util.ListEntryNodeDataWithSchema;
57 import org.opendaylight.yangtools.yang.data.util.ListNodeDataWithSchema;
58 import org.opendaylight.yangtools.yang.data.util.OperationAsContainer;
59 import org.opendaylight.yangtools.yang.data.util.ParserStreamUtils;
60 import org.opendaylight.yangtools.yang.data.util.SimpleNodeDataWithSchema;
61 import org.opendaylight.yangtools.yang.data.util.YangModeledAnyXmlNodeDataWithSchema;
62 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.Module;
69 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
70 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
71 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
72 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
75 import org.w3c.dom.Document;
76 import org.xml.sax.SAXException;
77
78 /**
79  * This class provides functionality for parsing an XML source containing YANG-modeled data. It disallows multiple
80  * instances of the same element except for leaf-list and list entries. It also expects that the YANG-modeled data in
81  * the XML source are wrapped in a root element. This class is NOT thread-safe.
82  *
83  * <p>
84  * Due to backwards compatibility reasons, RFC7952 metadata emitted by this parser may include key QNames with empty URI
85  * (as exposed via {@link #LEGACY_ATTRIBUTE_NAMESPACE}) as their QNameModule. These indicate an unqualified XML
86  * attribute and their value can be assumed to be a String. Furthermore, this extends to qualified attributes, which
87  * uses the proper namespace, but will not bind to a proper module revision -- these need to be reconciled with a
88  * particular SchemaContext and are expected to either be fully decoded, or contain a String value. Handling of such
89  * annotations is at the discretion of the user encountering it: preferred way of handling is to either filter or
90  * normalize them to proper QNames/values when encountered. This caveat will be removed in a future version.
91  */
92 @Beta
93 public final class XmlParserStream implements Closeable, Flushable {
94     /**
95      * {@link QNameModule} for use with legacy XML attributes.
96      * @deprecated The use on this namespace is discouraged and users are strongly encouraged to proper RFC7952 metadata
97      *             annotations.
98      */
99     @Deprecated
100     public static final QNameModule LEGACY_ATTRIBUTE_NAMESPACE = QNameModule.create(URI.create("")).intern();
101
102     private static final Logger LOG = LoggerFactory.getLogger(XmlParserStream.class);
103     private static final String XML_STANDARD_VERSION = "1.0";
104     private static final String COM_SUN_TRANSFORMER =
105             "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
106
107     private static final TransformerFactory TRANSFORMER_FACTORY;
108
109     static {
110         TransformerFactory fa = TransformerFactory.newInstance();
111         if (!fa.getFeature(StAXSource.FEATURE)) {
112             LOG.warn("Platform-default TransformerFactory {} does not support StAXSource, attempting fallback to {}",
113                     fa, COM_SUN_TRANSFORMER);
114             fa = TransformerFactory.newInstance(COM_SUN_TRANSFORMER, null);
115             if (!fa.getFeature(StAXSource.FEATURE)) {
116                 throw new TransformerFactoryConfigurationError("No TransformerFactory supporting StAXResult found.");
117             }
118         }
119
120         TRANSFORMER_FACTORY = fa;
121     }
122
123     private final NormalizedNodeStreamWriter writer;
124     private final XmlCodecFactory codecs;
125     private final DataSchemaNode parentNode;
126     private final boolean strictParsing;
127
128     private XmlParserStream(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
129             final DataSchemaNode parentNode, final boolean strictParsing) {
130         this.writer = requireNonNull(writer);
131         this.codecs = requireNonNull(codecs);
132         this.parentNode = parentNode;
133         this.strictParsing = strictParsing;
134     }
135
136     /**
137      * Construct a new {@link XmlParserStream} with strict parsing mode switched on.
138      *
139      * @param writer Output writer
140      * @param codecs Shared codecs
141      * @param parentNode Parent root node
142      * @return A new stream instance
143      */
144     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
145             final SchemaNode parentNode) {
146         return create(writer, codecs, parentNode, true);
147     }
148
149     /**
150      * Construct a new {@link XmlParserStream}.
151      *
152      * @param writer Output writer
153      * @param codecs Shared codecs
154      * @param parentNode Parent root node
155      * @param strictParsing parsing mode
156      *            if set to true, the parser will throw an exception if it encounters unknown child nodes
157      *            (nodes, that are not defined in the provided SchemaContext) in containers and lists
158      *            if set to false, the parser will skip unknown child nodes
159      * @return A new stream instance
160      */
161     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
162             final SchemaNode parentNode, final boolean strictParsing) {
163         final DataSchemaNode parent;
164         if (parentNode instanceof DataSchemaNode) {
165             parent = (DataSchemaNode) parentNode;
166         } else if (parentNode instanceof OperationDefinition) {
167             parent = OperationAsContainer.of((OperationDefinition) parentNode);
168         } else {
169             throw new IllegalArgumentException("Illegal parent node " + parentNode);
170         }
171         return new XmlParserStream(writer, codecs, parent, strictParsing);
172     }
173
174     /**
175      * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
176      * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
177      * maintain a {@link XmlCodecFactory} to match the current {@link SchemaContext}.
178      */
179     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
180             final SchemaNode parentNode) {
181         return create(writer, schemaContext, parentNode, true);
182     }
183
184     /**
185      * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
186      * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
187      * maintain a {@link XmlCodecFactory} to match the current {@link SchemaContext}.
188      */
189     public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
190             final SchemaNode parentNode, final boolean strictParsing) {
191         return create(writer, XmlCodecFactory.create(schemaContext), parentNode, strictParsing);
192     }
193
194     /**
195      * This method parses the XML source and emits node events into a NormalizedNodeStreamWriter based on the
196      * YANG-modeled data contained in the XML source.
197      *
198      * @param reader
199      *              StAX reader which is to used to walk through the XML source
200      * @return
201      *              instance of XmlParserStream
202      * @throws XMLStreamException
203      *              if a well-formedness error or an unexpected processing condition occurs while parsing the XML
204      * @throws URISyntaxException
205      *              if the namespace URI of an XML element contains a syntax error
206      * @throws IOException
207      *              if an error occurs while parsing the value of an anyxml node
208      * @throws SAXException
209      *              if an error occurs while parsing the value of an anyxml node
210      */
211     public XmlParserStream parse(final XMLStreamReader reader) throws XMLStreamException, URISyntaxException,
212             IOException, SAXException {
213         if (reader.hasNext()) {
214             reader.nextTag();
215             final AbstractNodeDataWithSchema<?> nodeDataWithSchema;
216             if (parentNode instanceof ContainerSchemaNode) {
217                 nodeDataWithSchema = new ContainerNodeDataWithSchema((ContainerSchemaNode) parentNode);
218             } else if (parentNode instanceof ListSchemaNode) {
219                 nodeDataWithSchema = new ListNodeDataWithSchema((ListSchemaNode) parentNode);
220             } else if (parentNode instanceof YangModeledAnyXmlSchemaNode) {
221                 nodeDataWithSchema = new YangModeledAnyXmlNodeDataWithSchema((YangModeledAnyXmlSchemaNode) parentNode);
222             } else if (parentNode instanceof AnyXmlSchemaNode) {
223                 nodeDataWithSchema = new AnyXmlNodeDataWithSchema((AnyXmlSchemaNode) parentNode);
224             } else if (parentNode instanceof LeafSchemaNode) {
225                 nodeDataWithSchema = new LeafNodeDataWithSchema((LeafSchemaNode) parentNode);
226             } else if (parentNode instanceof LeafListSchemaNode) {
227                 nodeDataWithSchema = new LeafListNodeDataWithSchema((LeafListSchemaNode) parentNode);
228             } else {
229                 throw new IllegalStateException("Unsupported schema node type " + parentNode.getClass() + ".");
230             }
231
232             read(reader, nodeDataWithSchema, reader.getLocalName());
233             nodeDataWithSchema.write(writer);
234         }
235
236         return this;
237     }
238
239     /**
240      * This method traverses a {@link DOMSource} and emits node events into a NormalizedNodeStreamWriter based on the
241      * YANG-modeled data contained in the source.
242      *
243      * @param src
244      *              {@link DOMSource} to be traversed
245      * @return
246      *              instance of XmlParserStream
247      * @throws XMLStreamException
248      *              if a well-formedness error or an unexpected processing condition occurs while parsing the XML
249      * @throws URISyntaxException
250      *              if the namespace URI of an XML element contains a syntax error
251      * @throws IOException
252      *              if an error occurs while parsing the value of an anyxml node
253      * @throws SAXException
254      *              if an error occurs while parsing the value of an anyxml node
255      */
256     @Beta
257     public XmlParserStream traverse(final DOMSource src) throws XMLStreamException, URISyntaxException, IOException,
258             SAXException {
259         return parse(new DOMSourceXMLStreamReader(src));
260     }
261
262     private ImmutableMap<QName, Object> getElementAttributes(final XMLStreamReader in) {
263         checkState(in.isStartElement(), "Attributes can be extracted only from START_ELEMENT.");
264         final Map<QName, Object> attributes = new LinkedHashMap<>();
265
266         for (int attrIndex = 0; attrIndex < in.getAttributeCount(); attrIndex++) {
267             final String attributeNS = in.getAttributeNamespace(attrIndex);
268
269             // Skip namespace definitions
270             if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attributeNS)) {
271                 continue;
272             }
273
274             final String localName = in.getAttributeLocalName(attrIndex);
275             final String attrValue = in.getAttributeValue(attrIndex);
276             if (Strings.isNullOrEmpty(attributeNS)) {
277                 StreamWriterFacade.warnLegacyAttribute(localName);
278                 attributes.put(QName.create(LEGACY_ATTRIBUTE_NAMESPACE, localName), attrValue);
279                 continue;
280             }
281
282             // Cross-relate attribute namespace to the module
283             final URI uri = URI.create(attributeNS);
284             final SchemaContext schemaContext = codecs.getSchemaContext();
285             final Set<Module> modules = schemaContext.findModules(uri);
286             if (!modules.isEmpty()) {
287                 final QName qname = QName.create(modules.iterator().next().getQNameModule(), localName);
288                 final Optional<AnnotationSchemaNode> optAnnotation = AnnotationSchemaNode.find(schemaContext, qname);
289                 if (optAnnotation.isPresent()) {
290                     final AnnotationSchemaNode schema = optAnnotation.get();
291                     final Object value = codecs.codecFor(schema).parseValue(in.getNamespaceContext(), attrValue);
292                     attributes.put(schema.getQName(), value);
293                     continue;
294                 }
295
296                 LOG.debug("Annotation for {} not found, using legacy QName", qname);
297             }
298
299             attributes.put(QName.create(uri, localName), attrValue);
300         }
301
302         return ImmutableMap.copyOf(attributes);
303     }
304
305     private static Document readAnyXmlValue(final XMLStreamReader in) throws XMLStreamException {
306         // Underlying reader might return null when asked for version, however when such reader is plugged into
307         // Stax -> DOM transformer, it fails with NPE due to null version. Use default xml version in such case.
308         final XMLStreamReader inWrapper;
309         if (in.getVersion() == null) {
310             inWrapper = new StreamReaderDelegate(in) {
311                 @Override
312                 public String getVersion() {
313                     final String ver = super.getVersion();
314                     return ver != null ? ver : XML_STANDARD_VERSION;
315                 }
316             };
317         } else {
318             inWrapper = in;
319         }
320
321         final DOMResult result = new DOMResult();
322         try {
323             TRANSFORMER_FACTORY.newTransformer().transform(new StAXSource(inWrapper), result);
324         } catch (final TransformerException e) {
325             throw new XMLStreamException("Unable to read anyxml value", e);
326         }
327         return (Document) result.getNode();
328     }
329
330     private void read(final XMLStreamReader in, final AbstractNodeDataWithSchema<?> parent, final String rootElement)
331             throws XMLStreamException, URISyntaxException {
332         if (!in.hasNext()) {
333             return;
334         }
335
336         if (parent instanceof LeafNodeDataWithSchema || parent instanceof LeafListEntryNodeDataWithSchema) {
337             parent.setAttributes(getElementAttributes(in));
338             setValue(parent, in.getElementText().trim(), in.getNamespaceContext());
339             if (isNextEndDocument(in)) {
340                 return;
341             }
342
343             if (!isAtElement(in)) {
344                 in.nextTag();
345             }
346             return;
347         }
348
349         if (parent instanceof ListEntryNodeDataWithSchema || parent instanceof ContainerNodeDataWithSchema) {
350             parent.setAttributes(getElementAttributes(in));
351         }
352
353         if (parent instanceof LeafListNodeDataWithSchema || parent instanceof ListNodeDataWithSchema) {
354             String xmlElementName = in.getLocalName();
355             while (xmlElementName.equals(parent.getSchema().getQName().getLocalName())) {
356                 read(in, newEntryNode(parent), rootElement);
357                 if (in.getEventType() == XMLStreamConstants.END_DOCUMENT
358                         || in.getEventType() == XMLStreamConstants.END_ELEMENT) {
359                     break;
360                 }
361                 xmlElementName = in.getLocalName();
362             }
363
364             return;
365         }
366
367         if (parent instanceof AnyXmlNodeDataWithSchema) {
368             setValue(parent, readAnyXmlValue(in), in.getNamespaceContext());
369             if (isNextEndDocument(in)) {
370                 return;
371             }
372
373             if (!isAtElement(in)) {
374                 in.nextTag();
375             }
376
377             return;
378         }
379
380         if (parent instanceof YangModeledAnyXmlSchemaNode) {
381             parent.setAttributes(getElementAttributes(in));
382         }
383
384         switch (in.nextTag()) {
385             case XMLStreamConstants.START_ELEMENT:
386                 // FIXME: why do we even need this tracker? either document it or remove it
387                 final Set<Entry<String, String>> namesakes = new HashSet<>();
388                 while (in.hasNext()) {
389                     final String xmlElementName = in.getLocalName();
390
391                     DataSchemaNode parentSchema = parent.getSchema();
392
393                     final String parentSchemaName = parentSchema.getQName().getLocalName();
394                     if (parentSchemaName.equals(xmlElementName)
395                             && in.getEventType() == XMLStreamConstants.END_ELEMENT) {
396                         if (isNextEndDocument(in)) {
397                             break;
398                         }
399
400                         if (!isAtElement(in)) {
401                             in.nextTag();
402                         }
403                         break;
404                     }
405
406                     if (in.isEndElement() && rootElement.equals(xmlElementName)) {
407                         break;
408                     }
409
410                     if (parentSchema instanceof YangModeledAnyXmlSchemaNode) {
411                         parentSchema = ((YangModeledAnyXmlSchemaNode) parentSchema).getSchemaOfAnyXmlData();
412                     }
413
414                     final String xmlElementNamespace = in.getNamespaceURI();
415                     if (!namesakes.add(new SimpleImmutableEntry<>(xmlElementNamespace, xmlElementName))) {
416                         final Location loc = in.getLocation();
417                         throw new IllegalStateException(String.format(
418                                 "Duplicate namespace \"%s\" element \"%s\" in XML input at: line %s column %s",
419                                 xmlElementNamespace, xmlElementName, loc.getLineNumber(), loc.getColumnNumber()));
420                     }
421
422                     final Deque<DataSchemaNode> childDataSchemaNodes =
423                             ParserStreamUtils.findSchemaNodeByNameAndNamespace(parentSchema, xmlElementName,
424                                     new URI(xmlElementNamespace));
425
426                     if (childDataSchemaNodes.isEmpty()) {
427                         checkState(!strictParsing, "Schema for node with name %s and namespace %s does not exist at %s",
428                             xmlElementName, xmlElementNamespace, parentSchema.getPath());
429                         skipUnknownNode(in);
430                         continue;
431                     }
432
433                     read(in, ((CompositeNodeDataWithSchema<?>) parent).addChild(childDataSchemaNodes), rootElement);
434                 }
435                 break;
436             case XMLStreamConstants.END_ELEMENT:
437                 if (isNextEndDocument(in)) {
438                     break;
439                 }
440
441                 if (!isAtElement(in)) {
442                     in.nextTag();
443                 }
444                 break;
445             default:
446                 break;
447         }
448     }
449
450     private static boolean isNextEndDocument(final XMLStreamReader in) throws XMLStreamException {
451         return !in.hasNext() || in.next() == XMLStreamConstants.END_DOCUMENT;
452     }
453
454     private static boolean isAtElement(final XMLStreamReader in) {
455         return in.getEventType() == XMLStreamConstants.START_ELEMENT
456                 || in.getEventType() == XMLStreamConstants.END_ELEMENT;
457     }
458
459     private static void skipUnknownNode(final XMLStreamReader in) throws XMLStreamException {
460         // in case when the unknown node and at least one of its descendant nodes have the same name
461         // we cannot properly reach the end just by checking if the current node is an end element and has the same name
462         // as the root unknown element. therefore we ignore the names completely and just track the level of nesting
463         int levelOfNesting = 0;
464         while (in.hasNext()) {
465             // in case there are text characters in an element, we cannot skip them by calling nextTag()
466             // therefore we skip them by calling next(), and then proceed to next element
467             in.next();
468             if (!isAtElement(in)) {
469                 in.nextTag();
470             }
471             if (in.isStartElement()) {
472                 levelOfNesting++;
473             }
474
475             if (in.isEndElement()) {
476                 if (levelOfNesting == 0) {
477                     break;
478                 }
479
480                 levelOfNesting--;
481             }
482         }
483
484         in.nextTag();
485     }
486
487
488     private void setValue(final AbstractNodeDataWithSchema<?> parent, final Object value,
489             final NamespaceContext nsContext) {
490         checkArgument(parent instanceof SimpleNodeDataWithSchema, "Node %s is not a simple type",
491                 parent.getSchema().getQName());
492         final SimpleNodeDataWithSchema<?> parentSimpleNode = (SimpleNodeDataWithSchema<?>) parent;
493         checkArgument(parentSimpleNode.getValue() == null, "Node '%s' has already set its value to '%s'",
494                 parentSimpleNode.getSchema().getQName(), parentSimpleNode.getValue());
495
496         parentSimpleNode.setValue(translateValueByType(value, parentSimpleNode.getSchema(), nsContext));
497     }
498
499     private Object translateValueByType(final Object value, final DataSchemaNode node,
500             final NamespaceContext namespaceCtx) {
501         if (node instanceof AnyXmlSchemaNode) {
502
503             checkArgument(value instanceof Document);
504             /*
505              *  FIXME: Figure out some YANG extension dispatch, which will
506              *  reuse JSON parsing or XML parsing - anyxml is not well-defined in
507              * JSON.
508              */
509             return new DOMSource(((Document) value).getDocumentElement());
510         }
511
512         checkArgument(node instanceof TypedDataSchemaNode);
513         checkArgument(value instanceof String);
514         return codecs.codecFor((TypedDataSchemaNode) node).parseValue(namespaceCtx, (String) value);
515     }
516
517     private static AbstractNodeDataWithSchema<?> newEntryNode(final AbstractNodeDataWithSchema<?> parent) {
518         final AbstractNodeDataWithSchema<?> newChild;
519         if (parent instanceof ListNodeDataWithSchema) {
520             newChild = ListEntryNodeDataWithSchema.forSchema(((ListNodeDataWithSchema) parent).getSchema());
521         } else {
522             verify(parent instanceof LeafListNodeDataWithSchema, "Unexpected parent %s", parent);
523             newChild = new LeafListEntryNodeDataWithSchema(((LeafListNodeDataWithSchema) parent).getSchema());
524         }
525         ((CompositeNodeDataWithSchema<?>) parent).addChild(newChild);
526         return newChild;
527     }
528
529     @Override
530     public void close() throws IOException {
531         writer.flush();
532         writer.close();
533     }
534
535     @Override
536     public void flush() throws IOException {
537         writer.flush();
538     }
539 }