2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.data.codec.xml;
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 import static org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter.TRANSFORMER_FACTORY;
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;
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;
27 import java.util.Map.Entry;
29 import javax.annotation.concurrent.NotThreadSafe;
30 import javax.xml.XMLConstants;
31 import javax.xml.namespace.NamespaceContext;
32 import javax.xml.parsers.ParserConfigurationException;
33 import javax.xml.stream.Location;
34 import javax.xml.stream.XMLStreamConstants;
35 import javax.xml.stream.XMLStreamException;
36 import javax.xml.stream.XMLStreamReader;
37 import javax.xml.stream.util.StreamReaderDelegate;
38 import javax.xml.transform.TransformerException;
39 import javax.xml.transform.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.ParserStreamUtils;
55 import org.opendaylight.yangtools.yang.data.util.RpcAsContainer;
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.RpcDefinition;
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.w3c.dom.Document;
69 import org.xml.sax.SAXException;
72 * This class provides functionality for parsing an XML source containing YANG-modeled data. It disallows multiple
73 * instances of the same element except for leaf-list and list entries. It also expects that the YANG-modeled data in
74 * the XML source are wrapped in a root element.
78 public final class XmlParserStream implements Closeable, Flushable {
80 private static final String XML_STANDARD_VERSION = "1.0";
82 private final NormalizedNodeStreamWriter writer;
83 private final XmlCodecFactory codecs;
84 private final DataSchemaNode parentNode;
85 private final boolean strictParsing;
87 private XmlParserStream(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
88 final DataSchemaNode parentNode, final boolean strictParsing) {
89 this.writer = requireNonNull(writer);
90 this.codecs = requireNonNull(codecs);
91 this.parentNode = parentNode;
92 this.strictParsing = strictParsing;
96 * Construct a new {@link XmlParserStream} with strict parsing mode switched on.
98 * @param writer Output writer
99 * @param codecs Shared codecs
100 * @param parentNode Parent root node
101 * @return A new stream instance
103 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
104 final SchemaNode parentNode) {
105 return create(writer, codecs, parentNode, true);
109 * Construct a new {@link XmlParserStream}.
111 * @param writer Output writer
112 * @param codecs Shared codecs
113 * @param parentNode Parent root node
114 * @param strictParsing parsing mode
115 * if set to true, the parser will throw an exception if it encounters unknown child nodes
116 * (nodes, that are not defined in the provided SchemaContext) in containers and lists
117 * if set to false, the parser will skip unknown child nodes
118 * @return A new stream instance
120 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
121 final SchemaNode parentNode, final boolean strictParsing) {
122 if (parentNode instanceof RpcDefinition) {
123 return new XmlParserStream(writer, codecs, new RpcAsContainer((RpcDefinition) parentNode), strictParsing);
125 checkArgument(parentNode instanceof DataSchemaNode, "Instance of DataSchemaNode class awaited.");
126 return new XmlParserStream(writer, codecs, (DataSchemaNode) parentNode, strictParsing);
130 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
131 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
132 * maintain a {@link XmlCodecFactory} to match the current {@link SchemaContext}.
134 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
135 final SchemaNode parentNode) {
136 return create(writer, schemaContext, parentNode, true);
140 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
141 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
142 * maintain a {@link XmlCodecFactory} to match the current {@link SchemaContext}.
144 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
145 final SchemaNode parentNode, final boolean strictParsing) {
146 return create(writer, XmlCodecFactory.create(schemaContext), parentNode, strictParsing);
150 * This method parses the XML source and emits node events into a NormalizedNodeStreamWriter based on the
151 * YANG-modeled data contained in the XML source.
154 * StAX reader which is to used to walk through the XML source
156 * instance of XmlParserStream
157 * @throws XMLStreamException
158 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
159 * @throws URISyntaxException
160 * if the namespace URI of an XML element contains a syntax error
161 * @throws IOException
162 * if an error occurs while parsing the value of an anyxml node
163 * @throws ParserConfigurationException
164 * if an error occurs while parsing the value of an anyxml node
165 * @throws SAXException
166 * if an error occurs while parsing the value of an anyxml node
168 // FIXME: 3.0.0 remove ParserConfigurationException
169 public XmlParserStream parse(final XMLStreamReader reader) throws XMLStreamException, URISyntaxException,
170 IOException, ParserConfigurationException, SAXException {
171 if (reader.hasNext()) {
173 final AbstractNodeDataWithSchema nodeDataWithSchema;
174 if (parentNode instanceof ContainerSchemaNode) {
175 nodeDataWithSchema = new ContainerNodeDataWithSchema(parentNode);
176 } else if (parentNode instanceof ListSchemaNode) {
177 nodeDataWithSchema = new ListNodeDataWithSchema(parentNode);
178 } else if (parentNode instanceof YangModeledAnyXmlSchemaNode) {
179 nodeDataWithSchema = new YangModeledAnyXmlNodeDataWithSchema((YangModeledAnyXmlSchemaNode) parentNode);
180 } else if (parentNode instanceof AnyXmlSchemaNode) {
181 nodeDataWithSchema = new AnyXmlNodeDataWithSchema(parentNode);
182 } else if (parentNode instanceof LeafSchemaNode) {
183 nodeDataWithSchema = new LeafNodeDataWithSchema(parentNode);
184 } else if (parentNode instanceof LeafListSchemaNode) {
185 nodeDataWithSchema = new LeafListNodeDataWithSchema(parentNode);
187 throw new IllegalStateException("Unsupported schema node type " + parentNode.getClass() + ".");
190 read(reader, nodeDataWithSchema, reader.getLocalName());
191 nodeDataWithSchema.write(writer);
198 * This method traverses a {@link DOMSource} and emits node events into a NormalizedNodeStreamWriter based on the
199 * YANG-modeled data contained in the source.
202 * {@link DOMSource} to be traversed
204 * instance of XmlParserStream
205 * @throws XMLStreamException
206 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
207 * @throws URISyntaxException
208 * if the namespace URI of an XML element contains a syntax error
209 * @throws IOException
210 * if an error occurs while parsing the value of an anyxml node
211 * @throws ParserConfigurationException
212 * if an error occurs while parsing the value of an anyxml node
213 * @throws SAXException
214 * if an error occurs while parsing the value of an anyxml node
217 // FIXME: 3.0.0 remove ParserConfigurationException
218 public XmlParserStream traverse(final DOMSource src) throws XMLStreamException, URISyntaxException,
219 IOException, ParserConfigurationException, SAXException {
220 return parse(new DOMSourceXMLStreamReader(src));
223 private static ImmutableMap<QName, String> getElementAttributes(final XMLStreamReader in) {
224 checkState(in.isStartElement(), "Attributes can be extracted only from START_ELEMENT.");
225 final Map<QName, String> attributes = new LinkedHashMap<>();
227 for (int attrIndex = 0; attrIndex < in.getAttributeCount(); attrIndex++) {
228 String attributeNS = in.getAttributeNamespace(attrIndex);
230 if (attributeNS == null) {
234 // Skip namespace definitions
235 if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attributeNS)) {
239 final QName qName = QName.create(URI.create(attributeNS), in.getAttributeLocalName(attrIndex));
240 attributes.put(qName, in.getAttributeValue(attrIndex));
243 return ImmutableMap.copyOf(attributes);
246 private static Document readAnyXmlValue(final XMLStreamReader in) throws XMLStreamException {
247 // Underlying reader might return null when asked for version, however when such reader is plugged into
248 // Stax -> DOM transformer, it fails with NPE due to null version. Use default xml version in such case.
249 final XMLStreamReader inWrapper;
250 if (in.getVersion() == null) {
251 inWrapper = new StreamReaderDelegate(in) {
253 public String getVersion() {
254 final String ver = super.getVersion();
255 return ver != null ? ver : XML_STANDARD_VERSION;
262 final DOMResult result = new DOMResult();
264 TRANSFORMER_FACTORY.newTransformer().transform(new StAXSource(inWrapper), result);
265 } catch (final TransformerException e) {
266 throw new XMLStreamException("Unable to read anyxml value", e);
268 return (Document) result.getNode();
271 private void read(final XMLStreamReader in, final AbstractNodeDataWithSchema parent, final String rootElement)
272 throws XMLStreamException, URISyntaxException {
277 if (parent instanceof LeafNodeDataWithSchema || parent instanceof LeafListEntryNodeDataWithSchema) {
278 parent.setAttributes(getElementAttributes(in));
279 setValue(parent, in.getElementText().trim(), in.getNamespaceContext());
280 if (isNextEndDocument(in)) {
284 if (!isAtElement(in)) {
290 if (parent instanceof ListEntryNodeDataWithSchema || parent instanceof ContainerNodeDataWithSchema) {
291 parent.setAttributes(getElementAttributes(in));
294 if (parent instanceof LeafListNodeDataWithSchema || parent instanceof ListNodeDataWithSchema) {
295 String xmlElementName = in.getLocalName();
296 while (xmlElementName.equals(parent.getSchema().getQName().getLocalName())) {
297 read(in, newEntryNode(parent), rootElement);
298 if (in.getEventType() == XMLStreamConstants.END_DOCUMENT
299 || in.getEventType() == XMLStreamConstants.END_ELEMENT) {
302 xmlElementName = in.getLocalName();
308 if (parent instanceof AnyXmlNodeDataWithSchema) {
309 setValue(parent, readAnyXmlValue(in), in.getNamespaceContext());
310 if (isNextEndDocument(in)) {
314 if (!isAtElement(in)) {
321 if (parent instanceof YangModeledAnyXmlSchemaNode) {
322 parent.setAttributes(getElementAttributes(in));
325 switch (in.nextTag()) {
326 case XMLStreamConstants.START_ELEMENT:
327 // FIXME: why do we even need this tracker? either document it or remove it
328 final Set<Entry<String, String>> namesakes = new HashSet<>();
329 while (in.hasNext()) {
330 final String xmlElementName = in.getLocalName();
332 DataSchemaNode parentSchema = parent.getSchema();
334 final String parentSchemaName = parentSchema.getQName().getLocalName();
335 if (parentSchemaName.equals(xmlElementName)
336 && in.getEventType() == XMLStreamConstants.END_ELEMENT) {
337 if (isNextEndDocument(in)) {
341 if (!isAtElement(in)) {
347 if (in.isEndElement() && rootElement.equals(xmlElementName)) {
351 if (parentSchema instanceof YangModeledAnyXmlSchemaNode) {
352 parentSchema = ((YangModeledAnyXmlSchemaNode) parentSchema).getSchemaOfAnyXmlData();
355 final String xmlElementNamespace = in.getNamespaceURI();
356 if (!namesakes.add(new SimpleImmutableEntry<>(xmlElementNamespace, xmlElementName))) {
357 final Location loc = in.getLocation();
358 throw new IllegalStateException(String.format(
359 "Duplicate namespace \"%s\" element \"%s\" in XML input at: line %s column %s",
360 xmlElementNamespace, xmlElementName, loc.getLineNumber(), loc.getColumnNumber()));
363 final Deque<DataSchemaNode> childDataSchemaNodes =
364 ParserStreamUtils.findSchemaNodeByNameAndNamespace(parentSchema, xmlElementName,
365 new URI(xmlElementNamespace));
367 if (childDataSchemaNodes.isEmpty()) {
368 checkState(!strictParsing, "Schema for node with name %s and namespace %s does not exist at %s",
369 xmlElementName, xmlElementNamespace, parentSchema.getPath());
374 read(in, ((CompositeNodeDataWithSchema) parent).addChild(childDataSchemaNodes), rootElement);
377 case XMLStreamConstants.END_ELEMENT:
378 if (isNextEndDocument(in)) {
382 if (!isAtElement(in)) {
391 private static boolean isNextEndDocument(final XMLStreamReader in) throws XMLStreamException {
392 return !in.hasNext() || in.next() == XMLStreamConstants.END_DOCUMENT;
395 private static boolean isAtElement(final XMLStreamReader in) {
396 return in.getEventType() == XMLStreamConstants.START_ELEMENT
397 || in.getEventType() == XMLStreamConstants.END_ELEMENT;
400 private static void skipUnknownNode(final XMLStreamReader in) throws XMLStreamException {
401 // in case when the unknown node and at least one of its descendant nodes have the same name
402 // we cannot properly reach the end just by checking if the current node is an end element and has the same name
403 // as the root unknown element. therefore we ignore the names completely and just track the level of nesting
404 int levelOfNesting = 0;
405 while (in.hasNext()) {
406 // in case there are text characters in an element, we cannot skip them by calling nextTag()
407 // therefore we skip them by calling next(), and then proceed to next element
409 if (!isAtElement(in)) {
412 if (in.isStartElement()) {
416 if (in.isEndElement()) {
417 if (levelOfNesting == 0) {
429 private void setValue(final AbstractNodeDataWithSchema parent, final Object value,
430 final NamespaceContext nsContext) {
431 checkArgument(parent instanceof SimpleNodeDataWithSchema, "Node %s is not a simple type",
432 parent.getSchema().getQName());
433 final SimpleNodeDataWithSchema parentSimpleNode = (SimpleNodeDataWithSchema) parent;
434 checkArgument(parentSimpleNode.getValue() == null, "Node '%s' has already set its value to '%s'",
435 parentSimpleNode.getSchema().getQName(), parentSimpleNode.getValue());
437 parentSimpleNode.setValue(translateValueByType(value, parentSimpleNode.getSchema(), nsContext));
440 private Object translateValueByType(final Object value, final DataSchemaNode node,
441 final NamespaceContext namespaceCtx) {
442 if (node instanceof AnyXmlSchemaNode) {
444 checkArgument(value instanceof Document);
446 * FIXME: Figure out some YANG extension dispatch, which will
447 * reuse JSON parsing or XML parsing - anyxml is not well-defined in
450 return new DOMSource(((Document) value).getDocumentElement());
453 checkArgument(node instanceof TypedDataSchemaNode);
454 checkArgument(value instanceof String);
455 return codecs.codecFor((TypedDataSchemaNode) node).parseValue(namespaceCtx, (String) value);
458 private static AbstractNodeDataWithSchema newEntryNode(final AbstractNodeDataWithSchema parent) {
459 final AbstractNodeDataWithSchema newChild;
460 if (parent instanceof ListNodeDataWithSchema) {
461 newChild = new ListEntryNodeDataWithSchema(parent.getSchema());
463 newChild = new LeafListEntryNodeDataWithSchema(parent.getSchema());
465 ((CompositeNodeDataWithSchema) parent).addChild(newChild);
470 public void close() throws IOException {
476 public void flush() throws IOException {