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.odlext.model.api.YangModeledAnyXmlSchemaNode;
39 import org.opendaylight.yangtools.util.xml.UntrustedXML;
40 import org.opendaylight.yangtools.yang.common.QName;
41 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
42 import org.opendaylight.yangtools.yang.data.util.AbstractNodeDataWithSchema;
43 import org.opendaylight.yangtools.yang.data.util.AnyXmlNodeDataWithSchema;
44 import org.opendaylight.yangtools.yang.data.util.CompositeNodeDataWithSchema;
45 import org.opendaylight.yangtools.yang.data.util.ContainerNodeDataWithSchema;
46 import org.opendaylight.yangtools.yang.data.util.LeafListEntryNodeDataWithSchema;
47 import org.opendaylight.yangtools.yang.data.util.LeafListNodeDataWithSchema;
48 import org.opendaylight.yangtools.yang.data.util.LeafNodeDataWithSchema;
49 import org.opendaylight.yangtools.yang.data.util.ListEntryNodeDataWithSchema;
50 import org.opendaylight.yangtools.yang.data.util.ListNodeDataWithSchema;
51 import org.opendaylight.yangtools.yang.data.util.ParserStreamUtils;
52 import org.opendaylight.yangtools.yang.data.util.RpcAsContainer;
53 import org.opendaylight.yangtools.yang.data.util.SimpleNodeDataWithSchema;
54 import org.opendaylight.yangtools.yang.data.util.YangModeledAnyXmlNodeDataWithSchema;
55 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
62 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
63 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
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 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
126 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
127 * maintain a {@link XmlCodecFactory} to match the current {@link SchemaContext}.
129 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
130 final SchemaNode parentNode) {
131 return create(writer, schemaContext, parentNode, true);
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, final boolean strictParsing) {
141 return create(writer, XmlCodecFactory.create(schemaContext), parentNode, strictParsing);
145 * This method parses the XML source and emits node events into a NormalizedNodeStreamWriter based on the
146 * YANG-modeled data contained in the XML source.
149 * StAX reader which is to used to walk through the XML source
151 * instance of XmlParserStream
152 * @throws XMLStreamException
153 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
154 * @throws URISyntaxException
155 * if the namespace URI of an XML element contains a syntax error
156 * @throws IOException
157 * if an error occurs while parsing the value of an anyxml node
158 * @throws ParserConfigurationException
159 * if an error occurs while parsing the value of an anyxml node
160 * @throws SAXException
161 * if an error occurs while parsing the value of an anyxml node
163 public XmlParserStream parse(final XMLStreamReader reader) throws XMLStreamException, URISyntaxException,
164 IOException, ParserConfigurationException, SAXException {
165 if (reader.hasNext()) {
167 final AbstractNodeDataWithSchema nodeDataWithSchema;
168 if (parentNode instanceof ContainerSchemaNode) {
169 nodeDataWithSchema = new ContainerNodeDataWithSchema(parentNode);
170 } else if (parentNode instanceof ListSchemaNode) {
171 nodeDataWithSchema = new ListNodeDataWithSchema(parentNode);
172 } else if (parentNode instanceof YangModeledAnyXmlSchemaNode) {
173 nodeDataWithSchema = new YangModeledAnyXmlNodeDataWithSchema((YangModeledAnyXmlSchemaNode) parentNode);
174 } else if (parentNode instanceof AnyXmlSchemaNode) {
175 nodeDataWithSchema = new AnyXmlNodeDataWithSchema(parentNode);
176 } else if (parentNode instanceof LeafSchemaNode) {
177 nodeDataWithSchema = new LeafNodeDataWithSchema(parentNode);
178 } else if (parentNode instanceof LeafListSchemaNode) {
179 nodeDataWithSchema = new LeafListNodeDataWithSchema(parentNode);
181 throw new IllegalStateException("Unsupported schema node type " + parentNode.getClass() + ".");
184 read(reader, nodeDataWithSchema, reader.getLocalName());
185 nodeDataWithSchema.write(writer);
192 * This method traverses a {@link DOMSource} and emits node events into a NormalizedNodeStreamWriter based on the
193 * YANG-modeled data contained in the source.
196 * {@link DOMSource} to be traversed
198 * instance of XmlParserStream
199 * @throws XMLStreamException
200 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
201 * @throws URISyntaxException
202 * if the namespace URI of an XML element contains a syntax error
203 * @throws IOException
204 * if an error occurs while parsing the value of an anyxml node
205 * @throws ParserConfigurationException
206 * if an error occurs while parsing the value of an anyxml node
207 * @throws SAXException
208 * if an error occurs while parsing the value of an anyxml node
211 public XmlParserStream traverse(final DOMSource src) throws XMLStreamException, URISyntaxException,
212 IOException, ParserConfigurationException, SAXException {
213 return parse(new DOMSourceXMLStreamReader(src));
216 private static Map<QName, String> getElementAttributes(final XMLStreamReader in) {
217 checkState(in.isStartElement(), "Attributes can be extracted only from START_ELEMENT.");
218 final Map<QName, String> attributes = new LinkedHashMap<>();
220 for (int attrIndex = 0; attrIndex < in.getAttributeCount(); attrIndex++) {
221 String attributeNS = in.getAttributeNamespace(attrIndex);
223 if (attributeNS == null) {
227 // Skip namespace definitions
228 if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attributeNS)) {
232 final QName qName = QName.create(URI.create(attributeNS), in.getAttributeLocalName(attrIndex));
233 attributes.put(qName, in.getAttributeValue(attrIndex));
236 return ImmutableMap.copyOf(attributes);
239 private static String readAnyXmlValue(final XMLStreamReader in) throws XMLStreamException {
240 final StringBuilder sb = new StringBuilder();
241 final String anyXmlElementName = in.getLocalName();
242 sb.append('<').append(anyXmlElementName).append(" xmlns=\"").append(in.getNamespaceURI()).append("\">");
244 while (in.hasNext()) {
245 final int eventType = in.next();
247 if (eventType == XMLStreamConstants.START_ELEMENT) {
248 sb.append('<').append(in.getLocalName()).append('>');
249 } else if (eventType == XMLStreamConstants.END_ELEMENT) {
250 sb.append("</").append(in.getLocalName()).append('>');
252 if (in.getLocalName().equals(anyXmlElementName)) {
256 } else if (eventType == XMLStreamConstants.CHARACTERS) {
257 sb.append(XmlEscapers.xmlContentEscaper().escape(in.getText()));
261 return sb.toString();
264 private void read(final XMLStreamReader in, final AbstractNodeDataWithSchema parent, final String rootElement)
265 throws XMLStreamException, URISyntaxException, ParserConfigurationException, SAXException, IOException {
270 if (parent instanceof LeafNodeDataWithSchema || parent instanceof LeafListEntryNodeDataWithSchema) {
271 parent.setAttributes(getElementAttributes(in));
272 setValue(parent, in.getElementText().trim(), in.getNamespaceContext());
273 if (isNextEndDocument(in)) {
277 if (!isAtElement(in)) {
283 if (parent instanceof ListEntryNodeDataWithSchema || parent instanceof ContainerNodeDataWithSchema) {
284 parent.setAttributes(getElementAttributes(in));
287 if (parent instanceof LeafListNodeDataWithSchema || parent instanceof ListNodeDataWithSchema) {
288 String xmlElementName = in.getLocalName();
289 while (xmlElementName.equals(parent.getSchema().getQName().getLocalName())) {
290 read(in, newEntryNode(parent), rootElement);
291 if (in.getEventType() == XMLStreamConstants.END_DOCUMENT) {
294 xmlElementName = in.getLocalName();
300 if (parent instanceof AnyXmlNodeDataWithSchema) {
301 setValue(parent, readAnyXmlValue(in), in.getNamespaceContext());
302 if (isNextEndDocument(in)) {
306 if (!isAtElement(in)) {
313 if (parent instanceof YangModeledAnyXmlSchemaNode) {
314 parent.setAttributes(getElementAttributes(in));
317 switch (in.nextTag()) {
318 case XMLStreamConstants.START_ELEMENT:
319 final Set<String> namesakes = new HashSet<>();
320 while (in.hasNext()) {
321 final String xmlElementName = in.getLocalName();
323 DataSchemaNode parentSchema = parent.getSchema();
325 final String parentSchemaName = parentSchema.getQName().getLocalName();
326 if (parentSchemaName.equals(xmlElementName)
327 && in.getEventType() == XMLStreamConstants.END_ELEMENT) {
328 if (isNextEndDocument(in)) {
332 if (!isAtElement(in)) {
338 if (in.isEndElement() && rootElement.equals(xmlElementName)) {
342 if (parentSchema instanceof YangModeledAnyXmlSchemaNode) {
343 parentSchema = ((YangModeledAnyXmlSchemaNode) parentSchema).getSchemaOfAnyXmlData();
346 if (!namesakes.add(xmlElementName)) {
347 final Location loc = in.getLocation();
348 throw new IllegalStateException(String.format(
349 "Duplicate element \"%s\" in XML input at: line %s column %s", xmlElementName,
350 loc.getLineNumber(), loc.getColumnNumber()));
353 final String xmlElementNamespace = in.getNamespaceURI();
354 final Deque<DataSchemaNode> childDataSchemaNodes =
355 ParserStreamUtils.findSchemaNodeByNameAndNamespace(parentSchema, xmlElementName,
356 new URI(xmlElementNamespace));
358 if (childDataSchemaNodes.isEmpty()) {
359 checkState(!strictParsing, "Schema for node with name %s and namespace %s does not exist at %s",
360 xmlElementName, xmlElementNamespace, parentSchema.getPath());
365 read(in, ((CompositeNodeDataWithSchema) parent).addChild(childDataSchemaNodes), rootElement);
368 case XMLStreamConstants.END_ELEMENT:
369 if (isNextEndDocument(in)) {
373 if (!isAtElement(in)) {
382 private static boolean isNextEndDocument(final XMLStreamReader in) throws XMLStreamException {
383 return in.next() == XMLStreamConstants.END_DOCUMENT;
386 private static boolean isAtElement(final XMLStreamReader in) {
387 return in.getEventType() == XMLStreamConstants.START_ELEMENT
388 || in.getEventType() == XMLStreamConstants.END_ELEMENT;
391 private static void skipUnknownNode(final XMLStreamReader in) throws XMLStreamException {
392 // in case when the unknown node and at least one of its descendant nodes have the same name
393 // we cannot properly reach the end just by checking if the current node is an end element and has the same name
394 // as the root unknown element. therefore we ignore the names completely and just track the level of nesting
395 int levelOfNesting = 0;
396 while (in.hasNext()) {
397 // in case there are text characters in an element, we cannot skip them by calling nextTag()
398 // therefore we skip them by calling next(), and then proceed to next element
400 if (!isAtElement(in)) {
403 if (in.isStartElement()) {
407 if (in.isEndElement()) {
408 if (levelOfNesting == 0) {
419 private void setValue(final AbstractNodeDataWithSchema parent, final String value, final NamespaceContext nsContext)
420 throws ParserConfigurationException, SAXException, IOException {
421 checkArgument(parent instanceof SimpleNodeDataWithSchema, "Node %s is not a simple type",
422 parent.getSchema().getQName());
423 final SimpleNodeDataWithSchema parentSimpleNode = (SimpleNodeDataWithSchema) parent;
424 checkArgument(parentSimpleNode.getValue() == null, "Node '%s' has already set its value to '%s'",
425 parentSimpleNode.getSchema().getQName(), parentSimpleNode.getValue());
427 parentSimpleNode.setValue(translateValueByType(value, parentSimpleNode.getSchema(), nsContext));
430 private Object translateValueByType(final String value, final DataSchemaNode node,
431 final NamespaceContext namespaceCtx) throws IOException, SAXException, ParserConfigurationException {
432 if (node instanceof AnyXmlSchemaNode) {
434 * FIXME: Figure out some YANG extension dispatch, which will
435 * reuse JSON parsing or XML parsing - anyxml is not well-defined in
438 final Document doc = UntrustedXML.newDocumentBuilder().parse(new InputSource(new StringReader(value)));
441 return new DOMSource(doc.getDocumentElement());
444 checkArgument(node instanceof TypedDataSchemaNode);
445 return codecs.codecFor((TypedDataSchemaNode) node).parseValue(namespaceCtx, value);
448 private static AbstractNodeDataWithSchema newEntryNode(final AbstractNodeDataWithSchema parent) {
449 final AbstractNodeDataWithSchema newChild;
450 if (parent instanceof ListNodeDataWithSchema) {
451 newChild = new ListEntryNodeDataWithSchema(parent.getSchema());
453 newChild = new LeafListEntryNodeDataWithSchema(parent.getSchema());
455 ((CompositeNodeDataWithSchema) parent).addChild(newChild);
460 public void close() throws IOException {
466 public void flush() throws IOException {