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 com.google.common.base.Verify.verify;
13 import static java.util.Objects.requireNonNull;
15 import com.google.common.annotations.Beta;
16 import com.google.common.base.Strings;
17 import com.google.common.collect.ImmutableMap;
18 import java.io.Closeable;
19 import java.io.Flushable;
20 import java.io.IOException;
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.xml.XMLConstants;
31 import javax.xml.namespace.NamespaceContext;
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.rfc7952.data.api.NormalizedMetadata;
45 import org.opendaylight.yangtools.yang.common.QName;
46 import org.opendaylight.yangtools.yang.common.QNameModule;
47 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
48 import org.opendaylight.yangtools.yang.data.util.AbstractNodeDataWithSchema;
49 import org.opendaylight.yangtools.yang.data.util.AnyXmlNodeDataWithSchema;
50 import org.opendaylight.yangtools.yang.data.util.CompositeNodeDataWithSchema;
51 import org.opendaylight.yangtools.yang.data.util.ContainerNodeDataWithSchema;
52 import org.opendaylight.yangtools.yang.data.util.LeafListEntryNodeDataWithSchema;
53 import org.opendaylight.yangtools.yang.data.util.LeafListNodeDataWithSchema;
54 import org.opendaylight.yangtools.yang.data.util.LeafNodeDataWithSchema;
55 import org.opendaylight.yangtools.yang.data.util.ListEntryNodeDataWithSchema;
56 import org.opendaylight.yangtools.yang.data.util.ListNodeDataWithSchema;
57 import org.opendaylight.yangtools.yang.data.util.OperationAsContainer;
58 import org.opendaylight.yangtools.yang.data.util.ParserStreamUtils;
59 import org.opendaylight.yangtools.yang.data.util.SimpleNodeDataWithSchema;
60 import org.opendaylight.yangtools.yang.data.util.YangModeledAnyXmlNodeDataWithSchema;
61 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
68 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
69 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
70 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
71 import org.slf4j.Logger;
72 import org.slf4j.LoggerFactory;
73 import org.w3c.dom.Document;
74 import org.xml.sax.SAXException;
77 * This class provides functionality for parsing an XML source containing YANG-modeled data. It disallows multiple
78 * instances of the same element except for leaf-list and list entries. It also expects that the YANG-modeled data in
79 * the XML source are wrapped in a root element. This class is NOT thread-safe.
82 public final class XmlParserStream implements Closeable, Flushable {
83 private static final Logger LOG = LoggerFactory.getLogger(XmlParserStream.class);
84 private static final String XML_STANDARD_VERSION = "1.0";
85 private static final String COM_SUN_TRANSFORMER =
86 "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
88 private static final TransformerFactory TRANSFORMER_FACTORY;
91 TransformerFactory fa = TransformerFactory.newInstance();
92 if (!fa.getFeature(StAXSource.FEATURE)) {
93 LOG.warn("Platform-default TransformerFactory {} does not support StAXSource, attempting fallback to {}",
94 fa, COM_SUN_TRANSFORMER);
95 fa = TransformerFactory.newInstance(COM_SUN_TRANSFORMER, null);
96 if (!fa.getFeature(StAXSource.FEATURE)) {
97 throw new TransformerFactoryConfigurationError("No TransformerFactory supporting StAXResult found.");
101 TRANSFORMER_FACTORY = fa;
104 private final NormalizedNodeStreamWriter writer;
105 private final XmlCodecFactory codecs;
106 private final DataSchemaNode parentNode;
107 private final boolean strictParsing;
109 private XmlParserStream(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
110 final DataSchemaNode parentNode, final boolean strictParsing) {
111 this.writer = requireNonNull(writer);
112 this.codecs = requireNonNull(codecs);
113 this.parentNode = parentNode;
114 this.strictParsing = strictParsing;
118 * Construct a new {@link XmlParserStream} with strict parsing mode switched on.
120 * @param writer Output writer
121 * @param codecs Shared codecs
122 * @param parentNode Parent root node
123 * @return A new stream instance
125 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
126 final SchemaNode parentNode) {
127 return create(writer, codecs, parentNode, true);
131 * Construct a new {@link XmlParserStream}.
133 * @param writer Output writer
134 * @param codecs Shared codecs
135 * @param parentNode Parent root node
136 * @param strictParsing parsing mode
137 * if set to true, the parser will throw an exception if it encounters unknown child nodes
138 * (nodes, that are not defined in the provided SchemaContext) in containers and lists
139 * if set to false, the parser will skip unknown child nodes
140 * @return A new stream instance
142 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
143 final SchemaNode parentNode, final boolean strictParsing) {
144 final DataSchemaNode parent;
145 if (parentNode instanceof DataSchemaNode) {
146 parent = (DataSchemaNode) parentNode;
147 } else if (parentNode instanceof OperationDefinition) {
148 parent = OperationAsContainer.of((OperationDefinition) parentNode);
150 throw new IllegalArgumentException("Illegal parent node " + parentNode);
152 return new XmlParserStream(writer, codecs, parent, strictParsing);
156 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
157 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
158 * maintain a {@link XmlCodecFactory} to match the current {@link SchemaContext}.
160 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
161 final SchemaNode parentNode) {
162 return create(writer, schemaContext, parentNode, true);
166 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
167 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
168 * maintain a {@link XmlCodecFactory} to match the current {@link SchemaContext}.
170 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
171 final SchemaNode parentNode, final boolean strictParsing) {
172 return create(writer, XmlCodecFactory.create(schemaContext), parentNode, strictParsing);
176 * This method parses the XML source and emits node events into a NormalizedNodeStreamWriter based on the
177 * YANG-modeled data contained in the XML source.
180 * StAX reader which is to used to walk through the XML source
182 * instance of XmlParserStream
183 * @throws XMLStreamException
184 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
185 * @throws URISyntaxException
186 * if the namespace URI of an XML element contains a syntax error
187 * @throws IOException
188 * if an error occurs while parsing the value of an anyxml node
189 * @throws SAXException
190 * if an error occurs while parsing the value of an anyxml node
192 public XmlParserStream parse(final XMLStreamReader reader) throws XMLStreamException, URISyntaxException,
193 IOException, SAXException {
194 if (reader.hasNext()) {
196 final AbstractNodeDataWithSchema<?> nodeDataWithSchema;
197 if (parentNode instanceof ContainerSchemaNode) {
198 nodeDataWithSchema = new ContainerNodeDataWithSchema((ContainerSchemaNode) parentNode);
199 } else if (parentNode instanceof ListSchemaNode) {
200 nodeDataWithSchema = new ListNodeDataWithSchema((ListSchemaNode) parentNode);
201 } else if (parentNode instanceof YangModeledAnyXmlSchemaNode) {
202 nodeDataWithSchema = new YangModeledAnyXmlNodeDataWithSchema((YangModeledAnyXmlSchemaNode) parentNode);
203 } else if (parentNode instanceof AnyXmlSchemaNode) {
204 nodeDataWithSchema = new AnyXmlNodeDataWithSchema((AnyXmlSchemaNode) parentNode);
205 } else if (parentNode instanceof LeafSchemaNode) {
206 nodeDataWithSchema = new LeafNodeDataWithSchema((LeafSchemaNode) parentNode);
207 } else if (parentNode instanceof LeafListSchemaNode) {
208 nodeDataWithSchema = new LeafListNodeDataWithSchema((LeafListSchemaNode) parentNode);
210 throw new IllegalStateException("Unsupported schema node type " + parentNode.getClass() + ".");
213 read(reader, nodeDataWithSchema, reader.getLocalName());
214 nodeDataWithSchema.write(writer);
221 * This method traverses a {@link DOMSource} and emits node events into a NormalizedNodeStreamWriter based on the
222 * YANG-modeled data contained in the source.
225 * {@link DOMSource} to be traversed
227 * instance of XmlParserStream
228 * @throws XMLStreamException
229 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
230 * @throws URISyntaxException
231 * if the namespace URI of an XML element contains a syntax error
232 * @throws IOException
233 * if an error occurs while parsing the value of an anyxml node
234 * @throws SAXException
235 * if an error occurs while parsing the value of an anyxml node
238 public XmlParserStream traverse(final DOMSource src) throws XMLStreamException, URISyntaxException, IOException,
240 return parse(new DOMSourceXMLStreamReader(src));
243 private static ImmutableMap<QName, String> getElementAttributes(final XMLStreamReader in) {
244 checkState(in.isStartElement(), "Attributes can be extracted only from START_ELEMENT.");
245 final Map<QName, String> attributes = new LinkedHashMap<>();
247 for (int attrIndex = 0; attrIndex < in.getAttributeCount(); attrIndex++) {
248 final String attributeNS = in.getAttributeNamespace(attrIndex);
250 // Skip namespace definitions
251 if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attributeNS)) {
255 final QNameModule namespace;
256 if (!Strings.isNullOrEmpty(attributeNS)) {
257 // FIXME: bind the namespace to a module, if available
258 namespace = QNameModule.create(URI.create(attributeNS));
260 namespace = NormalizedMetadata.LEGACY_ATTRIBUTE_NAMESPACE;
263 final QName qName = QName.create(namespace, in.getAttributeLocalName(attrIndex));
264 attributes.put(qName, in.getAttributeValue(attrIndex));
267 return ImmutableMap.copyOf(attributes);
270 private static Document readAnyXmlValue(final XMLStreamReader in) throws XMLStreamException {
271 // Underlying reader might return null when asked for version, however when such reader is plugged into
272 // Stax -> DOM transformer, it fails with NPE due to null version. Use default xml version in such case.
273 final XMLStreamReader inWrapper;
274 if (in.getVersion() == null) {
275 inWrapper = new StreamReaderDelegate(in) {
277 public String getVersion() {
278 final String ver = super.getVersion();
279 return ver != null ? ver : XML_STANDARD_VERSION;
286 final DOMResult result = new DOMResult();
288 TRANSFORMER_FACTORY.newTransformer().transform(new StAXSource(inWrapper), result);
289 } catch (final TransformerException e) {
290 throw new XMLStreamException("Unable to read anyxml value", e);
292 return (Document) result.getNode();
295 private void read(final XMLStreamReader in, final AbstractNodeDataWithSchema<?> parent, final String rootElement)
296 throws XMLStreamException, URISyntaxException {
301 if (parent instanceof LeafNodeDataWithSchema || parent instanceof LeafListEntryNodeDataWithSchema) {
302 parent.setAttributes(getElementAttributes(in));
303 setValue(parent, in.getElementText().trim(), in.getNamespaceContext());
304 if (isNextEndDocument(in)) {
308 if (!isAtElement(in)) {
314 if (parent instanceof ListEntryNodeDataWithSchema || parent instanceof ContainerNodeDataWithSchema) {
315 parent.setAttributes(getElementAttributes(in));
318 if (parent instanceof LeafListNodeDataWithSchema || parent instanceof ListNodeDataWithSchema) {
319 String xmlElementName = in.getLocalName();
320 while (xmlElementName.equals(parent.getSchema().getQName().getLocalName())) {
321 read(in, newEntryNode(parent), rootElement);
322 if (in.getEventType() == XMLStreamConstants.END_DOCUMENT
323 || in.getEventType() == XMLStreamConstants.END_ELEMENT) {
326 xmlElementName = in.getLocalName();
332 if (parent instanceof AnyXmlNodeDataWithSchema) {
333 setValue(parent, readAnyXmlValue(in), in.getNamespaceContext());
334 if (isNextEndDocument(in)) {
338 if (!isAtElement(in)) {
345 if (parent instanceof YangModeledAnyXmlSchemaNode) {
346 parent.setAttributes(getElementAttributes(in));
349 switch (in.nextTag()) {
350 case XMLStreamConstants.START_ELEMENT:
351 // FIXME: why do we even need this tracker? either document it or remove it
352 final Set<Entry<String, String>> namesakes = new HashSet<>();
353 while (in.hasNext()) {
354 final String xmlElementName = in.getLocalName();
356 DataSchemaNode parentSchema = parent.getSchema();
358 final String parentSchemaName = parentSchema.getQName().getLocalName();
359 if (parentSchemaName.equals(xmlElementName)
360 && in.getEventType() == XMLStreamConstants.END_ELEMENT) {
361 if (isNextEndDocument(in)) {
365 if (!isAtElement(in)) {
371 if (in.isEndElement() && rootElement.equals(xmlElementName)) {
375 if (parentSchema instanceof YangModeledAnyXmlSchemaNode) {
376 parentSchema = ((YangModeledAnyXmlSchemaNode) parentSchema).getSchemaOfAnyXmlData();
379 final String xmlElementNamespace = in.getNamespaceURI();
380 if (!namesakes.add(new SimpleImmutableEntry<>(xmlElementNamespace, xmlElementName))) {
381 final Location loc = in.getLocation();
382 throw new IllegalStateException(String.format(
383 "Duplicate namespace \"%s\" element \"%s\" in XML input at: line %s column %s",
384 xmlElementNamespace, xmlElementName, loc.getLineNumber(), loc.getColumnNumber()));
387 final Deque<DataSchemaNode> childDataSchemaNodes =
388 ParserStreamUtils.findSchemaNodeByNameAndNamespace(parentSchema, xmlElementName,
389 new URI(xmlElementNamespace));
391 if (childDataSchemaNodes.isEmpty()) {
392 checkState(!strictParsing, "Schema for node with name %s and namespace %s does not exist at %s",
393 xmlElementName, xmlElementNamespace, parentSchema.getPath());
398 read(in, ((CompositeNodeDataWithSchema<?>) parent).addChild(childDataSchemaNodes), rootElement);
401 case XMLStreamConstants.END_ELEMENT:
402 if (isNextEndDocument(in)) {
406 if (!isAtElement(in)) {
415 private static boolean isNextEndDocument(final XMLStreamReader in) throws XMLStreamException {
416 return !in.hasNext() || in.next() == XMLStreamConstants.END_DOCUMENT;
419 private static boolean isAtElement(final XMLStreamReader in) {
420 return in.getEventType() == XMLStreamConstants.START_ELEMENT
421 || in.getEventType() == XMLStreamConstants.END_ELEMENT;
424 private static void skipUnknownNode(final XMLStreamReader in) throws XMLStreamException {
425 // in case when the unknown node and at least one of its descendant nodes have the same name
426 // we cannot properly reach the end just by checking if the current node is an end element and has the same name
427 // as the root unknown element. therefore we ignore the names completely and just track the level of nesting
428 int levelOfNesting = 0;
429 while (in.hasNext()) {
430 // in case there are text characters in an element, we cannot skip them by calling nextTag()
431 // therefore we skip them by calling next(), and then proceed to next element
433 if (!isAtElement(in)) {
436 if (in.isStartElement()) {
440 if (in.isEndElement()) {
441 if (levelOfNesting == 0) {
453 private void setValue(final AbstractNodeDataWithSchema<?> parent, final Object value,
454 final NamespaceContext nsContext) {
455 checkArgument(parent instanceof SimpleNodeDataWithSchema, "Node %s is not a simple type",
456 parent.getSchema().getQName());
457 final SimpleNodeDataWithSchema<?> parentSimpleNode = (SimpleNodeDataWithSchema<?>) parent;
458 checkArgument(parentSimpleNode.getValue() == null, "Node '%s' has already set its value to '%s'",
459 parentSimpleNode.getSchema().getQName(), parentSimpleNode.getValue());
461 parentSimpleNode.setValue(translateValueByType(value, parentSimpleNode.getSchema(), nsContext));
464 private Object translateValueByType(final Object value, final DataSchemaNode node,
465 final NamespaceContext namespaceCtx) {
466 if (node instanceof AnyXmlSchemaNode) {
468 checkArgument(value instanceof Document);
470 * FIXME: Figure out some YANG extension dispatch, which will
471 * reuse JSON parsing or XML parsing - anyxml is not well-defined in
474 return new DOMSource(((Document) value).getDocumentElement());
477 checkArgument(node instanceof TypedDataSchemaNode);
478 checkArgument(value instanceof String);
479 return codecs.codecFor((TypedDataSchemaNode) node).parseValue(namespaceCtx, (String) value);
482 private static AbstractNodeDataWithSchema<?> newEntryNode(final AbstractNodeDataWithSchema<?> parent) {
483 final AbstractNodeDataWithSchema<?> newChild;
484 if (parent instanceof ListNodeDataWithSchema) {
485 newChild = ListEntryNodeDataWithSchema.forSchema(((ListNodeDataWithSchema) parent).getSchema());
487 verify(parent instanceof LeafListNodeDataWithSchema, "Unexpected parent %s", parent);
488 newChild = new LeafListEntryNodeDataWithSchema(((LeafListNodeDataWithSchema) parent).getSchema());
490 ((CompositeNodeDataWithSchema<?>) parent).addChild(newChild);
495 public void close() throws IOException {
501 public void flush() throws IOException {