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