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 com.google.common.annotations.Beta;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.ImmutableMap;
14 import com.google.common.xml.XmlEscapers;
15 import java.io.Closeable;
16 import java.io.Flushable;
17 import java.io.IOException;
18 import java.io.StringReader;
20 import java.net.URISyntaxException;
21 import java.util.Deque;
22 import java.util.HashSet;
23 import java.util.LinkedHashMap;
26 import javax.annotation.concurrent.NotThreadSafe;
27 import javax.xml.XMLConstants;
28 import javax.xml.namespace.NamespaceContext;
29 import javax.xml.parsers.ParserConfigurationException;
30 import javax.xml.stream.Location;
31 import javax.xml.stream.XMLStreamConstants;
32 import javax.xml.stream.XMLStreamException;
33 import javax.xml.stream.XMLStreamReader;
34 import javax.xml.transform.dom.DOMSource;
35 import org.opendaylight.yangtools.util.xml.UntrustedXML;
36 import org.opendaylight.yangtools.yang.common.QName;
37 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
38 import org.opendaylight.yangtools.yang.data.util.AbstractNodeDataWithSchema;
39 import org.opendaylight.yangtools.yang.data.util.AnyXmlNodeDataWithSchema;
40 import org.opendaylight.yangtools.yang.data.util.CompositeNodeDataWithSchema;
41 import org.opendaylight.yangtools.yang.data.util.ContainerNodeDataWithSchema;
42 import org.opendaylight.yangtools.yang.data.util.LeafListEntryNodeDataWithSchema;
43 import org.opendaylight.yangtools.yang.data.util.LeafListNodeDataWithSchema;
44 import org.opendaylight.yangtools.yang.data.util.LeafNodeDataWithSchema;
45 import org.opendaylight.yangtools.yang.data.util.ListEntryNodeDataWithSchema;
46 import org.opendaylight.yangtools.yang.data.util.ListNodeDataWithSchema;
47 import org.opendaylight.yangtools.yang.data.util.ParserStreamUtils;
48 import org.opendaylight.yangtools.yang.data.util.RpcAsContainer;
49 import org.opendaylight.yangtools.yang.data.util.SimpleNodeDataWithSchema;
50 import org.opendaylight.yangtools.yang.data.util.YangModeledAnyXmlNodeDataWithSchema;
51 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
58 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
59 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.YangModeledAnyXmlSchemaNode;
62 import org.w3c.dom.Document;
63 import org.xml.sax.InputSource;
64 import org.xml.sax.SAXException;
67 * This class provides functionality for parsing an XML source containing YANG-modeled data. It disallows multiple
68 * instances of the same element except for leaf-list and list entries. It also expects that the YANG-modeled data in
69 * the XML source are wrapped in a root element.
73 public final class XmlParserStream implements Closeable, Flushable {
74 private final NormalizedNodeStreamWriter writer;
75 private final XmlCodecFactory codecs;
76 private final DataSchemaNode parentNode;
77 private final boolean strictParsing;
79 private XmlParserStream(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
80 final DataSchemaNode parentNode, final boolean strictParsing) {
81 this.writer = Preconditions.checkNotNull(writer);
82 this.codecs = Preconditions.checkNotNull(codecs);
83 this.parentNode = parentNode;
84 this.strictParsing = strictParsing;
88 * Construct a new {@link XmlParserStream} with strict parsing mode switched on.
90 * @param writer Output writer
91 * @param codecs Shared codecs
92 * @param parentNode Parent root node
93 * @return A new stream instance
95 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
96 final SchemaNode parentNode) {
97 return create(writer, codecs, parentNode, true);
101 * Construct a new {@link XmlParserStream}.
103 * @param writer Output writer
104 * @param codecs Shared codecs
105 * @param parentNode Parent root node
106 * @param strictParsing parsing mode
107 * if set to true, the parser will throw an exception if it encounters unknown child nodes
108 * (nodes, that are not defined in the provided SchemaContext) in containers and lists
109 * if set to false, the parser will skip unknown child nodes
110 * @return A new stream instance
112 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
113 final SchemaNode parentNode, final boolean strictParsing) {
114 if (parentNode instanceof RpcDefinition) {
115 return new XmlParserStream(writer, codecs, new RpcAsContainer((RpcDefinition) parentNode), strictParsing);
117 Preconditions.checkArgument(parentNode instanceof DataSchemaNode, "Instance of DataSchemaNode class awaited.");
118 return new XmlParserStream(writer, codecs, (DataSchemaNode) parentNode, strictParsing);
122 * Construct a new {@link XmlParserStream}.
124 * @deprecated Use {@link #create(NormalizedNodeStreamWriter, SchemaContext, SchemaNode)} instead.
127 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext) {
128 return create(writer, schemaContext, schemaContext);
132 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
133 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
134 * maintain a {@link XmlCodecFactory} to match the current {@link SchemaContext}.
136 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
137 final SchemaNode parentNode) {
138 return create(writer, schemaContext, parentNode, true);
142 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
143 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
144 * maintain a {@link XmlCodecFactory} to match the current {@link SchemaContext}.
146 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
147 final SchemaNode parentNode, final boolean strictParsing) {
148 return create(writer, XmlCodecFactory.create(schemaContext), parentNode, strictParsing);
152 * This method parses the XML source and emits node events into a NormalizedNodeStreamWriter based on the
153 * YANG-modeled data contained in the XML source.
156 * StAX reader which is to used to walk through the XML source
158 * instance of XmlParserStream
159 * @throws XMLStreamException
160 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
161 * @throws URISyntaxException
162 * if the namespace URI of an XML element contains a syntax error
163 * @throws IOException
164 * if an error occurs while parsing the value of an anyxml node
165 * @throws ParserConfigurationException
166 * if an error occurs while parsing the value of an anyxml node
167 * @throws SAXException
168 * if an error occurs while parsing the value of an anyxml node
170 public XmlParserStream parse(final XMLStreamReader reader) throws XMLStreamException, URISyntaxException,
171 IOException, ParserConfigurationException, SAXException {
172 if (reader.hasNext()) {
174 final AbstractNodeDataWithSchema nodeDataWithSchema;
175 if (parentNode instanceof ContainerSchemaNode) {
176 nodeDataWithSchema = new ContainerNodeDataWithSchema(parentNode);
177 } else if (parentNode instanceof ListSchemaNode) {
178 nodeDataWithSchema = new ListNodeDataWithSchema(parentNode);
179 } else if (parentNode instanceof YangModeledAnyXmlSchemaNode) {
180 nodeDataWithSchema = new YangModeledAnyXmlNodeDataWithSchema((YangModeledAnyXmlSchemaNode) parentNode);
181 } else if (parentNode instanceof AnyXmlSchemaNode) {
182 nodeDataWithSchema = new AnyXmlNodeDataWithSchema(parentNode);
183 } else if (parentNode instanceof LeafSchemaNode) {
184 nodeDataWithSchema = new LeafNodeDataWithSchema(parentNode);
185 } else if (parentNode instanceof LeafListSchemaNode) {
186 nodeDataWithSchema = new LeafListNodeDataWithSchema(parentNode);
188 throw new IllegalStateException("Unsupported schema node type " + parentNode.getClass() + ".");
191 read(reader, nodeDataWithSchema, reader.getLocalName());
192 nodeDataWithSchema.write(writer);
199 * This method traverses a {@link DOMSource} and emits node events into a NormalizedNodeStreamWriter based on the
200 * YANG-modeled data contained in the source.
203 * {@link DOMSource} to be traversed
205 * instance of XmlParserStream
206 * @throws XMLStreamException
207 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
208 * @throws URISyntaxException
209 * if the namespace URI of an XML element contains a syntax error
210 * @throws IOException
211 * if an error occurs while parsing the value of an anyxml node
212 * @throws ParserConfigurationException
213 * if an error occurs while parsing the value of an anyxml node
214 * @throws SAXException
215 * if an error occurs while parsing the value of an anyxml node
218 public XmlParserStream traverse(final DOMSource src) throws XMLStreamException, URISyntaxException,
219 IOException, ParserConfigurationException, SAXException {
220 return parse(new DOMSourceXMLStreamReader(src));
223 private static Map<QName, String> getElementAttributes(final XMLStreamReader in) {
224 Preconditions.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 = new QName(URI.create(attributeNS), in.getAttributeLocalName(attrIndex));
240 attributes.put(qName, in.getAttributeValue(attrIndex));
243 return ImmutableMap.copyOf(attributes);
246 private static String readAnyXmlValue(final XMLStreamReader in) throws XMLStreamException {
247 final StringBuilder sb = new StringBuilder();
248 final String anyXmlElementName = in.getLocalName();
249 sb.append('<').append(anyXmlElementName).append(" xmlns=\"").append(in.getNamespaceURI()).append("\">");
251 while (in.hasNext()) {
252 final int eventType = in.next();
254 if (eventType == XMLStreamConstants.START_ELEMENT) {
255 sb.append('<').append(in.getLocalName()).append('>');
256 } else if (eventType == XMLStreamConstants.END_ELEMENT) {
257 sb.append("</").append(in.getLocalName()).append('>');
259 if (in.getLocalName().equals(anyXmlElementName)) {
263 } else if (eventType == XMLStreamConstants.CHARACTERS) {
264 sb.append(XmlEscapers.xmlContentEscaper().escape(in.getText()));
268 return sb.toString();
271 private void read(final XMLStreamReader in, final AbstractNodeDataWithSchema parent, final String rootElement)
272 throws XMLStreamException, URISyntaxException, ParserConfigurationException, SAXException, IOException {
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) {
301 xmlElementName = in.getLocalName();
307 if (parent instanceof AnyXmlNodeDataWithSchema) {
308 setValue(parent, readAnyXmlValue(in), in.getNamespaceContext());
309 if (isNextEndDocument(in)) {
313 if (!isAtElement(in)) {
320 if (parent instanceof YangModeledAnyXmlSchemaNode) {
321 parent.setAttributes(getElementAttributes(in));
324 switch (in.nextTag()) {
325 case XMLStreamConstants.START_ELEMENT:
326 final Set<String> namesakes = new HashSet<>();
327 while (in.hasNext()) {
328 final String xmlElementName = in.getLocalName();
330 DataSchemaNode parentSchema = parent.getSchema();
332 final String parentSchemaName = parentSchema.getQName().getLocalName();
333 if (parentSchemaName.equals(xmlElementName)
334 && in.getEventType() == XMLStreamConstants.END_ELEMENT) {
335 if (isNextEndDocument(in)) {
339 if (!isAtElement(in)) {
345 if (in.isEndElement() && rootElement.equals(xmlElementName)) {
349 if (parentSchema instanceof YangModeledAnyXmlSchemaNode) {
350 parentSchema = ((YangModeledAnyXmlSchemaNode) parentSchema).getSchemaOfAnyXmlData();
353 if (!namesakes.add(xmlElementName)) {
354 final Location loc = in.getLocation();
355 throw new IllegalStateException(String.format(
356 "Duplicate element \"%s\" in XML input at: line %s column %s", xmlElementName,
357 loc.getLineNumber(), loc.getColumnNumber()));
360 final String xmlElementNamespace = in.getNamespaceURI();
361 final Deque<DataSchemaNode> childDataSchemaNodes =
362 ParserStreamUtils.findSchemaNodeByNameAndNamespace(parentSchema, xmlElementName,
363 new URI(xmlElementNamespace));
365 if (childDataSchemaNodes.isEmpty()) {
366 Preconditions.checkState(!strictParsing,
367 "Schema for node with name %s and namespace %s doesn't exist.", xmlElementName,
368 xmlElementNamespace);
373 read(in, ((CompositeNodeDataWithSchema) parent).addChild(childDataSchemaNodes), rootElement);
376 case XMLStreamConstants.END_ELEMENT:
377 if (isNextEndDocument(in)) {
381 if (!isAtElement(in)) {
390 private static boolean isNextEndDocument(final XMLStreamReader in) throws XMLStreamException {
391 return in.next() == XMLStreamConstants.END_DOCUMENT;
394 private static boolean isAtElement(final XMLStreamReader in) {
395 return in.getEventType() == XMLStreamConstants.START_ELEMENT
396 || in.getEventType() == XMLStreamConstants.END_ELEMENT;
399 private static void skipUnknownNode(final XMLStreamReader in) throws XMLStreamException {
400 // in case when the unknown node and at least one of its descendant nodes have the same name
401 // we cannot properly reach the end just by checking if the current node is an end element and has the same name
402 // as the root unknown element. therefore we ignore the names completely and just track the level of nesting
403 int levelOfNesting = 0;
404 while (in.hasNext()) {
405 // in case there are text characters in an element, we cannot skip them by calling nextTag()
406 // therefore we skip them by calling next(), and then proceed to next element
408 if (!isAtElement(in)) {
411 if (in.isStartElement()) {
415 if (in.isEndElement()) {
416 if (levelOfNesting == 0) {
427 private void setValue(final AbstractNodeDataWithSchema parent, final String value, final NamespaceContext nsContext)
428 throws ParserConfigurationException, SAXException, IOException {
429 Preconditions.checkArgument(parent instanceof SimpleNodeDataWithSchema, "Node %s is not a simple type",
430 parent.getSchema().getQName());
431 final SimpleNodeDataWithSchema parentSimpleNode = (SimpleNodeDataWithSchema) parent;
432 Preconditions.checkArgument(parentSimpleNode.getValue() == null, "Node '%s' has already set its value to '%s'",
433 parentSimpleNode.getSchema().getQName(), parentSimpleNode.getValue());
435 parentSimpleNode.setValue(translateValueByType(value, parentSimpleNode.getSchema(), nsContext));
438 private Object translateValueByType(final String value, final DataSchemaNode node,
439 final NamespaceContext namespaceCtx) throws IOException, SAXException, ParserConfigurationException {
440 if (node instanceof AnyXmlSchemaNode) {
442 * FIXME: Figure out some YANG extension dispatch, which will
443 * reuse JSON parsing or XML parsing - anyxml is not well-defined in
446 final Document doc = UntrustedXML.newDocumentBuilder().parse(new InputSource(new StringReader(value)));
449 return new DOMSource(doc.getDocumentElement());
452 Preconditions.checkArgument(node instanceof TypedSchemaNode);
453 return codecs.codecFor((TypedSchemaNode) node).parseValue(namespaceCtx, value);
456 private static AbstractNodeDataWithSchema newEntryNode(final AbstractNodeDataWithSchema parent) {
457 final AbstractNodeDataWithSchema newChild;
458 if (parent instanceof ListNodeDataWithSchema) {
459 newChild = new ListEntryNodeDataWithSchema(parent.getSchema());
461 newChild = new LeafListEntryNodeDataWithSchema(parent.getSchema());
463 ((CompositeNodeDataWithSchema) parent).addChild(newChild);
468 public void close() throws IOException {
474 public void flush() throws IOException {