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