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