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.stream.Location;
32 import javax.xml.stream.XMLStreamConstants;
33 import javax.xml.stream.XMLStreamException;
34 import javax.xml.stream.XMLStreamReader;
35 import javax.xml.stream.util.StreamReaderDelegate;
36 import javax.xml.transform.TransformerException;
37 import javax.xml.transform.TransformerFactory;
38 import javax.xml.transform.TransformerFactoryConfigurationError;
39 import javax.xml.transform.dom.DOMResult;
40 import javax.xml.transform.dom.DOMSource;
41 import javax.xml.transform.stax.StAXSource;
42 import org.opendaylight.yangtools.odlext.model.api.YangModeledAnyXmlSchemaNode;
43 import org.opendaylight.yangtools.yang.common.QName;
44 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
45 import org.opendaylight.yangtools.yang.data.util.AbstractNodeDataWithSchema;
46 import org.opendaylight.yangtools.yang.data.util.AnyXmlNodeDataWithSchema;
47 import org.opendaylight.yangtools.yang.data.util.CompositeNodeDataWithSchema;
48 import org.opendaylight.yangtools.yang.data.util.ContainerNodeDataWithSchema;
49 import org.opendaylight.yangtools.yang.data.util.LeafListEntryNodeDataWithSchema;
50 import org.opendaylight.yangtools.yang.data.util.LeafListNodeDataWithSchema;
51 import org.opendaylight.yangtools.yang.data.util.LeafNodeDataWithSchema;
52 import org.opendaylight.yangtools.yang.data.util.ListEntryNodeDataWithSchema;
53 import org.opendaylight.yangtools.yang.data.util.ListNodeDataWithSchema;
54 import org.opendaylight.yangtools.yang.data.util.OperationAsContainer;
55 import org.opendaylight.yangtools.yang.data.util.ParserStreamUtils;
56 import org.opendaylight.yangtools.yang.data.util.SimpleNodeDataWithSchema;
57 import org.opendaylight.yangtools.yang.data.util.YangModeledAnyXmlNodeDataWithSchema;
58 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
65 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
66 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
70 import org.w3c.dom.Document;
71 import org.xml.sax.SAXException;
74 * This class provides functionality for parsing an XML source containing YANG-modeled data. It disallows multiple
75 * instances of the same element except for leaf-list and list entries. It also expects that the YANG-modeled data in
76 * the XML source are wrapped in a root element.
80 public final class XmlParserStream implements Closeable, Flushable {
81 private static final Logger LOG = LoggerFactory.getLogger(XmlParserStream.class);
82 private static final String XML_STANDARD_VERSION = "1.0";
83 private static final String COM_SUN_TRANSFORMER =
84 "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
86 private static final TransformerFactory TRANSFORMER_FACTORY;
89 TransformerFactory fa = TransformerFactory.newInstance();
90 if (!fa.getFeature(StAXSource.FEATURE)) {
91 LOG.warn("Platform-default TransformerFactory {} does not support StAXSource, attempting fallback to {}",
92 fa, COM_SUN_TRANSFORMER);
93 fa = TransformerFactory.newInstance(COM_SUN_TRANSFORMER, null);
94 if (!fa.getFeature(StAXSource.FEATURE)) {
95 throw new TransformerFactoryConfigurationError("No TransformerFactory supporting StAXResult found.");
99 TRANSFORMER_FACTORY = fa;
102 private final NormalizedNodeStreamWriter writer;
103 private final XmlCodecFactory codecs;
104 private final DataSchemaNode parentNode;
105 private final boolean strictParsing;
107 private XmlParserStream(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
108 final DataSchemaNode parentNode, final boolean strictParsing) {
109 this.writer = requireNonNull(writer);
110 this.codecs = requireNonNull(codecs);
111 this.parentNode = parentNode;
112 this.strictParsing = strictParsing;
116 * Construct a new {@link XmlParserStream} with strict parsing mode switched on.
118 * @param writer Output writer
119 * @param codecs Shared codecs
120 * @param parentNode Parent root node
121 * @return A new stream instance
123 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
124 final SchemaNode parentNode) {
125 return create(writer, codecs, parentNode, true);
129 * Construct a new {@link XmlParserStream}.
131 * @param writer Output writer
132 * @param codecs Shared codecs
133 * @param parentNode Parent root node
134 * @param strictParsing parsing mode
135 * if set to true, the parser will throw an exception if it encounters unknown child nodes
136 * (nodes, that are not defined in the provided SchemaContext) in containers and lists
137 * if set to false, the parser will skip unknown child nodes
138 * @return A new stream instance
140 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
141 final SchemaNode parentNode, final boolean strictParsing) {
142 final DataSchemaNode parent;
143 if (parentNode instanceof DataSchemaNode) {
144 parent = (DataSchemaNode) parentNode;
145 } else if (parentNode instanceof OperationDefinition) {
146 parent = OperationAsContainer.of((OperationDefinition) parentNode);
148 throw new IllegalArgumentException("Illegal parent node " + parentNode);
150 return new XmlParserStream(writer, codecs, parent, strictParsing);
154 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
155 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
156 * maintain a {@link XmlCodecFactory} to match the current {@link SchemaContext}.
158 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
159 final SchemaNode parentNode) {
160 return create(writer, schemaContext, parentNode, true);
164 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
165 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
166 * maintain a {@link XmlCodecFactory} to match the current {@link SchemaContext}.
168 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
169 final SchemaNode parentNode, final boolean strictParsing) {
170 return create(writer, XmlCodecFactory.create(schemaContext), parentNode, strictParsing);
174 * This method parses the XML source and emits node events into a NormalizedNodeStreamWriter based on the
175 * YANG-modeled data contained in the XML source.
178 * StAX reader which is to used to walk through the XML source
180 * instance of XmlParserStream
181 * @throws XMLStreamException
182 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
183 * @throws URISyntaxException
184 * if the namespace URI of an XML element contains a syntax error
185 * @throws IOException
186 * if an error occurs while parsing the value of an anyxml node
187 * @throws SAXException
188 * if an error occurs while parsing the value of an anyxml node
190 public XmlParserStream parse(final XMLStreamReader reader) throws XMLStreamException, URISyntaxException,
191 IOException, SAXException {
192 if (reader.hasNext()) {
194 final AbstractNodeDataWithSchema nodeDataWithSchema;
195 if (parentNode instanceof ContainerSchemaNode) {
196 nodeDataWithSchema = new ContainerNodeDataWithSchema(parentNode);
197 } else if (parentNode instanceof ListSchemaNode) {
198 nodeDataWithSchema = new ListNodeDataWithSchema(parentNode);
199 } else if (parentNode instanceof YangModeledAnyXmlSchemaNode) {
200 nodeDataWithSchema = new YangModeledAnyXmlNodeDataWithSchema((YangModeledAnyXmlSchemaNode) parentNode);
201 } else if (parentNode instanceof AnyXmlSchemaNode) {
202 nodeDataWithSchema = new AnyXmlNodeDataWithSchema(parentNode);
203 } else if (parentNode instanceof LeafSchemaNode) {
204 nodeDataWithSchema = new LeafNodeDataWithSchema(parentNode);
205 } else if (parentNode instanceof LeafListSchemaNode) {
206 nodeDataWithSchema = new LeafListNodeDataWithSchema(parentNode);
208 throw new IllegalStateException("Unsupported schema node type " + parentNode.getClass() + ".");
211 read(reader, nodeDataWithSchema, reader.getLocalName());
212 nodeDataWithSchema.write(writer);
219 * This method traverses a {@link DOMSource} and emits node events into a NormalizedNodeStreamWriter based on the
220 * YANG-modeled data contained in the source.
223 * {@link DOMSource} to be traversed
225 * instance of XmlParserStream
226 * @throws XMLStreamException
227 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
228 * @throws URISyntaxException
229 * if the namespace URI of an XML element contains a syntax error
230 * @throws IOException
231 * if an error occurs while parsing the value of an anyxml node
232 * @throws SAXException
233 * if an error occurs while parsing the value of an anyxml node
236 public XmlParserStream traverse(final DOMSource src) throws XMLStreamException, URISyntaxException, IOException,
238 return parse(new DOMSourceXMLStreamReader(src));
241 private static ImmutableMap<QName, String> getElementAttributes(final XMLStreamReader in) {
242 checkState(in.isStartElement(), "Attributes can be extracted only from START_ELEMENT.");
243 final Map<QName, String> attributes = new LinkedHashMap<>();
245 for (int attrIndex = 0; attrIndex < in.getAttributeCount(); attrIndex++) {
246 String attributeNS = in.getAttributeNamespace(attrIndex);
248 if (attributeNS == null) {
252 // Skip namespace definitions
253 if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attributeNS)) {
257 final QName qName = QName.create(URI.create(attributeNS), in.getAttributeLocalName(attrIndex));
258 attributes.put(qName, in.getAttributeValue(attrIndex));
261 return ImmutableMap.copyOf(attributes);
264 private static Document readAnyXmlValue(final XMLStreamReader in) throws XMLStreamException {
265 // Underlying reader might return null when asked for version, however when such reader is plugged into
266 // Stax -> DOM transformer, it fails with NPE due to null version. Use default xml version in such case.
267 final XMLStreamReader inWrapper;
268 if (in.getVersion() == null) {
269 inWrapper = new StreamReaderDelegate(in) {
271 public String getVersion() {
272 final String ver = super.getVersion();
273 return ver != null ? ver : XML_STANDARD_VERSION;
280 final DOMResult result = new DOMResult();
282 TRANSFORMER_FACTORY.newTransformer().transform(new StAXSource(inWrapper), result);
283 } catch (final TransformerException e) {
284 throw new XMLStreamException("Unable to read anyxml value", e);
286 return (Document) result.getNode();
289 private void read(final XMLStreamReader in, final AbstractNodeDataWithSchema parent, final String rootElement)
290 throws XMLStreamException, URISyntaxException {
295 if (parent instanceof LeafNodeDataWithSchema || parent instanceof LeafListEntryNodeDataWithSchema) {
296 parent.setAttributes(getElementAttributes(in));
297 setValue(parent, in.getElementText().trim(), in.getNamespaceContext());
298 if (isNextEndDocument(in)) {
302 if (!isAtElement(in)) {
308 if (parent instanceof ListEntryNodeDataWithSchema || parent instanceof ContainerNodeDataWithSchema) {
309 parent.setAttributes(getElementAttributes(in));
312 if (parent instanceof LeafListNodeDataWithSchema || parent instanceof ListNodeDataWithSchema) {
313 String xmlElementName = in.getLocalName();
314 while (xmlElementName.equals(parent.getSchema().getQName().getLocalName())) {
315 read(in, newEntryNode(parent), rootElement);
316 if (in.getEventType() == XMLStreamConstants.END_DOCUMENT
317 || in.getEventType() == XMLStreamConstants.END_ELEMENT) {
320 xmlElementName = in.getLocalName();
326 if (parent instanceof AnyXmlNodeDataWithSchema) {
327 setValue(parent, readAnyXmlValue(in), in.getNamespaceContext());
328 if (isNextEndDocument(in)) {
332 if (!isAtElement(in)) {
339 if (parent instanceof YangModeledAnyXmlSchemaNode) {
340 parent.setAttributes(getElementAttributes(in));
343 switch (in.nextTag()) {
344 case XMLStreamConstants.START_ELEMENT:
345 // FIXME: why do we even need this tracker? either document it or remove it
346 final Set<Entry<String, String>> namesakes = new HashSet<>();
347 while (in.hasNext()) {
348 final String xmlElementName = in.getLocalName();
350 DataSchemaNode parentSchema = parent.getSchema();
352 final String parentSchemaName = parentSchema.getQName().getLocalName();
353 if (parentSchemaName.equals(xmlElementName)
354 && in.getEventType() == XMLStreamConstants.END_ELEMENT) {
355 if (isNextEndDocument(in)) {
359 if (!isAtElement(in)) {
365 if (in.isEndElement() && rootElement.equals(xmlElementName)) {
369 if (parentSchema instanceof YangModeledAnyXmlSchemaNode) {
370 parentSchema = ((YangModeledAnyXmlSchemaNode) parentSchema).getSchemaOfAnyXmlData();
373 final String xmlElementNamespace = in.getNamespaceURI();
374 if (!namesakes.add(new SimpleImmutableEntry<>(xmlElementNamespace, xmlElementName))) {
375 final Location loc = in.getLocation();
376 throw new IllegalStateException(String.format(
377 "Duplicate namespace \"%s\" element \"%s\" in XML input at: line %s column %s",
378 xmlElementNamespace, xmlElementName, loc.getLineNumber(), loc.getColumnNumber()));
381 final Deque<DataSchemaNode> childDataSchemaNodes =
382 ParserStreamUtils.findSchemaNodeByNameAndNamespace(parentSchema, xmlElementName,
383 new URI(xmlElementNamespace));
385 if (childDataSchemaNodes.isEmpty()) {
386 checkState(!strictParsing, "Schema for node with name %s and namespace %s does not exist at %s",
387 xmlElementName, xmlElementNamespace, parentSchema.getPath());
392 read(in, ((CompositeNodeDataWithSchema) parent).addChild(childDataSchemaNodes), rootElement);
395 case XMLStreamConstants.END_ELEMENT:
396 if (isNextEndDocument(in)) {
400 if (!isAtElement(in)) {
409 private static boolean isNextEndDocument(final XMLStreamReader in) throws XMLStreamException {
410 return !in.hasNext() || in.next() == XMLStreamConstants.END_DOCUMENT;
413 private static boolean isAtElement(final XMLStreamReader in) {
414 return in.getEventType() == XMLStreamConstants.START_ELEMENT
415 || in.getEventType() == XMLStreamConstants.END_ELEMENT;
418 private static void skipUnknownNode(final XMLStreamReader in) throws XMLStreamException {
419 // in case when the unknown node and at least one of its descendant nodes have the same name
420 // we cannot properly reach the end just by checking if the current node is an end element and has the same name
421 // as the root unknown element. therefore we ignore the names completely and just track the level of nesting
422 int levelOfNesting = 0;
423 while (in.hasNext()) {
424 // in case there are text characters in an element, we cannot skip them by calling nextTag()
425 // therefore we skip them by calling next(), and then proceed to next element
427 if (!isAtElement(in)) {
430 if (in.isStartElement()) {
434 if (in.isEndElement()) {
435 if (levelOfNesting == 0) {
447 private void setValue(final AbstractNodeDataWithSchema parent, final Object value,
448 final NamespaceContext nsContext) {
449 checkArgument(parent instanceof SimpleNodeDataWithSchema, "Node %s is not a simple type",
450 parent.getSchema().getQName());
451 final SimpleNodeDataWithSchema parentSimpleNode = (SimpleNodeDataWithSchema) parent;
452 checkArgument(parentSimpleNode.getValue() == null, "Node '%s' has already set its value to '%s'",
453 parentSimpleNode.getSchema().getQName(), parentSimpleNode.getValue());
455 parentSimpleNode.setValue(translateValueByType(value, parentSimpleNode.getSchema(), nsContext));
458 private Object translateValueByType(final Object value, final DataSchemaNode node,
459 final NamespaceContext namespaceCtx) {
460 if (node instanceof AnyXmlSchemaNode) {
462 checkArgument(value instanceof Document);
464 * FIXME: Figure out some YANG extension dispatch, which will
465 * reuse JSON parsing or XML parsing - anyxml is not well-defined in
468 return new DOMSource(((Document) value).getDocumentElement());
471 checkArgument(node instanceof TypedDataSchemaNode);
472 checkArgument(value instanceof String);
473 return codecs.codecFor((TypedDataSchemaNode) node).parseValue(namespaceCtx, (String) value);
476 private static AbstractNodeDataWithSchema newEntryNode(final AbstractNodeDataWithSchema parent) {
477 final AbstractNodeDataWithSchema newChild;
478 if (parent instanceof ListNodeDataWithSchema) {
479 newChild = new ListEntryNodeDataWithSchema(parent.getSchema());
481 newChild = new LeafListEntryNodeDataWithSchema(parent.getSchema());
483 ((CompositeNodeDataWithSchema) parent).addChild(newChild);
488 public void close() throws IOException {
494 public void flush() throws IOException {