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;
21 import java.net.URISyntaxException;
22 import java.util.AbstractMap.SimpleImmutableEntry;
23 import java.util.Deque;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.Iterator;
27 import java.util.LinkedHashMap;
29 import java.util.Map.Entry;
30 import java.util.Optional;
32 import javax.xml.XMLConstants;
33 import javax.xml.namespace.NamespaceContext;
34 import javax.xml.stream.XMLStreamConstants;
35 import javax.xml.stream.XMLStreamException;
36 import javax.xml.stream.XMLStreamReader;
37 import javax.xml.stream.util.StreamReaderDelegate;
38 import javax.xml.transform.TransformerException;
39 import javax.xml.transform.TransformerFactory;
40 import javax.xml.transform.TransformerFactoryConfigurationError;
41 import javax.xml.transform.dom.DOMResult;
42 import javax.xml.transform.dom.DOMSource;
43 import javax.xml.transform.stax.StAXSource;
44 import org.opendaylight.yangtools.rfc7952.model.api.AnnotationSchemaNode;
45 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
46 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContextFactory;
47 import org.opendaylight.yangtools.rfc8528.data.api.MountPointIdentifier;
48 import org.opendaylight.yangtools.rfc8528.data.api.YangLibraryConstants;
49 import org.opendaylight.yangtools.rfc8528.data.api.YangLibraryConstants.ContainerName;
50 import org.opendaylight.yangtools.rfc8528.model.api.MountPointSchemaNode;
51 import org.opendaylight.yangtools.rfc8528.model.api.SchemaMountConstants;
52 import org.opendaylight.yangtools.yang.common.QName;
53 import org.opendaylight.yangtools.yang.common.QNameModule;
54 import org.opendaylight.yangtools.yang.common.XMLNamespace;
55 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
56 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
57 import org.opendaylight.yangtools.yang.data.util.AbstractMountPointDataWithSchema;
58 import org.opendaylight.yangtools.yang.data.util.AbstractNodeDataWithSchema;
59 import org.opendaylight.yangtools.yang.data.util.AnyXmlNodeDataWithSchema;
60 import org.opendaylight.yangtools.yang.data.util.AnydataNodeDataWithSchema;
61 import org.opendaylight.yangtools.yang.data.util.CompositeNodeDataWithSchema;
62 import org.opendaylight.yangtools.yang.data.util.CompositeNodeDataWithSchema.ChildReusePolicy;
63 import org.opendaylight.yangtools.yang.data.util.ContainerNodeDataWithSchema;
64 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
65 import org.opendaylight.yangtools.yang.data.util.LeafListEntryNodeDataWithSchema;
66 import org.opendaylight.yangtools.yang.data.util.LeafListNodeDataWithSchema;
67 import org.opendaylight.yangtools.yang.data.util.LeafNodeDataWithSchema;
68 import org.opendaylight.yangtools.yang.data.util.ListEntryNodeDataWithSchema;
69 import org.opendaylight.yangtools.yang.data.util.ListNodeDataWithSchema;
70 import org.opendaylight.yangtools.yang.data.util.MountPointData;
71 import org.opendaylight.yangtools.yang.data.util.MultipleEntryDataWithSchema;
72 import org.opendaylight.yangtools.yang.data.util.NotificationAsContainer;
73 import org.opendaylight.yangtools.yang.data.util.OperationAsContainer;
74 import org.opendaylight.yangtools.yang.data.util.ParserStreamUtils;
75 import org.opendaylight.yangtools.yang.data.util.SimpleNodeDataWithSchema;
76 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
77 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
78 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
79 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
80 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
82 import org.opendaylight.yangtools.yang.model.api.EffectiveStatementInference;
83 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.Module;
87 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
88 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
89 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
91 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
92 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
93 import org.slf4j.Logger;
94 import org.slf4j.LoggerFactory;
95 import org.w3c.dom.Document;
96 import org.xml.sax.SAXException;
99 * This class provides functionality for parsing an XML source containing YANG-modeled data. It disallows multiple
100 * instances of the same element except for leaf-list and list entries. It also expects that the YANG-modeled data in
101 * the XML source are wrapped in a root element. This class is NOT thread-safe.
104 * Due to backwards compatibility reasons, RFC7952 metadata emitted by this parser may include key QNames with empty URI
105 * (as exposed via {@link #LEGACY_ATTRIBUTE_NAMESPACE}) as their QNameModule. These indicate an unqualified XML
106 * attribute and their value can be assumed to be a String. Furthermore, this extends to qualified attributes, which
107 * uses the proper namespace, but will not bind to a proper module revision -- these need to be reconciled with a
108 * particular SchemaContext and are expected to either be fully decoded, or contain a String value. Handling of such
109 * annotations is at the discretion of the user encountering it: preferred way of handling is to either filter or
110 * normalize them to proper QNames/values when encountered. This caveat will be removed in a future version.
113 public final class XmlParserStream implements Closeable, Flushable {
115 * {@link QNameModule} for use with legacy XML attributes.
116 * @deprecated The use on this namespace is discouraged and users are strongly encouraged to proper RFC7952 metadata
120 public static final QNameModule LEGACY_ATTRIBUTE_NAMESPACE = QNameModule.create(XMLNamespace.of("")).intern();
122 private static final Logger LOG = LoggerFactory.getLogger(XmlParserStream.class);
123 private static final String XML_STANDARD_VERSION = "1.0";
124 private static final String COM_SUN_TRANSFORMER =
125 "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
127 private static final TransformerFactory TRANSFORMER_FACTORY;
130 TransformerFactory fa = TransformerFactory.newInstance();
131 if (!fa.getFeature(StAXSource.FEATURE)) {
132 LOG.warn("Platform-default TransformerFactory {} does not support StAXSource, attempting fallback to {}",
133 fa, COM_SUN_TRANSFORMER);
134 fa = TransformerFactory.newInstance(COM_SUN_TRANSFORMER, null);
135 if (!fa.getFeature(StAXSource.FEATURE)) {
136 throw new TransformerFactoryConfigurationError("No TransformerFactory supporting StAXResult found.");
140 TRANSFORMER_FACTORY = fa;
143 // Cache of nsUri Strings to QNameModules, as resolved in context
144 private final Map<String, Optional<QNameModule>> resolvedNamespaces = new HashMap<>();
145 // Cache of nsUri Strings to QNameModules, as inferred from document
146 private final Map<String, QNameModule> rawNamespaces = new HashMap<>();
147 private final NormalizedNodeStreamWriter writer;
148 private final SchemaInferenceStack stack;
149 private final XmlCodecFactory codecs;
150 private final DataSchemaNode parentNode;
151 private final boolean strictParsing;
153 private XmlParserStream(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
154 final SchemaInferenceStack stack, final boolean strictParsing) {
155 this.writer = requireNonNull(writer);
156 this.codecs = requireNonNull(codecs);
157 this.stack = requireNonNull(stack);
158 this.strictParsing = strictParsing;
160 if (!stack.isEmpty()) {
161 final EffectiveStatement<?, ?> stmt = stack.currentStatement();
162 if (stmt instanceof DataSchemaNode) {
163 parentNode = (DataSchemaNode) stmt;
164 } else if (stmt instanceof OperationDefinition) {
165 parentNode = OperationAsContainer.of((OperationDefinition) stmt);
166 } else if (stmt instanceof NotificationDefinition) {
167 parentNode = NotificationAsContainer.of((NotificationDefinition) stmt);
169 throw new IllegalArgumentException("Illegal parent node " + stmt);
172 parentNode = stack.getEffectiveModelContext();
177 * Construct a new {@link XmlParserStream} with strict parsing mode switched on.
179 * @param writer Output writer
180 * @param codecs Shared codecs
181 * @param parentNode Parent root node
182 * @return A new stream instance
184 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
185 final EffectiveStatementInference parentNode) {
186 return create(writer, codecs, parentNode, true);
190 * Construct a new {@link XmlParserStream}.
192 * @param writer Output writer
193 * @param codecs Shared codecs
194 * @param parentNode Parent root node
195 * @param strictParsing parsing mode
196 * if set to true, the parser will throw an exception if it encounters unknown child nodes
197 * (nodes, that are not defined in the provided SchemaContext) in containers and lists
198 * if set to false, the parser will skip unknown child nodes
199 * @return A new stream instance
201 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
202 final EffectiveStatementInference parentNode, final boolean strictParsing) {
203 return new XmlParserStream(writer, codecs, SchemaInferenceStack.ofInference(parentNode), strictParsing);
207 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
208 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, EffectiveStatementInference)}
209 * instead and maintain a {@link XmlCodecFactory} to match the current {@link EffectiveModelContext}.
211 public static XmlParserStream create(final NormalizedNodeStreamWriter writer,
212 final EffectiveModelContext context) {
213 return create(writer, context, true);
217 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
218 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, EffectiveStatementInference)}
219 * instead and maintain a {@link XmlCodecFactory} to match the current {@link EffectiveModelContext}.
221 public static XmlParserStream create(final NormalizedNodeStreamWriter writer,
222 final EffectiveModelContext context, final boolean strictParsing) {
223 return create(writer, SchemaInferenceStack.of(context).toInference(), strictParsing);
227 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
228 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, EffectiveStatementInference)}
229 * instead and maintain a {@link XmlCodecFactory} to match the current {@link EffectiveModelContext}.
231 public static XmlParserStream create(final NormalizedNodeStreamWriter writer,
232 final EffectiveStatementInference parentNode) {
233 return create(writer, parentNode, true);
237 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
238 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, EffectiveStatementInference)}
239 * instead and maintain a {@link XmlCodecFactory} to match the current {@link EffectiveModelContext}.
241 public static XmlParserStream create(final NormalizedNodeStreamWriter writer,
242 final EffectiveStatementInference parentNode, final boolean strictParsing) {
243 return create(writer, XmlCodecFactory.create(parentNode.getEffectiveModelContext()), parentNode, strictParsing);
247 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
248 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, EffectiveStatementInference)}
249 * instead and maintain a {@link XmlCodecFactory} to match the current {@link MountPointContext}.
251 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx) {
252 return create(writer, mountCtx, SchemaInferenceStack.of(mountCtx.getEffectiveModelContext()).toInference(),
257 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
258 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, EffectiveStatementInference)}
259 * instead and maintain a {@link XmlCodecFactory} to match the current {@link MountPointContext}.
261 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
262 final EffectiveStatementInference parentNode) {
263 return create(writer, mountCtx, parentNode, true);
267 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
268 final Absolute parentNode) {
269 return create(writer, mountCtx, parentNode, true);
273 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
274 final Absolute parentNode, final boolean strictParsing) {
275 return create(writer, XmlCodecFactory.create(mountCtx), parentNode, strictParsing);
279 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
280 final Absolute parentNode) {
281 return create(writer, codecs, parentNode, true);
285 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
286 final Absolute parentNode, final boolean strictParsing) {
287 return new XmlParserStream(writer, codecs,
288 SchemaInferenceStack.of(codecs.getEffectiveModelContext(), parentNode), strictParsing);
292 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
293 final YangInstanceIdentifier parentNode) {
294 return create(writer, mountCtx, parentNode, true);
298 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
299 final YangInstanceIdentifier parentNode, final boolean strictParsing) {
300 final var init = DataSchemaContextTree.from(mountCtx.getEffectiveModelContext())
301 .enterPath(parentNode)
303 return new XmlParserStream(writer, XmlCodecFactory.create(mountCtx), init.stack(), strictParsing);
307 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
308 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, EffectiveStatementInference)}
309 * instead and maintain a {@link XmlCodecFactory} to match the current {@link MountPointContext}.
311 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
312 final EffectiveStatementInference parentNode, final boolean strictParsing) {
313 return create(writer, XmlCodecFactory.create(mountCtx), parentNode, strictParsing);
317 * This method parses the XML source and emits node events into a NormalizedNodeStreamWriter based on the
318 * YANG-modeled data contained in the XML source.
321 * StAX reader which is to used to walk through the XML source
323 * instance of XmlParserStream
324 * @throws XMLStreamException
325 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
326 * @throws URISyntaxException
327 * if the namespace URI of an XML element contains a syntax error
328 * @throws IOException
329 * if an error occurs while parsing the value of an anyxml node
330 * @throws SAXException
331 * if an error occurs while parsing the value of an anyxml node
333 public XmlParserStream parse(final XMLStreamReader reader) throws XMLStreamException, URISyntaxException,
334 IOException, SAXException {
335 if (reader.hasNext()) {
337 final AbstractNodeDataWithSchema<?> nodeDataWithSchema;
338 if (parentNode instanceof ContainerLike) {
339 nodeDataWithSchema = new ContainerNodeDataWithSchema((ContainerLike) parentNode);
340 } else if (parentNode instanceof ListSchemaNode) {
341 nodeDataWithSchema = new ListNodeDataWithSchema((ListSchemaNode) parentNode);
342 } else if (parentNode instanceof AnyxmlSchemaNode) {
343 nodeDataWithSchema = new AnyXmlNodeDataWithSchema((AnyxmlSchemaNode) parentNode);
344 } else if (parentNode instanceof LeafSchemaNode) {
345 nodeDataWithSchema = new LeafNodeDataWithSchema((LeafSchemaNode) parentNode);
346 } else if (parentNode instanceof LeafListSchemaNode) {
347 nodeDataWithSchema = new LeafListNodeDataWithSchema((LeafListSchemaNode) parentNode);
348 } else if (parentNode instanceof AnydataSchemaNode) {
349 nodeDataWithSchema = new AnydataNodeDataWithSchema((AnydataSchemaNode) parentNode);
351 throw new IllegalStateException("Unsupported schema node type " + parentNode.getClass() + ".");
354 read(reader, nodeDataWithSchema, reader.getLocalName());
355 nodeDataWithSchema.write(writer);
362 * This method traverses a {@link DOMSource} and emits node events into a NormalizedNodeStreamWriter based on the
363 * YANG-modeled data contained in the source.
366 * {@link DOMSource} to be traversed
368 * instance of XmlParserStream
369 * @throws XMLStreamException
370 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
371 * @throws URISyntaxException
372 * if the namespace URI of an XML element contains a syntax error
373 * @throws IOException
374 * if an error occurs while parsing the value of an anyxml node
375 * @throws SAXException
376 * if an error occurs while parsing the value of an anyxml node
379 public XmlParserStream traverse(final DOMSource src) throws XMLStreamException, URISyntaxException, IOException,
381 return parse(new DOMSourceXMLStreamReader(src));
384 private ImmutableMap<QName, Object> getElementAttributes(final XMLStreamReader in) {
385 checkState(in.isStartElement(), "Attributes can be extracted only from START_ELEMENT.");
386 final Map<QName, Object> attributes = new LinkedHashMap<>();
388 for (int attrIndex = 0; attrIndex < in.getAttributeCount(); attrIndex++) {
389 final String attributeNS = in.getAttributeNamespace(attrIndex);
391 // Skip namespace definitions
392 if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attributeNS)) {
396 final String localName = in.getAttributeLocalName(attrIndex);
397 final String attrValue = in.getAttributeValue(attrIndex);
398 if (Strings.isNullOrEmpty(attributeNS)) {
399 StreamWriterFacade.warnLegacyAttribute(localName);
400 attributes.put(QName.create(LEGACY_ATTRIBUTE_NAMESPACE, localName), attrValue);
404 // Cross-relate attribute namespace to the module
405 final Optional<QNameModule> optModule = resolveXmlNamespace(attributeNS);
406 if (optModule.isPresent()) {
407 final QName qname = QName.create(optModule.get(), localName);
408 final Optional<AnnotationSchemaNode> optAnnotation = AnnotationSchemaNode.find(
409 codecs.getEffectiveModelContext(), qname);
410 if (optAnnotation.isPresent()) {
411 final AnnotationSchemaNode schema = optAnnotation.get();
412 final Object value = codecs.codecFor(schema, stack)
413 .parseValue(in.getNamespaceContext(), attrValue);
414 attributes.put(schema.getQName(), value);
418 LOG.debug("Annotation for {} not found, using legacy QName", qname);
421 attributes.put(QName.create(rawXmlNamespace(attributeNS), localName), attrValue);
424 return ImmutableMap.copyOf(attributes);
427 private static Document readAnyXmlValue(final XMLStreamReader in) throws XMLStreamException {
428 // Underlying reader might return null when asked for version, however when such reader is plugged into
429 // Stax -> DOM transformer, it fails with NPE due to null version. Use default xml version in such case.
430 final XMLStreamReader inWrapper;
431 if (in.getVersion() == null) {
432 inWrapper = new StreamReaderDelegate(in) {
434 public String getVersion() {
435 final String ver = super.getVersion();
436 return ver != null ? ver : XML_STANDARD_VERSION;
443 final DOMResult result = new DOMResult();
445 TRANSFORMER_FACTORY.newTransformer().transform(new StAXSource(inWrapper), result);
446 } catch (final TransformerException e) {
447 throw new XMLStreamException("Unable to read anyxml value", e);
449 return (Document) result.getNode();
452 private void read(final XMLStreamReader in, final AbstractNodeDataWithSchema<?> parent, final String rootElement)
453 throws XMLStreamException {
458 if (parent instanceof LeafNodeDataWithSchema || parent instanceof LeafListEntryNodeDataWithSchema) {
459 parent.setAttributes(getElementAttributes(in));
460 setValue((SimpleNodeDataWithSchema<?>) parent, in.getElementText().trim(), in.getNamespaceContext());
461 if (isNextEndDocument(in)) {
465 if (!isAtElement(in)) {
471 if (parent instanceof ListEntryNodeDataWithSchema || parent instanceof ContainerNodeDataWithSchema) {
472 parent.setAttributes(getElementAttributes(in));
475 if (parent instanceof LeafListNodeDataWithSchema || parent instanceof ListNodeDataWithSchema) {
476 String xmlElementName = in.getLocalName();
477 while (xmlElementName.equals(parent.getSchema().getQName().getLocalName())) {
478 read(in, newEntryNode(parent), rootElement);
479 if (in.getEventType() == XMLStreamConstants.END_DOCUMENT
480 || in.getEventType() == XMLStreamConstants.END_ELEMENT) {
483 xmlElementName = in.getLocalName();
489 if (parent instanceof AnyXmlNodeDataWithSchema) {
490 setValue((AnyXmlNodeDataWithSchema) parent, readAnyXmlValue(in), in.getNamespaceContext());
491 if (isNextEndDocument(in)) {
495 if (!isAtElement(in)) {
502 if (parent instanceof AnydataNodeDataWithSchema) {
503 final AnydataNodeDataWithSchema anydata = (AnydataNodeDataWithSchema) parent;
504 anydata.setObjectModel(DOMSourceAnydata.class);
505 anydata.setAttributes(getElementAttributes(in));
506 setValue(anydata, readAnyXmlValue(in), in.getNamespaceContext());
507 if (isNextEndDocument(in)) {
511 if (!isAtElement(in)) {
518 switch (in.nextTag()) {
519 case XMLStreamConstants.START_ELEMENT:
520 // FIXME: 7.0.0: why do we even need this tracker? either document it or remove it.
521 // it looks like it is a crude duplicate finder, which should really be handled via
522 // ChildReusePolicy.REJECT
523 final Set<Entry<String, String>> namesakes = new HashSet<>();
524 while (in.hasNext()) {
525 final String xmlElementName = in.getLocalName();
526 final DataSchemaNode parentSchema = parent.getSchema();
528 final String parentSchemaName = parentSchema.getQName().getLocalName();
529 if (parentSchemaName.equals(xmlElementName)
530 && in.getEventType() == XMLStreamConstants.END_ELEMENT) {
531 if (isNextEndDocument(in)) {
535 if (!isAtElement(in)) {
541 if (in.isEndElement() && rootElement.equals(xmlElementName)) {
545 final String elementNS = in.getNamespaceURI();
546 final boolean added = namesakes.add(new SimpleImmutableEntry<>(elementNS, xmlElementName));
548 final XMLNamespace nsUri;
550 nsUri = rawXmlNamespace(elementNS).getNamespace();
551 } catch (IllegalArgumentException e) {
552 throw new XMLStreamException("Failed to convert namespace " + xmlElementName, in.getLocation(),
556 final Deque<DataSchemaNode> childDataSchemaNodes =
557 ParserStreamUtils.findSchemaNodeByNameAndNamespace(parentSchema, xmlElementName, nsUri);
558 if (!childDataSchemaNodes.isEmpty()) {
559 final boolean elementList = isElementList(childDataSchemaNodes);
560 if (!added && !elementList) {
561 throw new XMLStreamException(String.format(
562 "Duplicate element \"%s\" in namespace \"%s\" with parent \"%s\" in XML input",
563 xmlElementName, elementNS, parentSchema), in.getLocation());
566 // We have a match, proceed with it
567 final QName qname = childDataSchemaNodes.peekLast().getQName();
568 final AbstractNodeDataWithSchema<?> child = ((CompositeNodeDataWithSchema<?>) parent).addChild(
569 childDataSchemaNodes, elementList ? ChildReusePolicy.REUSE : ChildReusePolicy.NOOP);
570 stack.enterDataTree(qname);
571 read(in, child, rootElement);
576 if (parent instanceof AbstractMountPointDataWithSchema) {
577 // Parent can potentially hold a mount point, let's see if there is a label present
578 final Optional<MountPointSchemaNode> optMount;
579 if (parentSchema instanceof ContainerSchemaNode) {
580 optMount = MountPointSchemaNode.streamAll((ContainerSchemaNode) parentSchema).findFirst();
581 } else if (parentSchema instanceof ListSchemaNode) {
582 optMount = MountPointSchemaNode.streamAll((ListSchemaNode) parentSchema).findFirst();
584 throw new XMLStreamException("Unhandled mount-aware schema " + parentSchema,
588 if (optMount.isPresent()) {
589 final MountPointIdentifier mountId = MountPointIdentifier.of(optMount.get().getQName());
590 LOG.debug("Assuming node {} and namespace {} belongs to mount point {}", xmlElementName,
593 final Optional<MountPointContextFactory> optFactory = codecs.mountPointContext()
594 .findMountPoint(mountId);
595 if (optFactory.isPresent()) {
596 final MountPointData mountData = ((AbstractMountPointDataWithSchema<?>) parent)
597 .getMountPointData(mountId, optFactory.get());
598 addMountPointChild(mountData, nsUri, xmlElementName,
599 new DOMSource(readAnyXmlValue(in).getDocumentElement()));
603 LOG.debug("Mount point {} not attached", mountId);
607 // We have not handled the node -- let's decide what to do about that
609 throw new XMLStreamException(String.format(
610 "Schema for node with name %s and namespace %s does not exist in parent %s", xmlElementName,
611 elementNS, parentSchema), in.getLocation());
614 LOG.debug("Skipping unknown node ns=\"{}\" localName=\"{}\" in parent {}", elementNS,
615 xmlElementName, parentSchema);
619 case XMLStreamConstants.END_ELEMENT:
620 if (isNextEndDocument(in)) {
624 if (!isAtElement(in)) {
633 // Return true if schema represents a construct which uses multiple sibling elements to represent its content. The
634 // siblings MAY be interleaved as per RFC7950.
635 private static boolean isElementList(final Deque<DataSchemaNode> childDataSchemaNodes) {
636 final DataSchemaNode last = childDataSchemaNodes.getLast();
637 return last instanceof ListSchemaNode || last instanceof LeafListSchemaNode;
640 private static void addMountPointChild(final MountPointData mount, final XMLNamespace namespace,
641 final String localName, final DOMSource source) {
642 final DOMSourceMountPointChild child = new DOMSourceMountPointChild(source);
643 if (YangLibraryConstants.MODULE_NAMESPACE.equals(namespace)) {
644 final Optional<ContainerName> optName = ContainerName.forLocalName(localName);
645 if (optName.isPresent()) {
646 mount.setContainer(optName.get(), child);
650 LOG.warn("Encountered unknown element {} from YANG Library namespace", localName);
651 } else if (SchemaMountConstants.RFC8528_MODULE.getNamespace().equals(namespace)) {
652 mount.setSchemaMounts(child);
656 mount.addChild(child);
659 private static boolean isNextEndDocument(final XMLStreamReader in) throws XMLStreamException {
660 return !in.hasNext() || in.next() == XMLStreamConstants.END_DOCUMENT;
663 private static boolean isAtElement(final XMLStreamReader in) {
664 return in.getEventType() == XMLStreamConstants.START_ELEMENT
665 || in.getEventType() == XMLStreamConstants.END_ELEMENT;
668 private static void skipUnknownNode(final XMLStreamReader in) throws XMLStreamException {
669 // in case when the unknown node and at least one of its descendant nodes have the same name
670 // we cannot properly reach the end just by checking if the current node is an end element and has the same name
671 // as the root unknown element. therefore we ignore the names completely and just track the level of nesting
672 int levelOfNesting = 0;
673 while (in.hasNext()) {
674 // in case there are text characters in an element, we cannot skip them by calling nextTag()
675 // therefore we skip them by calling next(), and then proceed to next element
677 if (!isAtElement(in)) {
680 if (in.isStartElement()) {
684 if (in.isEndElement()) {
685 if (levelOfNesting == 0) {
696 private void setValue(final SimpleNodeDataWithSchema<?> parent, final Object value,
697 final NamespaceContext nsContext) {
698 final DataSchemaNode schema = parent.getSchema();
699 final Object prev = parent.getValue();
700 checkArgument(prev == null, "Node '%s' has already set its value to '%s'", schema.getQName(), prev);
701 parent.setValue(translateValueByType(value, schema, nsContext));
704 private Object translateValueByType(final Object value, final DataSchemaNode node,
705 final NamespaceContext namespaceCtx) {
706 if (node instanceof AnyxmlSchemaNode) {
707 checkArgument(value instanceof Document);
709 * FIXME: Figure out some YANG extension dispatch, which will reuse JSON parsing or XML parsing -
710 * anyxml is not well-defined in JSON.
712 return new DOMSource(((Document) value).getDocumentElement());
714 if (node instanceof AnydataSchemaNode) {
715 checkArgument(value instanceof Document);
716 return new DOMSourceAnydata(new DOMSource(((Document) value).getDocumentElement()));
719 checkArgument(node instanceof TypedDataSchemaNode);
720 checkArgument(value instanceof String);
721 return codecs.codecFor((TypedDataSchemaNode) node, stack).parseValue(namespaceCtx, (String) value);
724 private static AbstractNodeDataWithSchema<?> newEntryNode(final AbstractNodeDataWithSchema<?> parent) {
725 verify(parent instanceof MultipleEntryDataWithSchema, "Unexpected parent %s", parent);
726 return ((MultipleEntryDataWithSchema<?>) parent).newChildEntry();
730 public void close() throws IOException {
736 public void flush() throws IOException {
740 private Optional<QNameModule> resolveXmlNamespace(final String xmlNamespace) {
741 return resolvedNamespaces.computeIfAbsent(xmlNamespace, nsUri -> {
742 final Iterator<? extends Module> it = codecs.getEffectiveModelContext().findModules(XMLNamespace.of(nsUri))
744 return it.hasNext() ? Optional.of(it.next().getQNameModule()) : Optional.empty();
748 private QNameModule rawXmlNamespace(final String xmlNamespace) {
749 return rawNamespaces.computeIfAbsent(xmlNamespace, nsUri -> QNameModule.create(XMLNamespace.of(nsUri)));