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
9 package org.opendaylight.yangtools.yang.data.codec.xml;
11 import static com.google.common.base.Preconditions.checkArgument;
12 import static com.google.common.base.Preconditions.checkState;
13 import static java.util.Objects.requireNonNull;
15 import com.google.common.annotations.Beta;
16 import com.google.common.collect.ImmutableMap;
17 import com.google.common.xml.XmlEscapers;
18 import java.io.Closeable;
19 import java.io.Flushable;
20 import java.io.IOException;
21 import java.io.StringReader;
23 import java.net.URISyntaxException;
24 import java.util.Deque;
25 import java.util.HashSet;
26 import java.util.LinkedHashMap;
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.transform.dom.DOMSource;
38 import org.opendaylight.yangtools.util.xml.UntrustedXML;
39 import org.opendaylight.yangtools.yang.common.QName;
40 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
41 import org.opendaylight.yangtools.yang.data.util.AbstractNodeDataWithSchema;
42 import org.opendaylight.yangtools.yang.data.util.AnyXmlNodeDataWithSchema;
43 import org.opendaylight.yangtools.yang.data.util.CompositeNodeDataWithSchema;
44 import org.opendaylight.yangtools.yang.data.util.ContainerNodeDataWithSchema;
45 import org.opendaylight.yangtools.yang.data.util.LeafListEntryNodeDataWithSchema;
46 import org.opendaylight.yangtools.yang.data.util.LeafListNodeDataWithSchema;
47 import org.opendaylight.yangtools.yang.data.util.LeafNodeDataWithSchema;
48 import org.opendaylight.yangtools.yang.data.util.ListEntryNodeDataWithSchema;
49 import org.opendaylight.yangtools.yang.data.util.ListNodeDataWithSchema;
50 import org.opendaylight.yangtools.yang.data.util.ParserStreamUtils;
51 import org.opendaylight.yangtools.yang.data.util.RpcAsContainer;
52 import org.opendaylight.yangtools.yang.data.util.SimpleNodeDataWithSchema;
53 import org.opendaylight.yangtools.yang.data.util.YangModeledAnyXmlNodeDataWithSchema;
54 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
61 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
62 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.YangModeledAnyXmlSchemaNode;
65 import org.w3c.dom.Document;
66 import org.xml.sax.InputSource;
67 import org.xml.sax.SAXException;
70 * This class provides functionality for parsing an XML source containing YANG-modeled data. It disallows multiple
71 * instances of the same element except for leaf-list and list entries. It also expects that the YANG-modeled data in
72 * the XML source are wrapped in a root element.
76 public final class XmlParserStream implements Closeable, Flushable {
77 private final NormalizedNodeStreamWriter writer;
78 private final XmlCodecFactory codecs;
79 private final DataSchemaNode parentNode;
80 private final boolean strictParsing;
82 private XmlParserStream(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
83 final DataSchemaNode parentNode, final boolean strictParsing) {
84 this.writer = requireNonNull(writer);
85 this.codecs = requireNonNull(codecs);
86 this.parentNode = parentNode;
87 this.strictParsing = strictParsing;
91 * Construct a new {@link XmlParserStream} with strict parsing mode switched on.
93 * @param writer Output writer
94 * @param codecs Shared codecs
95 * @param parentNode Parent root node
96 * @return A new stream instance
98 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
99 final SchemaNode parentNode) {
100 return create(writer, codecs, parentNode, true);
104 * Construct a new {@link XmlParserStream}.
106 * @param writer Output writer
107 * @param codecs Shared codecs
108 * @param parentNode Parent root node
109 * @param strictParsing parsing mode
110 * if set to true, the parser will throw an exception if it encounters unknown child nodes
111 * (nodes, that are not defined in the provided SchemaContext) in containers and lists
112 * if set to false, the parser will skip unknown child nodes
113 * @return A new stream instance
115 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
116 final SchemaNode parentNode, final boolean strictParsing) {
117 if (parentNode instanceof RpcDefinition) {
118 return new XmlParserStream(writer, codecs, new RpcAsContainer((RpcDefinition) parentNode), strictParsing);
120 checkArgument(parentNode instanceof DataSchemaNode, "Instance of DataSchemaNode class awaited.");
121 return new XmlParserStream(writer, codecs, (DataSchemaNode) parentNode, strictParsing);
125 * Construct a new {@link XmlParserStream}.
127 * @deprecated Use {@link #create(NormalizedNodeStreamWriter, SchemaContext, SchemaNode)} instead.
130 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext) {
131 return create(writer, schemaContext, schemaContext);
135 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
136 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
137 * maintain a {@link XmlCodecFactory} to match the current {@link SchemaContext}.
139 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
140 final SchemaNode parentNode) {
141 return create(writer, schemaContext, parentNode, true);
145 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
146 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
147 * maintain a {@link XmlCodecFactory} to match the current {@link SchemaContext}.
149 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
150 final SchemaNode parentNode, final boolean strictParsing) {
151 return create(writer, XmlCodecFactory.create(schemaContext), parentNode, strictParsing);
155 * This method parses the XML source and emits node events into a NormalizedNodeStreamWriter based on the
156 * YANG-modeled data contained in the XML source.
159 * StAX reader which is to used to walk through the XML source
161 * instance of XmlParserStream
162 * @throws XMLStreamException
163 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
164 * @throws URISyntaxException
165 * if the namespace URI of an XML element contains a syntax error
166 * @throws IOException
167 * if an error occurs while parsing the value of an anyxml node
168 * @throws ParserConfigurationException
169 * if an error occurs while parsing the value of an anyxml node
170 * @throws SAXException
171 * if an error occurs while parsing the value of an anyxml node
173 public XmlParserStream parse(final XMLStreamReader reader) throws XMLStreamException, URISyntaxException,
174 IOException, ParserConfigurationException, SAXException {
175 if (reader.hasNext()) {
177 final AbstractNodeDataWithSchema nodeDataWithSchema;
178 if (parentNode instanceof ContainerSchemaNode) {
179 nodeDataWithSchema = new ContainerNodeDataWithSchema(parentNode);
180 } else if (parentNode instanceof ListSchemaNode) {
181 nodeDataWithSchema = new ListNodeDataWithSchema(parentNode);
182 } else if (parentNode instanceof YangModeledAnyXmlSchemaNode) {
183 nodeDataWithSchema = new YangModeledAnyXmlNodeDataWithSchema((YangModeledAnyXmlSchemaNode) parentNode);
184 } else if (parentNode instanceof AnyXmlSchemaNode) {
185 nodeDataWithSchema = new AnyXmlNodeDataWithSchema(parentNode);
186 } else if (parentNode instanceof LeafSchemaNode) {
187 nodeDataWithSchema = new LeafNodeDataWithSchema(parentNode);
188 } else if (parentNode instanceof LeafListSchemaNode) {
189 nodeDataWithSchema = new LeafListNodeDataWithSchema(parentNode);
191 throw new IllegalStateException("Unsupported schema node type " + parentNode.getClass() + ".");
194 read(reader, nodeDataWithSchema, reader.getLocalName());
195 nodeDataWithSchema.write(writer);
202 * This method traverses a {@link DOMSource} and emits node events into a NormalizedNodeStreamWriter based on the
203 * YANG-modeled data contained in the source.
206 * {@link DOMSource} to be traversed
208 * instance of XmlParserStream
209 * @throws XMLStreamException
210 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
211 * @throws URISyntaxException
212 * if the namespace URI of an XML element contains a syntax error
213 * @throws IOException
214 * if an error occurs while parsing the value of an anyxml node
215 * @throws ParserConfigurationException
216 * if an error occurs while parsing the value of an anyxml node
217 * @throws SAXException
218 * if an error occurs while parsing the value of an anyxml node
221 public XmlParserStream traverse(final DOMSource src) throws XMLStreamException, URISyntaxException,
222 IOException, ParserConfigurationException, SAXException {
223 return parse(new DOMSourceXMLStreamReader(src));
226 private static Map<QName, String> getElementAttributes(final XMLStreamReader in) {
227 checkState(in.isStartElement(), "Attributes can be extracted only from START_ELEMENT.");
228 final Map<QName, String> attributes = new LinkedHashMap<>();
230 for (int attrIndex = 0; attrIndex < in.getAttributeCount(); attrIndex++) {
231 String attributeNS = in.getAttributeNamespace(attrIndex);
233 if (attributeNS == null) {
237 // Skip namespace definitions
238 if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attributeNS)) {
242 final QName qName = new QName(URI.create(attributeNS), in.getAttributeLocalName(attrIndex));
243 attributes.put(qName, in.getAttributeValue(attrIndex));
246 return ImmutableMap.copyOf(attributes);
249 private static String readAnyXmlValue(final XMLStreamReader in) throws XMLStreamException {
250 final StringBuilder sb = new StringBuilder();
251 final String anyXmlElementName = in.getLocalName();
252 sb.append('<').append(anyXmlElementName).append(" xmlns=\"").append(in.getNamespaceURI()).append("\">");
254 while (in.hasNext()) {
255 final int eventType = in.next();
257 if (eventType == XMLStreamConstants.START_ELEMENT) {
258 sb.append('<').append(in.getLocalName()).append('>');
259 } else if (eventType == XMLStreamConstants.END_ELEMENT) {
260 sb.append("</").append(in.getLocalName()).append('>');
262 if (in.getLocalName().equals(anyXmlElementName)) {
266 } else if (eventType == XMLStreamConstants.CHARACTERS) {
267 sb.append(XmlEscapers.xmlContentEscaper().escape(in.getText()));
271 return sb.toString();
274 private void read(final XMLStreamReader in, final AbstractNodeDataWithSchema parent, final String rootElement)
275 throws XMLStreamException, URISyntaxException, ParserConfigurationException, SAXException, IOException {
280 if (parent instanceof LeafNodeDataWithSchema || parent instanceof LeafListEntryNodeDataWithSchema) {
281 parent.setAttributes(getElementAttributes(in));
282 setValue(parent, in.getElementText().trim(), in.getNamespaceContext());
283 if (isNextEndDocument(in)) {
287 if (!isAtElement(in)) {
293 if (parent instanceof ListEntryNodeDataWithSchema || parent instanceof ContainerNodeDataWithSchema) {
294 parent.setAttributes(getElementAttributes(in));
297 if (parent instanceof LeafListNodeDataWithSchema || parent instanceof ListNodeDataWithSchema) {
298 String xmlElementName = in.getLocalName();
299 while (xmlElementName.equals(parent.getSchema().getQName().getLocalName())) {
300 read(in, newEntryNode(parent), rootElement);
301 if (in.getEventType() == XMLStreamConstants.END_DOCUMENT) {
304 xmlElementName = in.getLocalName();
310 if (parent instanceof AnyXmlNodeDataWithSchema) {
311 setValue(parent, readAnyXmlValue(in), in.getNamespaceContext());
312 if (isNextEndDocument(in)) {
316 if (!isAtElement(in)) {
323 if (parent instanceof YangModeledAnyXmlSchemaNode) {
324 parent.setAttributes(getElementAttributes(in));
327 switch (in.nextTag()) {
328 case XMLStreamConstants.START_ELEMENT:
329 final Set<String> namesakes = new HashSet<>();
330 while (in.hasNext()) {
331 final String xmlElementName = in.getLocalName();
333 DataSchemaNode parentSchema = parent.getSchema();
335 final String parentSchemaName = parentSchema.getQName().getLocalName();
336 if (parentSchemaName.equals(xmlElementName)
337 && in.getEventType() == XMLStreamConstants.END_ELEMENT) {
338 if (isNextEndDocument(in)) {
342 if (!isAtElement(in)) {
348 if (in.isEndElement() && rootElement.equals(xmlElementName)) {
352 if (parentSchema instanceof YangModeledAnyXmlSchemaNode) {
353 parentSchema = ((YangModeledAnyXmlSchemaNode) parentSchema).getSchemaOfAnyXmlData();
356 if (!namesakes.add(xmlElementName)) {
357 final Location loc = in.getLocation();
358 throw new IllegalStateException(String.format(
359 "Duplicate element \"%s\" in XML input at: line %s column %s", xmlElementName,
360 loc.getLineNumber(), loc.getColumnNumber()));
363 final String xmlElementNamespace = in.getNamespaceURI();
364 final Deque<DataSchemaNode> childDataSchemaNodes =
365 ParserStreamUtils.findSchemaNodeByNameAndNamespace(parentSchema, xmlElementName,
366 new URI(xmlElementNamespace));
368 if (childDataSchemaNodes.isEmpty()) {
369 checkState(!strictParsing, "Schema for node with name %s and namespace %s doesn't exist.",
370 xmlElementName, xmlElementNamespace);
375 read(in, ((CompositeNodeDataWithSchema) parent).addChild(childDataSchemaNodes), rootElement);
378 case XMLStreamConstants.END_ELEMENT:
379 if (isNextEndDocument(in)) {
383 if (!isAtElement(in)) {
392 private static boolean isNextEndDocument(final XMLStreamReader in) throws XMLStreamException {
393 return in.next() == XMLStreamConstants.END_DOCUMENT;
396 private static boolean isAtElement(final XMLStreamReader in) {
397 return in.getEventType() == XMLStreamConstants.START_ELEMENT
398 || in.getEventType() == XMLStreamConstants.END_ELEMENT;
401 private static void skipUnknownNode(final XMLStreamReader in) throws XMLStreamException {
402 // in case when the unknown node and at least one of its descendant nodes have the same name
403 // we cannot properly reach the end just by checking if the current node is an end element and has the same name
404 // as the root unknown element. therefore we ignore the names completely and just track the level of nesting
405 int levelOfNesting = 0;
406 while (in.hasNext()) {
407 // in case there are text characters in an element, we cannot skip them by calling nextTag()
408 // therefore we skip them by calling next(), and then proceed to next element
410 if (!isAtElement(in)) {
413 if (in.isStartElement()) {
417 if (in.isEndElement()) {
418 if (levelOfNesting == 0) {
429 private void setValue(final AbstractNodeDataWithSchema parent, final String value, final NamespaceContext nsContext)
430 throws ParserConfigurationException, SAXException, IOException {
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 String value, final DataSchemaNode node,
441 final NamespaceContext namespaceCtx) throws IOException, SAXException, ParserConfigurationException {
442 if (node instanceof AnyXmlSchemaNode) {
444 * FIXME: Figure out some YANG extension dispatch, which will
445 * reuse JSON parsing or XML parsing - anyxml is not well-defined in
448 final Document doc = UntrustedXML.newDocumentBuilder().parse(new InputSource(new StringReader(value)));
451 return new DOMSource(doc.getDocumentElement());
454 checkArgument(node instanceof TypedSchemaNode);
455 return codecs.codecFor((TypedSchemaNode) node).parseValue(namespaceCtx, 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 {