Refactor ListEntryNodeDataWithSchema
[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.collect.ImmutableMap;
17 import java.io.Closeable;
18 import java.io.Flushable;
19 import java.io.IOException;
20 import java.net.URI;
21 import java.net.URISyntaxException;
22 import java.util.AbstractMap.SimpleImmutableEntry;
23 import java.util.Deque;
24 import java.util.HashSet;
25 import java.util.LinkedHashMap;
26 import java.util.Map;
27 import java.util.Map.Entry;
28 import java.util.Set;
29 import javax.annotation.concurrent.NotThreadSafe;
30 import javax.xml.XMLConstants;
31 import javax.xml.namespace.NamespaceContext;
32 import javax.xml.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 SAXException
189      *              if an error occurs while parsing the value of an anyxml node
190      */
191     public XmlParserStream parse(final XMLStreamReader reader) throws XMLStreamException, URISyntaxException,
192             IOException, SAXException {
193         if (reader.hasNext()) {
194             reader.nextTag();
195             final AbstractNodeDataWithSchema<?> nodeDataWithSchema;
196             if (parentNode instanceof ContainerSchemaNode) {
197                 nodeDataWithSchema = new ContainerNodeDataWithSchema((ContainerSchemaNode) parentNode);
198             } else if (parentNode instanceof ListSchemaNode) {
199                 nodeDataWithSchema = new ListNodeDataWithSchema((ListSchemaNode) parentNode);
200             } else if (parentNode instanceof YangModeledAnyXmlSchemaNode) {
201                 nodeDataWithSchema = new YangModeledAnyXmlNodeDataWithSchema((YangModeledAnyXmlSchemaNode) parentNode);
202             } else if (parentNode instanceof AnyXmlSchemaNode) {
203                 nodeDataWithSchema = new AnyXmlNodeDataWithSchema((AnyXmlSchemaNode) parentNode);
204             } else if (parentNode instanceof LeafSchemaNode) {
205                 nodeDataWithSchema = new LeafNodeDataWithSchema((LeafSchemaNode) parentNode);
206             } else if (parentNode instanceof LeafListSchemaNode) {
207                 nodeDataWithSchema = new LeafListNodeDataWithSchema((LeafListSchemaNode) parentNode);
208             } else {
209                 throw new IllegalStateException("Unsupported schema node type " + parentNode.getClass() + ".");
210             }
211
212             read(reader, nodeDataWithSchema, reader.getLocalName());
213             nodeDataWithSchema.write(writer);
214         }
215
216         return this;
217     }
218
219     /**
220      * This method traverses a {@link DOMSource} and emits node events into a NormalizedNodeStreamWriter based on the
221      * YANG-modeled data contained in the source.
222      *
223      * @param src
224      *              {@link DOMSource} to be traversed
225      * @return
226      *              instance of XmlParserStream
227      * @throws XMLStreamException
228      *              if a well-formedness error or an unexpected processing condition occurs while parsing the XML
229      * @throws URISyntaxException
230      *              if the namespace URI of an XML element contains a syntax error
231      * @throws IOException
232      *              if an error occurs while parsing the value of an anyxml node
233      * @throws SAXException
234      *              if an error occurs while parsing the value of an anyxml node
235      */
236     @Beta
237     public XmlParserStream traverse(final DOMSource src) throws XMLStreamException, URISyntaxException, IOException,
238             SAXException {
239         return parse(new DOMSourceXMLStreamReader(src));
240     }
241
242     private static ImmutableMap<QName, String> getElementAttributes(final XMLStreamReader in) {
243         checkState(in.isStartElement(), "Attributes can be extracted only from START_ELEMENT.");
244         final Map<QName, String> attributes = new LinkedHashMap<>();
245
246         for (int attrIndex = 0; attrIndex < in.getAttributeCount(); attrIndex++) {
247             String attributeNS = in.getAttributeNamespace(attrIndex);
248
249             if (attributeNS == null) {
250                 attributeNS = "";
251             }
252
253             // Skip namespace definitions
254             if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attributeNS)) {
255                 continue;
256             }
257
258             final QName qName = QName.create(URI.create(attributeNS), in.getAttributeLocalName(attrIndex));
259             attributes.put(qName, in.getAttributeValue(attrIndex));
260         }
261
262         return ImmutableMap.copyOf(attributes);
263     }
264
265     private static Document readAnyXmlValue(final XMLStreamReader in) throws XMLStreamException {
266         // Underlying reader might return null when asked for version, however when such reader is plugged into
267         // Stax -> DOM transformer, it fails with NPE due to null version. Use default xml version in such case.
268         final XMLStreamReader inWrapper;
269         if (in.getVersion() == null) {
270             inWrapper = new StreamReaderDelegate(in) {
271                 @Override
272                 public String getVersion() {
273                     final String ver = super.getVersion();
274                     return ver != null ? ver : XML_STANDARD_VERSION;
275                 }
276             };
277         } else {
278             inWrapper = in;
279         }
280
281         final DOMResult result = new DOMResult();
282         try {
283             TRANSFORMER_FACTORY.newTransformer().transform(new StAXSource(inWrapper), result);
284         } catch (final TransformerException e) {
285             throw new XMLStreamException("Unable to read anyxml value", e);
286         }
287         return (Document) result.getNode();
288     }
289
290     private void read(final XMLStreamReader in, final AbstractNodeDataWithSchema<?> parent, final String rootElement)
291             throws XMLStreamException, URISyntaxException {
292         if (!in.hasNext()) {
293             return;
294         }
295
296         if (parent instanceof LeafNodeDataWithSchema || parent instanceof LeafListEntryNodeDataWithSchema) {
297             parent.setAttributes(getElementAttributes(in));
298             setValue(parent, in.getElementText().trim(), in.getNamespaceContext());
299             if (isNextEndDocument(in)) {
300                 return;
301             }
302
303             if (!isAtElement(in)) {
304                 in.nextTag();
305             }
306             return;
307         }
308
309         if (parent instanceof ListEntryNodeDataWithSchema || parent instanceof ContainerNodeDataWithSchema) {
310             parent.setAttributes(getElementAttributes(in));
311         }
312
313         if (parent instanceof LeafListNodeDataWithSchema || parent instanceof ListNodeDataWithSchema) {
314             String xmlElementName = in.getLocalName();
315             while (xmlElementName.equals(parent.getSchema().getQName().getLocalName())) {
316                 read(in, newEntryNode(parent), rootElement);
317                 if (in.getEventType() == XMLStreamConstants.END_DOCUMENT
318                         || in.getEventType() == XMLStreamConstants.END_ELEMENT) {
319                     break;
320                 }
321                 xmlElementName = in.getLocalName();
322             }
323
324             return;
325         }
326
327         if (parent instanceof AnyXmlNodeDataWithSchema) {
328             setValue(parent, readAnyXmlValue(in), in.getNamespaceContext());
329             if (isNextEndDocument(in)) {
330                 return;
331             }
332
333             if (!isAtElement(in)) {
334                 in.nextTag();
335             }
336
337             return;
338         }
339
340         if (parent instanceof YangModeledAnyXmlSchemaNode) {
341             parent.setAttributes(getElementAttributes(in));
342         }
343
344         switch (in.nextTag()) {
345             case XMLStreamConstants.START_ELEMENT:
346                 // FIXME: why do we even need this tracker? either document it or remove it
347                 final Set<Entry<String, String>> namesakes = new HashSet<>();
348                 while (in.hasNext()) {
349                     final String xmlElementName = in.getLocalName();
350
351                     DataSchemaNode parentSchema = parent.getSchema();
352
353                     final String parentSchemaName = parentSchema.getQName().getLocalName();
354                     if (parentSchemaName.equals(xmlElementName)
355                             && in.getEventType() == XMLStreamConstants.END_ELEMENT) {
356                         if (isNextEndDocument(in)) {
357                             break;
358                         }
359
360                         if (!isAtElement(in)) {
361                             in.nextTag();
362                         }
363                         break;
364                     }
365
366                     if (in.isEndElement() && rootElement.equals(xmlElementName)) {
367                         break;
368                     }
369
370                     if (parentSchema instanceof YangModeledAnyXmlSchemaNode) {
371                         parentSchema = ((YangModeledAnyXmlSchemaNode) parentSchema).getSchemaOfAnyXmlData();
372                     }
373
374                     final String xmlElementNamespace = in.getNamespaceURI();
375                     if (!namesakes.add(new SimpleImmutableEntry<>(xmlElementNamespace, xmlElementName))) {
376                         final Location loc = in.getLocation();
377                         throw new IllegalStateException(String.format(
378                                 "Duplicate namespace \"%s\" element \"%s\" in XML input at: line %s column %s",
379                                 xmlElementNamespace, xmlElementName, loc.getLineNumber(), loc.getColumnNumber()));
380                     }
381
382                     final Deque<DataSchemaNode> childDataSchemaNodes =
383                             ParserStreamUtils.findSchemaNodeByNameAndNamespace(parentSchema, xmlElementName,
384                                     new URI(xmlElementNamespace));
385
386                     if (childDataSchemaNodes.isEmpty()) {
387                         checkState(!strictParsing, "Schema for node with name %s and namespace %s does not exist at %s",
388                             xmlElementName, xmlElementNamespace, parentSchema.getPath());
389                         skipUnknownNode(in);
390                         continue;
391                     }
392
393                     read(in, ((CompositeNodeDataWithSchema<?>) parent).addChild(childDataSchemaNodes), rootElement);
394                 }
395                 break;
396             case XMLStreamConstants.END_ELEMENT:
397                 if (isNextEndDocument(in)) {
398                     break;
399                 }
400
401                 if (!isAtElement(in)) {
402                     in.nextTag();
403                 }
404                 break;
405             default:
406                 break;
407         }
408     }
409
410     private static boolean isNextEndDocument(final XMLStreamReader in) throws XMLStreamException {
411         return !in.hasNext() || in.next() == XMLStreamConstants.END_DOCUMENT;
412     }
413
414     private static boolean isAtElement(final XMLStreamReader in) {
415         return in.getEventType() == XMLStreamConstants.START_ELEMENT
416                 || in.getEventType() == XMLStreamConstants.END_ELEMENT;
417     }
418
419     private static void skipUnknownNode(final XMLStreamReader in) throws XMLStreamException {
420         // in case when the unknown node and at least one of its descendant nodes have the same name
421         // we cannot properly reach the end just by checking if the current node is an end element and has the same name
422         // as the root unknown element. therefore we ignore the names completely and just track the level of nesting
423         int levelOfNesting = 0;
424         while (in.hasNext()) {
425             // in case there are text characters in an element, we cannot skip them by calling nextTag()
426             // therefore we skip them by calling next(), and then proceed to next element
427             in.next();
428             if (!isAtElement(in)) {
429                 in.nextTag();
430             }
431             if (in.isStartElement()) {
432                 levelOfNesting++;
433             }
434
435             if (in.isEndElement()) {
436                 if (levelOfNesting == 0) {
437                     break;
438                 }
439
440                 levelOfNesting--;
441             }
442         }
443
444         in.nextTag();
445     }
446
447
448     private void setValue(final AbstractNodeDataWithSchema<?> parent, final Object value,
449             final NamespaceContext nsContext) {
450         checkArgument(parent instanceof SimpleNodeDataWithSchema, "Node %s is not a simple type",
451                 parent.getSchema().getQName());
452         final SimpleNodeDataWithSchema<?> parentSimpleNode = (SimpleNodeDataWithSchema<?>) parent;
453         checkArgument(parentSimpleNode.getValue() == null, "Node '%s' has already set its value to '%s'",
454                 parentSimpleNode.getSchema().getQName(), parentSimpleNode.getValue());
455
456         parentSimpleNode.setValue(translateValueByType(value, parentSimpleNode.getSchema(), nsContext));
457     }
458
459     private Object translateValueByType(final Object value, final DataSchemaNode node,
460             final NamespaceContext namespaceCtx) {
461         if (node instanceof AnyXmlSchemaNode) {
462
463             checkArgument(value instanceof Document);
464             /*
465              *  FIXME: Figure out some YANG extension dispatch, which will
466              *  reuse JSON parsing or XML parsing - anyxml is not well-defined in
467              * JSON.
468              */
469             return new DOMSource(((Document) value).getDocumentElement());
470         }
471
472         checkArgument(node instanceof TypedDataSchemaNode);
473         checkArgument(value instanceof String);
474         return codecs.codecFor((TypedDataSchemaNode) node).parseValue(namespaceCtx, (String) value);
475     }
476
477     private static AbstractNodeDataWithSchema<?> newEntryNode(final AbstractNodeDataWithSchema<?> parent) {
478         final AbstractNodeDataWithSchema<?> newChild;
479         if (parent instanceof ListNodeDataWithSchema) {
480             newChild = ListEntryNodeDataWithSchema.forSchema(((ListNodeDataWithSchema) parent).getSchema());
481         } else {
482             verify(parent instanceof LeafListNodeDataWithSchema, "Unexpected parent %s", parent);
483             newChild = new LeafListEntryNodeDataWithSchema(((LeafListNodeDataWithSchema) parent).getSchema());
484         }
485         ((CompositeNodeDataWithSchema<?>) parent).addChild(newChild);
486         return newChild;
487     }
488
489     @Override
490     public void close() throws IOException {
491         writer.flush();
492         writer.close();
493     }
494
495     @Override
496     public void flush() throws IOException {
497         writer.flush();
498     }
499 }