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 java.io.Closeable;
17 import java.io.Flushable;
18 import java.io.IOException;
20 import java.net.URISyntaxException;
21 import java.util.AbstractMap.SimpleImmutableEntry;
22 import java.util.Deque;
23 import java.util.HashSet;
24 import java.util.LinkedHashMap;
26 import java.util.Map.Entry;
28 import javax.annotation.concurrent.NotThreadSafe;
29 import javax.xml.XMLConstants;
30 import javax.xml.namespace.NamespaceContext;
31 import javax.xml.parsers.ParserConfigurationException;
32 import javax.xml.stream.Location;
33 import javax.xml.stream.XMLStreamConstants;
34 import javax.xml.stream.XMLStreamException;
35 import javax.xml.stream.XMLStreamReader;
36 import javax.xml.stream.util.StreamReaderDelegate;
37 import javax.xml.transform.TransformerException;
38 import javax.xml.transform.TransformerFactory;
39 import javax.xml.transform.TransformerFactoryConfigurationError;
40 import javax.xml.transform.dom.DOMResult;
41 import javax.xml.transform.dom.DOMSource;
42 import javax.xml.transform.stax.StAXSource;
43 import org.opendaylight.yangtools.odlext.model.api.YangModeledAnyXmlSchemaNode;
44 import org.opendaylight.yangtools.yang.common.QName;
45 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
46 import org.opendaylight.yangtools.yang.data.util.AbstractNodeDataWithSchema;
47 import org.opendaylight.yangtools.yang.data.util.AnyXmlNodeDataWithSchema;
48 import org.opendaylight.yangtools.yang.data.util.CompositeNodeDataWithSchema;
49 import org.opendaylight.yangtools.yang.data.util.ContainerNodeDataWithSchema;
50 import org.opendaylight.yangtools.yang.data.util.LeafListEntryNodeDataWithSchema;
51 import org.opendaylight.yangtools.yang.data.util.LeafListNodeDataWithSchema;
52 import org.opendaylight.yangtools.yang.data.util.LeafNodeDataWithSchema;
53 import org.opendaylight.yangtools.yang.data.util.ListEntryNodeDataWithSchema;
54 import org.opendaylight.yangtools.yang.data.util.ListNodeDataWithSchema;
55 import org.opendaylight.yangtools.yang.data.util.OperationAsContainer;
56 import org.opendaylight.yangtools.yang.data.util.ParserStreamUtils;
57 import org.opendaylight.yangtools.yang.data.util.SimpleNodeDataWithSchema;
58 import org.opendaylight.yangtools.yang.data.util.YangModeledAnyXmlNodeDataWithSchema;
59 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
66 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
67 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
71 import org.w3c.dom.Document;
72 import org.xml.sax.SAXException;
75 * This class provides functionality for parsing an XML source containing YANG-modeled data. It disallows multiple
76 * instances of the same element except for leaf-list and list entries. It also expects that the YANG-modeled data in
77 * the XML source are wrapped in a root element.
81 public final class XmlParserStream implements Closeable, Flushable {
82 private static final Logger LOG = LoggerFactory.getLogger(XmlParserStream.class);
83 private static final String XML_STANDARD_VERSION = "1.0";
84 private static final String COM_SUN_TRANSFORMER =
85 "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
87 private static final TransformerFactory TRANSFORMER_FACTORY;
90 TransformerFactory fa = TransformerFactory.newInstance();
91 if (!fa.getFeature(StAXSource.FEATURE)) {
92 LOG.warn("Platform-default TransformerFactory {} does not support StAXSource, attempting fallback to {}",
93 fa, COM_SUN_TRANSFORMER);
94 fa = TransformerFactory.newInstance(COM_SUN_TRANSFORMER, null);
95 if (!fa.getFeature(StAXSource.FEATURE)) {
96 throw new TransformerFactoryConfigurationError("No TransformerFactory supporting StAXResult found.");
100 TRANSFORMER_FACTORY = fa;
103 private final NormalizedNodeStreamWriter writer;
104 private final XmlCodecFactory codecs;
105 private final DataSchemaNode parentNode;
106 private final boolean strictParsing;
108 private XmlParserStream(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
109 final DataSchemaNode parentNode, final boolean strictParsing) {
110 this.writer = requireNonNull(writer);
111 this.codecs = requireNonNull(codecs);
112 this.parentNode = parentNode;
113 this.strictParsing = strictParsing;
117 * Construct a new {@link XmlParserStream} with strict parsing mode switched on.
119 * @param writer Output writer
120 * @param codecs Shared codecs
121 * @param parentNode Parent root node
122 * @return A new stream instance
124 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
125 final SchemaNode parentNode) {
126 return create(writer, codecs, parentNode, true);
130 * Construct a new {@link XmlParserStream}.
132 * @param writer Output writer
133 * @param codecs Shared codecs
134 * @param parentNode Parent root node
135 * @param strictParsing parsing mode
136 * if set to true, the parser will throw an exception if it encounters unknown child nodes
137 * (nodes, that are not defined in the provided SchemaContext) in containers and lists
138 * if set to false, the parser will skip unknown child nodes
139 * @return A new stream instance
141 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
142 final SchemaNode parentNode, final boolean strictParsing) {
143 final DataSchemaNode parent;
144 if (parentNode instanceof DataSchemaNode) {
145 parent = (DataSchemaNode) parentNode;
146 } else if (parentNode instanceof OperationDefinition) {
147 parent = OperationAsContainer.of((OperationDefinition) parentNode);
149 throw new IllegalArgumentException("Illegal parent node " + parentNode);
151 return new XmlParserStream(writer, codecs, parent, strictParsing);
155 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
156 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
157 * maintain a {@link XmlCodecFactory} to match the current {@link SchemaContext}.
159 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
160 final SchemaNode parentNode) {
161 return create(writer, schemaContext, parentNode, true);
165 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
166 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
167 * maintain a {@link XmlCodecFactory} to match the current {@link SchemaContext}.
169 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
170 final SchemaNode parentNode, final boolean strictParsing) {
171 return create(writer, XmlCodecFactory.create(schemaContext), parentNode, strictParsing);
175 * This method parses the XML source and emits node events into a NormalizedNodeStreamWriter based on the
176 * YANG-modeled data contained in the XML source.
179 * StAX reader which is to used to walk through the XML source
181 * instance of XmlParserStream
182 * @throws XMLStreamException
183 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
184 * @throws URISyntaxException
185 * if the namespace URI of an XML element contains a syntax error
186 * @throws IOException
187 * if an error occurs while parsing the value of an anyxml node
188 * @throws ParserConfigurationException
189 * if an error occurs while parsing the value of an anyxml node
190 * @throws SAXException
191 * if an error occurs while parsing the value of an anyxml node
193 // FIXME: 3.0.0 remove ParserConfigurationException
194 public XmlParserStream parse(final XMLStreamReader reader) throws XMLStreamException, URISyntaxException,
195 IOException, ParserConfigurationException, SAXException {
196 if (reader.hasNext()) {
198 final AbstractNodeDataWithSchema nodeDataWithSchema;
199 if (parentNode instanceof ContainerSchemaNode) {
200 nodeDataWithSchema = new ContainerNodeDataWithSchema(parentNode);
201 } else if (parentNode instanceof ListSchemaNode) {
202 nodeDataWithSchema = new ListNodeDataWithSchema(parentNode);
203 } else if (parentNode instanceof YangModeledAnyXmlSchemaNode) {
204 nodeDataWithSchema = new YangModeledAnyXmlNodeDataWithSchema((YangModeledAnyXmlSchemaNode) parentNode);
205 } else if (parentNode instanceof AnyXmlSchemaNode) {
206 nodeDataWithSchema = new AnyXmlNodeDataWithSchema(parentNode);
207 } else if (parentNode instanceof LeafSchemaNode) {
208 nodeDataWithSchema = new LeafNodeDataWithSchema(parentNode);
209 } else if (parentNode instanceof LeafListSchemaNode) {
210 nodeDataWithSchema = new LeafListNodeDataWithSchema(parentNode);
212 throw new IllegalStateException("Unsupported schema node type " + parentNode.getClass() + ".");
215 read(reader, nodeDataWithSchema, reader.getLocalName());
216 nodeDataWithSchema.write(writer);
223 * This method traverses a {@link DOMSource} and emits node events into a NormalizedNodeStreamWriter based on the
224 * YANG-modeled data contained in the source.
227 * {@link DOMSource} to be traversed
229 * instance of XmlParserStream
230 * @throws XMLStreamException
231 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
232 * @throws URISyntaxException
233 * if the namespace URI of an XML element contains a syntax error
234 * @throws IOException
235 * if an error occurs while parsing the value of an anyxml node
236 * @throws ParserConfigurationException
237 * if an error occurs while parsing the value of an anyxml node
238 * @throws SAXException
239 * if an error occurs while parsing the value of an anyxml node
242 // FIXME: 3.0.0 remove ParserConfigurationException
243 public XmlParserStream traverse(final DOMSource src) throws XMLStreamException, URISyntaxException,
244 IOException, ParserConfigurationException, SAXException {
245 return parse(new DOMSourceXMLStreamReader(src));
248 private static ImmutableMap<QName, String> getElementAttributes(final XMLStreamReader in) {
249 checkState(in.isStartElement(), "Attributes can be extracted only from START_ELEMENT.");
250 final Map<QName, String> attributes = new LinkedHashMap<>();
252 for (int attrIndex = 0; attrIndex < in.getAttributeCount(); attrIndex++) {
253 String attributeNS = in.getAttributeNamespace(attrIndex);
255 if (attributeNS == null) {
259 // Skip namespace definitions
260 if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attributeNS)) {
264 final QName qName = QName.create(URI.create(attributeNS), in.getAttributeLocalName(attrIndex));
265 attributes.put(qName, in.getAttributeValue(attrIndex));
268 return ImmutableMap.copyOf(attributes);
271 private static Document readAnyXmlValue(final XMLStreamReader in) throws XMLStreamException {
272 // Underlying reader might return null when asked for version, however when such reader is plugged into
273 // Stax -> DOM transformer, it fails with NPE due to null version. Use default xml version in such case.
274 final XMLStreamReader inWrapper;
275 if (in.getVersion() == null) {
276 inWrapper = new StreamReaderDelegate(in) {
278 public String getVersion() {
279 final String ver = super.getVersion();
280 return ver != null ? ver : XML_STANDARD_VERSION;
287 final DOMResult result = new DOMResult();
289 TRANSFORMER_FACTORY.newTransformer().transform(new StAXSource(inWrapper), result);
290 } catch (final TransformerException e) {
291 throw new XMLStreamException("Unable to read anyxml value", e);
293 return (Document) result.getNode();
296 private void read(final XMLStreamReader in, final AbstractNodeDataWithSchema parent, final String rootElement)
297 throws XMLStreamException, URISyntaxException {
302 if (parent instanceof LeafNodeDataWithSchema || parent instanceof LeafListEntryNodeDataWithSchema) {
303 parent.setAttributes(getElementAttributes(in));
304 setValue(parent, in.getElementText().trim(), in.getNamespaceContext());
305 if (isNextEndDocument(in)) {
309 if (!isAtElement(in)) {
315 if (parent instanceof ListEntryNodeDataWithSchema || parent instanceof ContainerNodeDataWithSchema) {
316 parent.setAttributes(getElementAttributes(in));
319 if (parent instanceof LeafListNodeDataWithSchema || parent instanceof ListNodeDataWithSchema) {
320 String xmlElementName = in.getLocalName();
321 while (xmlElementName.equals(parent.getSchema().getQName().getLocalName())) {
322 read(in, newEntryNode(parent), rootElement);
323 if (in.getEventType() == XMLStreamConstants.END_DOCUMENT
324 || in.getEventType() == XMLStreamConstants.END_ELEMENT) {
327 xmlElementName = in.getLocalName();
333 if (parent instanceof AnyXmlNodeDataWithSchema) {
334 setValue(parent, readAnyXmlValue(in), in.getNamespaceContext());
335 if (isNextEndDocument(in)) {
339 if (!isAtElement(in)) {
346 if (parent instanceof YangModeledAnyXmlSchemaNode) {
347 parent.setAttributes(getElementAttributes(in));
350 switch (in.nextTag()) {
351 case XMLStreamConstants.START_ELEMENT:
352 // FIXME: why do we even need this tracker? either document it or remove it
353 final Set<Entry<String, String>> namesakes = new HashSet<>();
354 while (in.hasNext()) {
355 final String xmlElementName = in.getLocalName();
357 DataSchemaNode parentSchema = parent.getSchema();
359 final String parentSchemaName = parentSchema.getQName().getLocalName();
360 if (parentSchemaName.equals(xmlElementName)
361 && in.getEventType() == XMLStreamConstants.END_ELEMENT) {
362 if (isNextEndDocument(in)) {
366 if (!isAtElement(in)) {
372 if (in.isEndElement() && rootElement.equals(xmlElementName)) {
376 if (parentSchema instanceof YangModeledAnyXmlSchemaNode) {
377 parentSchema = ((YangModeledAnyXmlSchemaNode) parentSchema).getSchemaOfAnyXmlData();
380 final String xmlElementNamespace = in.getNamespaceURI();
381 if (!namesakes.add(new SimpleImmutableEntry<>(xmlElementNamespace, xmlElementName))) {
382 final Location loc = in.getLocation();
383 throw new IllegalStateException(String.format(
384 "Duplicate namespace \"%s\" element \"%s\" in XML input at: line %s column %s",
385 xmlElementNamespace, xmlElementName, loc.getLineNumber(), loc.getColumnNumber()));
388 final Deque<DataSchemaNode> childDataSchemaNodes =
389 ParserStreamUtils.findSchemaNodeByNameAndNamespace(parentSchema, xmlElementName,
390 new URI(xmlElementNamespace));
392 if (childDataSchemaNodes.isEmpty()) {
393 checkState(!strictParsing, "Schema for node with name %s and namespace %s does not exist at %s",
394 xmlElementName, xmlElementNamespace, parentSchema.getPath());
399 read(in, ((CompositeNodeDataWithSchema) parent).addChild(childDataSchemaNodes), rootElement);
402 case XMLStreamConstants.END_ELEMENT:
403 if (isNextEndDocument(in)) {
407 if (!isAtElement(in)) {
416 private static boolean isNextEndDocument(final XMLStreamReader in) throws XMLStreamException {
417 return !in.hasNext() || in.next() == XMLStreamConstants.END_DOCUMENT;
420 private static boolean isAtElement(final XMLStreamReader in) {
421 return in.getEventType() == XMLStreamConstants.START_ELEMENT
422 || in.getEventType() == XMLStreamConstants.END_ELEMENT;
425 private static void skipUnknownNode(final XMLStreamReader in) throws XMLStreamException {
426 // in case when the unknown node and at least one of its descendant nodes have the same name
427 // we cannot properly reach the end just by checking if the current node is an end element and has the same name
428 // as the root unknown element. therefore we ignore the names completely and just track the level of nesting
429 int levelOfNesting = 0;
430 while (in.hasNext()) {
431 // in case there are text characters in an element, we cannot skip them by calling nextTag()
432 // therefore we skip them by calling next(), and then proceed to next element
434 if (!isAtElement(in)) {
437 if (in.isStartElement()) {
441 if (in.isEndElement()) {
442 if (levelOfNesting == 0) {
454 private void setValue(final AbstractNodeDataWithSchema parent, final Object value,
455 final NamespaceContext nsContext) {
456 checkArgument(parent instanceof SimpleNodeDataWithSchema, "Node %s is not a simple type",
457 parent.getSchema().getQName());
458 final SimpleNodeDataWithSchema parentSimpleNode = (SimpleNodeDataWithSchema) parent;
459 checkArgument(parentSimpleNode.getValue() == null, "Node '%s' has already set its value to '%s'",
460 parentSimpleNode.getSchema().getQName(), parentSimpleNode.getValue());
462 parentSimpleNode.setValue(translateValueByType(value, parentSimpleNode.getSchema(), nsContext));
465 private Object translateValueByType(final Object value, final DataSchemaNode node,
466 final NamespaceContext namespaceCtx) {
467 if (node instanceof AnyXmlSchemaNode) {
469 checkArgument(value instanceof Document);
471 * FIXME: Figure out some YANG extension dispatch, which will
472 * reuse JSON parsing or XML parsing - anyxml is not well-defined in
475 return new DOMSource(((Document) value).getDocumentElement());
478 checkArgument(node instanceof TypedDataSchemaNode);
479 checkArgument(value instanceof String);
480 return codecs.codecFor((TypedDataSchemaNode) node).parseValue(namespaceCtx, (String) value);
483 private static AbstractNodeDataWithSchema newEntryNode(final AbstractNodeDataWithSchema parent) {
484 final AbstractNodeDataWithSchema newChild;
485 if (parent instanceof ListNodeDataWithSchema) {
486 newChild = new ListEntryNodeDataWithSchema(parent.getSchema());
488 newChild = new LeafListEntryNodeDataWithSchema(parent.getSchema());
490 ((CompositeNodeDataWithSchema) parent).addChild(newChild);
495 public void close() throws IOException {
501 public void flush() throws IOException {