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