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.stmt.SchemaNodeIdentifier.Absolute;
91 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
92 import org.slf4j.Logger;
93 import org.slf4j.LoggerFactory;
94 import org.w3c.dom.Document;
95 import org.xml.sax.SAXException;
98 * This class provides functionality for parsing an XML source containing YANG-modeled data. It disallows multiple
99 * instances of the same element except for leaf-list and list entries. It also expects that the YANG-modeled data in
100 * the XML source are wrapped in a root element. This class is NOT thread-safe.
103 * Due to backwards compatibility reasons, RFC7952 metadata emitted by this parser may include key QNames with empty URI
104 * (as exposed via {@link #LEGACY_ATTRIBUTE_NAMESPACE}) as their QNameModule. These indicate an unqualified XML
105 * attribute and their value can be assumed to be a String. Furthermore, this extends to qualified attributes, which
106 * uses the proper namespace, but will not bind to a proper module revision -- these need to be reconciled with a
107 * particular SchemaContext and are expected to either be fully decoded, or contain a String value. Handling of such
108 * annotations is at the discretion of the user encountering it: preferred way of handling is to either filter or
109 * normalize them to proper QNames/values when encountered. This caveat will be removed in a future version.
112 public final class XmlParserStream implements Closeable, Flushable {
114 * {@link QNameModule} for use with legacy XML attributes.
115 * @deprecated The use on this namespace is discouraged and users are strongly encouraged to proper RFC7952 metadata
119 public static final QNameModule LEGACY_ATTRIBUTE_NAMESPACE = QNameModule.create(XMLNamespace.of("")).intern();
121 private static final Logger LOG = LoggerFactory.getLogger(XmlParserStream.class);
122 private static final String XML_STANDARD_VERSION = "1.0";
123 private static final String COM_SUN_TRANSFORMER =
124 "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
126 private static final TransformerFactory TRANSFORMER_FACTORY;
129 TransformerFactory fa = TransformerFactory.newInstance();
130 if (!fa.getFeature(StAXSource.FEATURE)) {
131 LOG.warn("Platform-default TransformerFactory {} does not support StAXSource, attempting fallback to {}",
132 fa, COM_SUN_TRANSFORMER);
133 fa = TransformerFactory.newInstance(COM_SUN_TRANSFORMER, null);
134 if (!fa.getFeature(StAXSource.FEATURE)) {
135 throw new TransformerFactoryConfigurationError("No TransformerFactory supporting StAXResult found.");
139 TRANSFORMER_FACTORY = fa;
142 // Cache of nsUri Strings to QNameModules, as resolved in context
143 private final Map<String, Optional<QNameModule>> resolvedNamespaces = new HashMap<>();
144 // Cache of nsUri Strings to QNameModules, as inferred from document
145 private final Map<String, QNameModule> rawNamespaces = new HashMap<>();
146 private final NormalizedNodeStreamWriter writer;
147 private final SchemaInferenceStack stack;
148 private final XmlCodecFactory codecs;
149 private final DataSchemaNode parentNode;
150 private final boolean strictParsing;
152 private XmlParserStream(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
153 final SchemaInferenceStack stack, final boolean strictParsing) {
154 this.writer = requireNonNull(writer);
155 this.codecs = requireNonNull(codecs);
156 this.stack = requireNonNull(stack);
157 this.strictParsing = strictParsing;
159 if (!stack.isEmpty()) {
160 final var stmt = stack.currentStatement();
161 if (stmt instanceof DataSchemaNode data) {
163 } else if (stmt instanceof OperationDefinition oper) {
164 parentNode = OperationAsContainer.of(oper);
165 } else if (stmt instanceof NotificationDefinition notif) {
166 parentNode = NotificationAsContainer.of(notif);
168 throw new IllegalArgumentException("Illegal parent node " + stmt);
171 parentNode = stack.getEffectiveModelContext();
176 * Construct a new {@link XmlParserStream} with strict parsing mode switched on.
178 * @param writer Output writer
179 * @param codecs Shared codecs
180 * @param parentNode Parent root node
181 * @return A new stream instance
183 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
184 final EffectiveStatementInference parentNode) {
185 return create(writer, codecs, parentNode, true);
189 * Construct a new {@link XmlParserStream}.
191 * @param writer Output writer
192 * @param codecs Shared codecs
193 * @param parentNode Parent root node
194 * @param strictParsing parsing mode
195 * if set to true, the parser will throw an exception if it encounters unknown child nodes
196 * (nodes, that are not defined in the provided SchemaContext) in containers and lists
197 * if set to false, the parser will skip unknown child nodes
198 * @return A new stream instance
200 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
201 final EffectiveStatementInference parentNode, final boolean strictParsing) {
202 return new XmlParserStream(writer, codecs, SchemaInferenceStack.ofInference(parentNode), strictParsing);
206 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
207 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, EffectiveStatementInference)}
208 * instead and maintain a {@link XmlCodecFactory} to match the current {@link EffectiveModelContext}.
210 public static XmlParserStream create(final NormalizedNodeStreamWriter writer,
211 final EffectiveModelContext context) {
212 return create(writer, context, true);
216 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
217 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, EffectiveStatementInference)}
218 * instead and maintain a {@link XmlCodecFactory} to match the current {@link EffectiveModelContext}.
220 public static XmlParserStream create(final NormalizedNodeStreamWriter writer,
221 final EffectiveModelContext context, final boolean strictParsing) {
222 return create(writer, SchemaInferenceStack.of(context).toInference(), strictParsing);
226 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
227 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, EffectiveStatementInference)}
228 * instead and maintain a {@link XmlCodecFactory} to match the current {@link EffectiveModelContext}.
230 public static XmlParserStream create(final NormalizedNodeStreamWriter writer,
231 final EffectiveStatementInference parentNode) {
232 return create(writer, parentNode, true);
236 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
237 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, EffectiveStatementInference)}
238 * instead and maintain a {@link XmlCodecFactory} to match the current {@link EffectiveModelContext}.
240 public static XmlParserStream create(final NormalizedNodeStreamWriter writer,
241 final EffectiveStatementInference parentNode, final boolean strictParsing) {
242 return create(writer, XmlCodecFactory.create(parentNode.getEffectiveModelContext()), parentNode, strictParsing);
246 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
247 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, EffectiveStatementInference)}
248 * instead and maintain a {@link XmlCodecFactory} to match the current {@link MountPointContext}.
250 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx) {
251 return create(writer, mountCtx, SchemaInferenceStack.of(mountCtx.getEffectiveModelContext()).toInference(),
256 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
257 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, EffectiveStatementInference)}
258 * instead and maintain a {@link XmlCodecFactory} to match the current {@link MountPointContext}.
260 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
261 final EffectiveStatementInference parentNode) {
262 return create(writer, mountCtx, parentNode, true);
266 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
267 final Absolute parentNode) {
268 return create(writer, mountCtx, parentNode, true);
272 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
273 final Absolute parentNode, final boolean strictParsing) {
274 return create(writer, XmlCodecFactory.create(mountCtx), parentNode, strictParsing);
278 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
279 final Absolute parentNode) {
280 return create(writer, codecs, parentNode, true);
284 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
285 final Absolute parentNode, final boolean strictParsing) {
286 return new XmlParserStream(writer, codecs,
287 SchemaInferenceStack.of(codecs.getEffectiveModelContext(), parentNode), strictParsing);
291 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
292 final YangInstanceIdentifier parentNode) {
293 return create(writer, mountCtx, parentNode, true);
297 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
298 final YangInstanceIdentifier parentNode, final boolean strictParsing) {
299 final var init = DataSchemaContextTree.from(mountCtx.getEffectiveModelContext())
300 .enterPath(parentNode)
302 return new XmlParserStream(writer, XmlCodecFactory.create(mountCtx), init.stack(), strictParsing);
306 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
307 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, EffectiveStatementInference)}
308 * instead and maintain a {@link XmlCodecFactory} to match the current {@link MountPointContext}.
310 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
311 final EffectiveStatementInference parentNode, final boolean strictParsing) {
312 return create(writer, XmlCodecFactory.create(mountCtx), parentNode, strictParsing);
316 * This method parses the XML source and emits node events into a NormalizedNodeStreamWriter based on the
317 * YANG-modeled data contained in the XML source.
320 * StAX reader which is to used to walk through the XML source
322 * instance of XmlParserStream
323 * @throws XMLStreamException
324 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
325 * @throws IOException
326 * if an error occurs while parsing the value of an anyxml node
328 public XmlParserStream parse(final XMLStreamReader reader) throws XMLStreamException, IOException {
329 if (reader.hasNext()) {
331 final AbstractNodeDataWithSchema<?> nodeDataWithSchema;
332 if (parentNode instanceof ContainerLike containerLike) {
333 nodeDataWithSchema = new ContainerNodeDataWithSchema(containerLike);
334 } else if (parentNode instanceof ListSchemaNode list) {
335 nodeDataWithSchema = new ListNodeDataWithSchema(list);
336 } else if (parentNode instanceof AnyxmlSchemaNode anyxml) {
337 nodeDataWithSchema = new AnyXmlNodeDataWithSchema(anyxml);
338 } else if (parentNode instanceof LeafSchemaNode leaf) {
339 nodeDataWithSchema = new LeafNodeDataWithSchema(leaf);
340 } else if (parentNode instanceof LeafListSchemaNode leafList) {
341 nodeDataWithSchema = new LeafListNodeDataWithSchema(leafList);
342 } else if (parentNode instanceof AnydataSchemaNode anydata) {
343 nodeDataWithSchema = new AnydataNodeDataWithSchema(anydata);
345 throw new IllegalStateException("Unsupported schema node type " + parentNode.getClass() + ".");
348 read(reader, nodeDataWithSchema, reader.getLocalName());
349 nodeDataWithSchema.write(writer);
356 * This method traverses a {@link DOMSource} and emits node events into a NormalizedNodeStreamWriter based on the
357 * YANG-modeled data contained in the source.
360 * {@link DOMSource} to be traversed
362 * instance of XmlParserStream
363 * @throws XMLStreamException
364 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
365 * @throws URISyntaxException
366 * if the namespace URI of an XML element contains a syntax error
367 * @throws IOException
368 * if an error occurs while parsing the value of an anyxml node
369 * @throws SAXException
370 * if an error occurs while parsing the value of an anyxml node
373 public XmlParserStream traverse(final DOMSource src) throws XMLStreamException, URISyntaxException, IOException,
375 return parse(new DOMSourceXMLStreamReader(src));
378 private ImmutableMap<QName, Object> getElementAttributes(final XMLStreamReader in) {
379 checkState(in.isStartElement(), "Attributes can be extracted only from START_ELEMENT.");
380 final Map<QName, Object> attributes = new LinkedHashMap<>();
382 for (int attrIndex = 0; attrIndex < in.getAttributeCount(); attrIndex++) {
383 final String attributeNS = in.getAttributeNamespace(attrIndex);
385 // Skip namespace definitions
386 if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attributeNS)) {
390 final String localName = in.getAttributeLocalName(attrIndex);
391 final String attrValue = in.getAttributeValue(attrIndex);
392 if (Strings.isNullOrEmpty(attributeNS)) {
393 StreamWriterFacade.warnLegacyAttribute(localName);
394 attributes.put(QName.create(LEGACY_ATTRIBUTE_NAMESPACE, localName), attrValue);
398 // Cross-relate attribute namespace to the module
399 final Optional<QNameModule> optModule = resolveXmlNamespace(attributeNS);
400 if (optModule.isPresent()) {
401 final QName qname = QName.create(optModule.orElseThrow(), localName);
402 final var optAnnotation = AnnotationSchemaNode.find(codecs.getEffectiveModelContext(), qname);
403 if (optAnnotation.isPresent()) {
404 final AnnotationSchemaNode schema = optAnnotation.orElseThrow();
405 final Object value = codecs.codecFor(schema, stack)
406 .parseValue(in.getNamespaceContext(), attrValue);
407 attributes.put(schema.getQName(), value);
411 LOG.debug("Annotation for {} not found, using legacy QName", qname);
414 attributes.put(QName.create(rawXmlNamespace(attributeNS), localName), attrValue);
417 return ImmutableMap.copyOf(attributes);
420 private static Document readAnyXmlValue(final XMLStreamReader in) throws XMLStreamException {
421 // Underlying reader might return null when asked for version, however when such reader is plugged into
422 // Stax -> DOM transformer, it fails with NPE due to null version. Use default xml version in such case.
423 final XMLStreamReader inWrapper;
424 if (in.getVersion() == null) {
425 inWrapper = new StreamReaderDelegate(in) {
427 public String getVersion() {
428 final String ver = super.getVersion();
429 return ver != null ? ver : XML_STANDARD_VERSION;
436 final DOMResult result = new DOMResult();
438 TRANSFORMER_FACTORY.newTransformer().transform(new StAXSource(inWrapper), result);
439 } catch (final TransformerException e) {
440 throw new XMLStreamException("Unable to read anyxml value", e);
442 return (Document) result.getNode();
445 private void read(final XMLStreamReader in, final AbstractNodeDataWithSchema<?> parent, final String rootElement)
446 throws XMLStreamException {
451 if (parent instanceof LeafNodeDataWithSchema || parent instanceof LeafListEntryNodeDataWithSchema) {
452 parent.setAttributes(getElementAttributes(in));
453 setValue((SimpleNodeDataWithSchema<?>) parent, in.getElementText().trim(), in.getNamespaceContext());
454 if (isNextEndDocument(in)) {
458 if (!isAtElement(in)) {
464 if (parent instanceof ListEntryNodeDataWithSchema || parent instanceof ContainerNodeDataWithSchema) {
465 parent.setAttributes(getElementAttributes(in));
468 if (parent instanceof LeafListNodeDataWithSchema || parent instanceof ListNodeDataWithSchema) {
469 final String localName = in.getLocalName();
470 final String namespaceURI = in.getNamespaceURI();
471 // aggregate current and subsequent nodes having same localName and namespace
472 // into set of entries belonging to current parent node
473 while (localName.equals(in.getLocalName()) && namespaceURI.equals(in.getNamespaceURI())) {
474 read(in, newEntryNode(parent), rootElement);
475 if (in.getEventType() == XMLStreamConstants.END_DOCUMENT
476 || in.getEventType() == XMLStreamConstants.END_ELEMENT) {
483 if (parent instanceof AnyXmlNodeDataWithSchema anyxml) {
484 setValue(anyxml, readAnyXmlValue(in), in.getNamespaceContext());
485 if (isNextEndDocument(in)) {
489 if (!isAtElement(in)) {
496 if (parent instanceof AnydataNodeDataWithSchema anydata) {
497 anydata.setObjectModel(DOMSourceAnydata.class);
498 anydata.setAttributes(getElementAttributes(in));
499 setValue(anydata, readAnyXmlValue(in), in.getNamespaceContext());
500 if (isNextEndDocument(in)) {
504 if (!isAtElement(in)) {
511 switch (in.nextTag()) {
512 case XMLStreamConstants.START_ELEMENT:
513 // FIXME: 7.0.0: why do we even need this tracker? either document it or remove it.
514 // it looks like it is a crude duplicate finder, which should really be handled via
515 // ChildReusePolicy.REJECT
516 final Set<Entry<String, String>> namesakes = new HashSet<>();
517 while (in.hasNext()) {
518 final String xmlElementName = in.getLocalName();
519 final DataSchemaNode parentSchema = parent.getSchema();
521 final String parentSchemaName = parentSchema.getQName().getLocalName();
522 if (parentSchemaName.equals(xmlElementName)
523 && in.getEventType() == XMLStreamConstants.END_ELEMENT) {
524 if (isNextEndDocument(in)) {
528 if (!isAtElement(in)) {
534 if (in.isEndElement() && rootElement.equals(xmlElementName)) {
538 final String elementNS = in.getNamespaceURI();
539 final boolean added = namesakes.add(new SimpleImmutableEntry<>(elementNS, xmlElementName));
541 final XMLNamespace nsUri;
543 nsUri = rawXmlNamespace(elementNS).getNamespace();
544 } catch (IllegalArgumentException e) {
545 throw new XMLStreamException("Failed to convert namespace " + xmlElementName, in.getLocation(),
549 final Deque<DataSchemaNode> childDataSchemaNodes =
550 ParserStreamUtils.findSchemaNodeByNameAndNamespace(parentSchema, xmlElementName, nsUri);
551 if (!childDataSchemaNodes.isEmpty()) {
552 final boolean elementList = isElementList(childDataSchemaNodes);
553 if (!added && !elementList) {
554 throw new XMLStreamException(String.format(
555 "Duplicate element \"%s\" in namespace \"%s\" with parent \"%s\" in XML input",
556 xmlElementName, elementNS, parentSchema), in.getLocation());
559 // We have a match, proceed with it
560 final QName qname = childDataSchemaNodes.peekLast().getQName();
561 final AbstractNodeDataWithSchema<?> child = ((CompositeNodeDataWithSchema<?>) parent).addChild(
562 childDataSchemaNodes, elementList ? ChildReusePolicy.REUSE : ChildReusePolicy.NOOP);
563 stack.enterDataTree(qname);
564 read(in, child, rootElement);
569 if (parent instanceof AbstractMountPointDataWithSchema<?> mountParent) {
570 // Parent can potentially hold a mount point, let's see if there is a label present
571 final Optional<MountPointSchemaNode> optMount;
572 if (parentSchema instanceof ContainerSchemaNode container) {
573 optMount = MountPointSchemaNode.streamAll(container).findFirst();
574 } else if (parentSchema instanceof ListSchemaNode list) {
575 optMount = MountPointSchemaNode.streamAll(list).findFirst();
577 throw new XMLStreamException("Unhandled mount-aware schema " + parentSchema,
581 if (optMount.isPresent()) {
582 final var mountId = MountPointIdentifier.of(optMount.orElseThrow().getQName());
583 LOG.debug("Assuming node {} and namespace {} belongs to mount point {}", xmlElementName,
586 final Optional<MountPointContextFactory> optFactory = codecs.mountPointContext()
587 .findMountPoint(mountId);
588 if (optFactory.isPresent()) {
589 final MountPointData mountData =
590 mountParent.getMountPointData(mountId, optFactory.orElseThrow());
591 addMountPointChild(mountData, nsUri, xmlElementName,
592 new DOMSource(readAnyXmlValue(in).getDocumentElement()));
596 LOG.debug("Mount point {} not attached", mountId);
600 // We have not handled the node -- let's decide what to do about that
602 throw new XMLStreamException(String.format(
603 "Schema for node with name %s and namespace %s does not exist in parent %s", xmlElementName,
604 elementNS, parentSchema), in.getLocation());
607 LOG.debug("Skipping unknown node ns=\"{}\" localName=\"{}\" in parent {}", elementNS,
608 xmlElementName, parentSchema);
612 case XMLStreamConstants.END_ELEMENT:
613 if (isNextEndDocument(in)) {
617 if (!isAtElement(in)) {
626 // Return true if schema represents a construct which uses multiple sibling elements to represent its content. The
627 // siblings MAY be interleaved as per RFC7950.
628 private static boolean isElementList(final Deque<DataSchemaNode> childDataSchemaNodes) {
629 final DataSchemaNode last = childDataSchemaNodes.getLast();
630 return last instanceof ListSchemaNode || last instanceof LeafListSchemaNode;
633 private static void addMountPointChild(final MountPointData mount, final XMLNamespace namespace,
634 final String localName, final DOMSource source) {
635 final DOMSourceMountPointChild child = new DOMSourceMountPointChild(source);
636 if (YangLibraryConstants.MODULE_NAMESPACE.equals(namespace)) {
637 final var optName = ContainerName.forLocalName(localName);
638 if (optName.isPresent()) {
639 mount.setContainer(optName.orElseThrow(), child);
643 LOG.warn("Encountered unknown element {} from YANG Library namespace", localName);
644 } else if (SchemaMountConstants.RFC8528_MODULE.getNamespace().equals(namespace)) {
645 mount.setSchemaMounts(child);
649 mount.addChild(child);
652 private static boolean isNextEndDocument(final XMLStreamReader in) throws XMLStreamException {
653 return !in.hasNext() || in.next() == XMLStreamConstants.END_DOCUMENT;
656 private static boolean isAtElement(final XMLStreamReader in) {
657 return in.getEventType() == XMLStreamConstants.START_ELEMENT
658 || in.getEventType() == XMLStreamConstants.END_ELEMENT;
661 private static void skipUnknownNode(final XMLStreamReader in) throws XMLStreamException {
662 // in case when the unknown node and at least one of its descendant nodes have the same name
663 // we cannot properly reach the end just by checking if the current node is an end element and has the same name
664 // as the root unknown element. therefore we ignore the names completely and just track the level of nesting
665 int levelOfNesting = 0;
666 while (in.hasNext()) {
667 // in case there are text characters in an element, we cannot skip them by calling nextTag()
668 // therefore we skip them by calling next(), and then proceed to next element
670 if (!isAtElement(in)) {
673 if (in.isStartElement()) {
677 if (in.isEndElement()) {
678 if (levelOfNesting == 0) {
689 private void setValue(final SimpleNodeDataWithSchema<?> parent, final Object value,
690 final NamespaceContext nsContext) {
691 final DataSchemaNode schema = parent.getSchema();
692 final Object prev = parent.getValue();
693 checkArgument(prev == null, "Node '%s' has already set its value to '%s'", schema.getQName(), prev);
694 parent.setValue(translateValueByType(value, schema, nsContext));
697 private Object translateValueByType(final Object value, final DataSchemaNode node,
698 final NamespaceContext namespaceCtx) {
699 if (node instanceof AnyxmlSchemaNode) {
700 checkArgument(value instanceof Document);
702 * FIXME: Figure out some YANG extension dispatch, which will reuse JSON parsing or XML parsing -
703 * anyxml is not well-defined in JSON.
705 return new DOMSource(((Document) value).getDocumentElement());
707 if (node instanceof AnydataSchemaNode) {
708 checkArgument(value instanceof Document);
709 return new DOMSourceAnydata(new DOMSource(((Document) value).getDocumentElement()));
712 checkArgument(node instanceof TypedDataSchemaNode);
713 checkArgument(value instanceof String);
714 return codecs.codecFor((TypedDataSchemaNode) node, stack).parseValue(namespaceCtx, (String) value);
717 private static AbstractNodeDataWithSchema<?> newEntryNode(final AbstractNodeDataWithSchema<?> parent) {
718 verify(parent instanceof MultipleEntryDataWithSchema, "Unexpected parent %s", parent);
719 return ((MultipleEntryDataWithSchema<?>) parent).newChildEntry();
723 public void close() throws IOException {
729 public void flush() throws IOException {
733 private Optional<QNameModule> resolveXmlNamespace(final String xmlNamespace) {
734 return resolvedNamespaces.computeIfAbsent(xmlNamespace, nsUri -> {
735 final Iterator<? extends Module> it = codecs.getEffectiveModelContext().findModules(XMLNamespace.of(nsUri))
737 return it.hasNext() ? Optional.of(it.next().getQNameModule()) : Optional.empty();
741 private QNameModule rawXmlNamespace(final String xmlNamespace) {
742 return rawNamespaces.computeIfAbsent(xmlNamespace, nsUri -> QNameModule.create(XMLNamespace.of(nsUri)));