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;
14 import com.google.common.annotations.Beta;
15 import com.google.common.collect.ImmutableMap;
16 import com.google.common.xml.XmlEscapers;
17 import java.io.Closeable;
18 import java.io.Flushable;
19 import java.io.IOException;
20 import java.io.StringReader;
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;
28 import java.util.Map.Entry;
30 import javax.annotation.concurrent.NotThreadSafe;
31 import javax.xml.XMLConstants;
32 import javax.xml.namespace.NamespaceContext;
33 import javax.xml.parsers.ParserConfigurationException;
34 import javax.xml.stream.Location;
35 import javax.xml.stream.XMLStreamConstants;
36 import javax.xml.stream.XMLStreamException;
37 import javax.xml.stream.XMLStreamReader;
38 import javax.xml.transform.dom.DOMSource;
39 import org.opendaylight.yangtools.odlext.model.api.YangModeledAnyXmlSchemaNode;
40 import org.opendaylight.yangtools.util.xml.UntrustedXML;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
43 import org.opendaylight.yangtools.yang.data.util.AbstractNodeDataWithSchema;
44 import org.opendaylight.yangtools.yang.data.util.AnyXmlNodeDataWithSchema;
45 import org.opendaylight.yangtools.yang.data.util.CompositeNodeDataWithSchema;
46 import org.opendaylight.yangtools.yang.data.util.ContainerNodeDataWithSchema;
47 import org.opendaylight.yangtools.yang.data.util.LeafListEntryNodeDataWithSchema;
48 import org.opendaylight.yangtools.yang.data.util.LeafListNodeDataWithSchema;
49 import org.opendaylight.yangtools.yang.data.util.LeafNodeDataWithSchema;
50 import org.opendaylight.yangtools.yang.data.util.ListEntryNodeDataWithSchema;
51 import org.opendaylight.yangtools.yang.data.util.ListNodeDataWithSchema;
52 import org.opendaylight.yangtools.yang.data.util.ParserStreamUtils;
53 import org.opendaylight.yangtools.yang.data.util.RpcAsContainer;
54 import org.opendaylight.yangtools.yang.data.util.SimpleNodeDataWithSchema;
55 import org.opendaylight.yangtools.yang.data.util.YangModeledAnyXmlNodeDataWithSchema;
56 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
63 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
64 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
66 import org.w3c.dom.Document;
67 import org.xml.sax.InputSource;
68 import org.xml.sax.SAXException;
71 * This class provides functionality for parsing an XML source containing YANG-modeled data. It disallows multiple
72 * instances of the same element except for leaf-list and list entries. It also expects that the YANG-modeled data in
73 * the XML source are wrapped in a root element.
77 public final class XmlParserStream implements Closeable, Flushable {
78 private final NormalizedNodeStreamWriter writer;
79 private final XmlCodecFactory codecs;
80 private final DataSchemaNode parentNode;
81 private final boolean strictParsing;
83 private XmlParserStream(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
84 final DataSchemaNode parentNode, final boolean strictParsing) {
85 this.writer = requireNonNull(writer);
86 this.codecs = requireNonNull(codecs);
87 this.parentNode = parentNode;
88 this.strictParsing = strictParsing;
92 * Construct a new {@link XmlParserStream} with strict parsing mode switched on.
94 * @param writer Output writer
95 * @param codecs Shared codecs
96 * @param parentNode Parent root node
97 * @return A new stream instance
99 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
100 final SchemaNode parentNode) {
101 return create(writer, codecs, parentNode, true);
105 * Construct a new {@link XmlParserStream}.
107 * @param writer Output writer
108 * @param codecs Shared codecs
109 * @param parentNode Parent root node
110 * @param strictParsing parsing mode
111 * if set to true, the parser will throw an exception if it encounters unknown child nodes
112 * (nodes, that are not defined in the provided SchemaContext) in containers and lists
113 * if set to false, the parser will skip unknown child nodes
114 * @return A new stream instance
116 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
117 final SchemaNode parentNode, final boolean strictParsing) {
118 if (parentNode instanceof RpcDefinition) {
119 return new XmlParserStream(writer, codecs, new RpcAsContainer((RpcDefinition) parentNode), strictParsing);
121 checkArgument(parentNode instanceof DataSchemaNode, "Instance of DataSchemaNode class awaited.");
122 return new XmlParserStream(writer, codecs, (DataSchemaNode) parentNode, strictParsing);
126 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
127 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
128 * maintain a {@link XmlCodecFactory} to match the current {@link SchemaContext}.
130 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
131 final SchemaNode parentNode) {
132 return create(writer, schemaContext, parentNode, true);
136 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
137 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
138 * maintain a {@link XmlCodecFactory} to match the current {@link SchemaContext}.
140 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
141 final SchemaNode parentNode, final boolean strictParsing) {
142 return create(writer, XmlCodecFactory.create(schemaContext), parentNode, strictParsing);
146 * This method parses the XML source and emits node events into a NormalizedNodeStreamWriter based on the
147 * YANG-modeled data contained in the XML source.
150 * StAX reader which is to used to walk through the XML source
152 * instance of XmlParserStream
153 * @throws XMLStreamException
154 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
155 * @throws URISyntaxException
156 * if the namespace URI of an XML element contains a syntax error
157 * @throws IOException
158 * if an error occurs while parsing the value of an anyxml node
159 * @throws ParserConfigurationException
160 * if an error occurs while parsing the value of an anyxml node
161 * @throws SAXException
162 * if an error occurs while parsing the value of an anyxml node
164 // FIXME: 3.0.0 remove ParserConfigurationException
165 public XmlParserStream parse(final XMLStreamReader reader) throws XMLStreamException, URISyntaxException,
166 IOException, ParserConfigurationException, SAXException {
167 if (reader.hasNext()) {
169 final AbstractNodeDataWithSchema nodeDataWithSchema;
170 if (parentNode instanceof ContainerSchemaNode) {
171 nodeDataWithSchema = new ContainerNodeDataWithSchema(parentNode);
172 } else if (parentNode instanceof ListSchemaNode) {
173 nodeDataWithSchema = new ListNodeDataWithSchema(parentNode);
174 } else if (parentNode instanceof YangModeledAnyXmlSchemaNode) {
175 nodeDataWithSchema = new YangModeledAnyXmlNodeDataWithSchema((YangModeledAnyXmlSchemaNode) parentNode);
176 } else if (parentNode instanceof AnyXmlSchemaNode) {
177 nodeDataWithSchema = new AnyXmlNodeDataWithSchema(parentNode);
178 } else if (parentNode instanceof LeafSchemaNode) {
179 nodeDataWithSchema = new LeafNodeDataWithSchema(parentNode);
180 } else if (parentNode instanceof LeafListSchemaNode) {
181 nodeDataWithSchema = new LeafListNodeDataWithSchema(parentNode);
183 throw new IllegalStateException("Unsupported schema node type " + parentNode.getClass() + ".");
186 read(reader, nodeDataWithSchema, reader.getLocalName());
187 nodeDataWithSchema.write(writer);
194 * This method traverses a {@link DOMSource} and emits node events into a NormalizedNodeStreamWriter based on the
195 * YANG-modeled data contained in the source.
198 * {@link DOMSource} to be traversed
200 * instance of XmlParserStream
201 * @throws XMLStreamException
202 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
203 * @throws URISyntaxException
204 * if the namespace URI of an XML element contains a syntax error
205 * @throws IOException
206 * if an error occurs while parsing the value of an anyxml node
207 * @throws ParserConfigurationException
208 * if an error occurs while parsing the value of an anyxml node
209 * @throws SAXException
210 * if an error occurs while parsing the value of an anyxml node
213 // FIXME: 3.0.0 remove ParserConfigurationException
214 public XmlParserStream traverse(final DOMSource src) throws XMLStreamException, URISyntaxException,
215 IOException, ParserConfigurationException, SAXException {
216 return parse(new DOMSourceXMLStreamReader(src));
219 private static Map<QName, String> getElementAttributes(final XMLStreamReader in) {
220 checkState(in.isStartElement(), "Attributes can be extracted only from START_ELEMENT.");
221 final Map<QName, String> attributes = new LinkedHashMap<>();
223 for (int attrIndex = 0; attrIndex < in.getAttributeCount(); attrIndex++) {
224 String attributeNS = in.getAttributeNamespace(attrIndex);
226 if (attributeNS == null) {
230 // Skip namespace definitions
231 if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attributeNS)) {
235 final QName qName = QName.create(URI.create(attributeNS), in.getAttributeLocalName(attrIndex));
236 attributes.put(qName, in.getAttributeValue(attrIndex));
239 return ImmutableMap.copyOf(attributes);
242 private static String readAnyXmlValue(final XMLStreamReader in) throws XMLStreamException {
243 final StringBuilder sb = new StringBuilder();
244 final String anyXmlElementName = in.getLocalName();
245 sb.append('<').append(anyXmlElementName).append(" xmlns=\"").append(in.getNamespaceURI()).append("\">");
247 while (in.hasNext()) {
248 final int eventType = in.next();
250 if (eventType == XMLStreamConstants.START_ELEMENT) {
251 sb.append('<').append(in.getLocalName()).append('>');
252 } else if (eventType == XMLStreamConstants.END_ELEMENT) {
253 sb.append("</").append(in.getLocalName()).append('>');
255 if (in.getLocalName().equals(anyXmlElementName)) {
259 } else if (eventType == XMLStreamConstants.CHARACTERS) {
260 sb.append(XmlEscapers.xmlContentEscaper().escape(in.getText()));
264 return sb.toString();
267 private void read(final XMLStreamReader in, final AbstractNodeDataWithSchema parent, final String rootElement)
268 throws XMLStreamException, URISyntaxException, SAXException, IOException {
273 if (parent instanceof LeafNodeDataWithSchema || parent instanceof LeafListEntryNodeDataWithSchema) {
274 parent.setAttributes(getElementAttributes(in));
275 setValue(parent, in.getElementText().trim(), in.getNamespaceContext());
276 if (isNextEndDocument(in)) {
280 if (!isAtElement(in)) {
286 if (parent instanceof ListEntryNodeDataWithSchema || parent instanceof ContainerNodeDataWithSchema) {
287 parent.setAttributes(getElementAttributes(in));
290 if (parent instanceof LeafListNodeDataWithSchema || parent instanceof ListNodeDataWithSchema) {
291 String xmlElementName = in.getLocalName();
292 while (xmlElementName.equals(parent.getSchema().getQName().getLocalName())) {
293 read(in, newEntryNode(parent), rootElement);
294 if (in.getEventType() == XMLStreamConstants.END_DOCUMENT
295 || in.getEventType() == XMLStreamConstants.END_ELEMENT) {
298 xmlElementName = in.getLocalName();
304 if (parent instanceof AnyXmlNodeDataWithSchema) {
305 setValue(parent, readAnyXmlValue(in), in.getNamespaceContext());
306 if (isNextEndDocument(in)) {
310 if (!isAtElement(in)) {
317 if (parent instanceof YangModeledAnyXmlSchemaNode) {
318 parent.setAttributes(getElementAttributes(in));
321 switch (in.nextTag()) {
322 case XMLStreamConstants.START_ELEMENT:
323 // FIXME: why do we even need this tracker? either document it or remove it
324 final Set<Entry<String, String>> namesakes = new HashSet<>();
325 while (in.hasNext()) {
326 final String xmlElementName = in.getLocalName();
328 DataSchemaNode parentSchema = parent.getSchema();
330 final String parentSchemaName = parentSchema.getQName().getLocalName();
331 if (parentSchemaName.equals(xmlElementName)
332 && in.getEventType() == XMLStreamConstants.END_ELEMENT) {
333 if (isNextEndDocument(in)) {
337 if (!isAtElement(in)) {
343 if (in.isEndElement() && rootElement.equals(xmlElementName)) {
347 if (parentSchema instanceof YangModeledAnyXmlSchemaNode) {
348 parentSchema = ((YangModeledAnyXmlSchemaNode) parentSchema).getSchemaOfAnyXmlData();
351 final String xmlElementNamespace = in.getNamespaceURI();
352 if (!namesakes.add(new SimpleImmutableEntry<>(xmlElementNamespace, xmlElementName))) {
353 final Location loc = in.getLocation();
354 throw new IllegalStateException(String.format(
355 "Duplicate namespace \"%s\" element \"%s\" in XML input at: line %s column %s",
356 xmlElementNamespace, xmlElementName, loc.getLineNumber(), loc.getColumnNumber()));
359 final Deque<DataSchemaNode> childDataSchemaNodes =
360 ParserStreamUtils.findSchemaNodeByNameAndNamespace(parentSchema, xmlElementName,
361 new URI(xmlElementNamespace));
363 if (childDataSchemaNodes.isEmpty()) {
364 checkState(!strictParsing, "Schema for node with name %s and namespace %s does not exist at %s",
365 xmlElementName, xmlElementNamespace, parentSchema.getPath());
370 read(in, ((CompositeNodeDataWithSchema) parent).addChild(childDataSchemaNodes), rootElement);
373 case XMLStreamConstants.END_ELEMENT:
374 if (isNextEndDocument(in)) {
378 if (!isAtElement(in)) {
387 private static boolean isNextEndDocument(final XMLStreamReader in) throws XMLStreamException {
388 return in.next() == XMLStreamConstants.END_DOCUMENT;
391 private static boolean isAtElement(final XMLStreamReader in) {
392 return in.getEventType() == XMLStreamConstants.START_ELEMENT
393 || in.getEventType() == XMLStreamConstants.END_ELEMENT;
396 private static void skipUnknownNode(final XMLStreamReader in) throws XMLStreamException {
397 // in case when the unknown node and at least one of its descendant nodes have the same name
398 // we cannot properly reach the end just by checking if the current node is an end element and has the same name
399 // as the root unknown element. therefore we ignore the names completely and just track the level of nesting
400 int levelOfNesting = 0;
401 while (in.hasNext()) {
402 // in case there are text characters in an element, we cannot skip them by calling nextTag()
403 // therefore we skip them by calling next(), and then proceed to next element
405 if (!isAtElement(in)) {
408 if (in.isStartElement()) {
412 if (in.isEndElement()) {
413 if (levelOfNesting == 0) {
424 private void setValue(final AbstractNodeDataWithSchema parent, final String value, final NamespaceContext nsContext)
425 throws SAXException, IOException {
426 checkArgument(parent instanceof SimpleNodeDataWithSchema, "Node %s is not a simple type",
427 parent.getSchema().getQName());
428 final SimpleNodeDataWithSchema parentSimpleNode = (SimpleNodeDataWithSchema) parent;
429 checkArgument(parentSimpleNode.getValue() == null, "Node '%s' has already set its value to '%s'",
430 parentSimpleNode.getSchema().getQName(), parentSimpleNode.getValue());
432 parentSimpleNode.setValue(translateValueByType(value, parentSimpleNode.getSchema(), nsContext));
435 private Object translateValueByType(final String value, final DataSchemaNode node,
436 final NamespaceContext namespaceCtx) throws IOException, SAXException {
437 if (node instanceof AnyXmlSchemaNode) {
439 * FIXME: Figure out some YANG extension dispatch, which will
440 * reuse JSON parsing or XML parsing - anyxml is not well-defined in
443 final Document doc = UntrustedXML.newDocumentBuilder().parse(new InputSource(new StringReader(value)));
446 return new DOMSource(doc.getDocumentElement());
449 checkArgument(node instanceof TypedDataSchemaNode);
450 return codecs.codecFor((TypedDataSchemaNode) node).parseValue(namespaceCtx, value);
453 private static AbstractNodeDataWithSchema newEntryNode(final AbstractNodeDataWithSchema parent) {
454 final AbstractNodeDataWithSchema newChild;
455 if (parent instanceof ListNodeDataWithSchema) {
456 newChild = new ListEntryNodeDataWithSchema(parent.getSchema());
458 newChild = new LeafListEntryNodeDataWithSchema(parent.getSchema());
460 ((CompositeNodeDataWithSchema) parent).addChild(newChild);
465 public void close() throws IOException {
471 public void flush() throws IOException {