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.HashMap;
26 import java.util.HashSet;
27 import java.util.Iterator;
28 import java.util.LinkedHashMap;
30 import java.util.Map.Entry;
31 import java.util.Optional;
33 import javax.xml.XMLConstants;
34 import javax.xml.namespace.NamespaceContext;
35 import javax.xml.stream.XMLStreamConstants;
36 import javax.xml.stream.XMLStreamException;
37 import javax.xml.stream.XMLStreamReader;
38 import javax.xml.stream.util.StreamReaderDelegate;
39 import javax.xml.transform.TransformerException;
40 import javax.xml.transform.TransformerFactory;
41 import javax.xml.transform.TransformerFactoryConfigurationError;
42 import javax.xml.transform.dom.DOMResult;
43 import javax.xml.transform.dom.DOMSource;
44 import javax.xml.transform.stax.StAXSource;
45 import org.opendaylight.yangtools.odlext.model.api.YangModeledAnyxmlSchemaNode;
46 import org.opendaylight.yangtools.rfc7952.model.api.AnnotationSchemaNode;
47 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
48 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContextFactory;
49 import org.opendaylight.yangtools.rfc8528.data.api.MountPointIdentifier;
50 import org.opendaylight.yangtools.rfc8528.data.api.YangLibraryConstants;
51 import org.opendaylight.yangtools.rfc8528.data.api.YangLibraryConstants.ContainerName;
52 import org.opendaylight.yangtools.rfc8528.model.api.MountPointSchemaNode;
53 import org.opendaylight.yangtools.rfc8528.model.api.SchemaMountConstants;
54 import org.opendaylight.yangtools.yang.common.QName;
55 import org.opendaylight.yangtools.yang.common.QNameModule;
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.LeafListEntryNodeDataWithSchema;
65 import org.opendaylight.yangtools.yang.data.util.LeafListNodeDataWithSchema;
66 import org.opendaylight.yangtools.yang.data.util.LeafNodeDataWithSchema;
67 import org.opendaylight.yangtools.yang.data.util.ListEntryNodeDataWithSchema;
68 import org.opendaylight.yangtools.yang.data.util.ListNodeDataWithSchema;
69 import org.opendaylight.yangtools.yang.data.util.MountPointData;
70 import org.opendaylight.yangtools.yang.data.util.MultipleEntryDataWithSchema;
71 import org.opendaylight.yangtools.yang.data.util.OperationAsContainer;
72 import org.opendaylight.yangtools.yang.data.util.ParserStreamUtils;
73 import org.opendaylight.yangtools.yang.data.util.SimpleNodeDataWithSchema;
74 import org.opendaylight.yangtools.yang.data.util.YangModeledAnyXmlNodeDataWithSchema;
75 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
76 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
77 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
78 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
79 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
80 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.Module;
84 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
85 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
87 import org.slf4j.Logger;
88 import org.slf4j.LoggerFactory;
89 import org.w3c.dom.Document;
90 import org.xml.sax.SAXException;
93 * This class provides functionality for parsing an XML source containing YANG-modeled data. It disallows multiple
94 * instances of the same element except for leaf-list and list entries. It also expects that the YANG-modeled data in
95 * the XML source are wrapped in a root element. This class is NOT thread-safe.
98 * Due to backwards compatibility reasons, RFC7952 metadata emitted by this parser may include key QNames with empty URI
99 * (as exposed via {@link #LEGACY_ATTRIBUTE_NAMESPACE}) as their QNameModule. These indicate an unqualified XML
100 * attribute and their value can be assumed to be a String. Furthermore, this extends to qualified attributes, which
101 * uses the proper namespace, but will not bind to a proper module revision -- these need to be reconciled with a
102 * particular SchemaContext and are expected to either be fully decoded, or contain a String value. Handling of such
103 * annotations is at the discretion of the user encountering it: preferred way of handling is to either filter or
104 * normalize them to proper QNames/values when encountered. This caveat will be removed in a future version.
107 public final class XmlParserStream implements Closeable, Flushable {
109 * {@link QNameModule} for use with legacy XML attributes.
110 * @deprecated The use on this namespace is discouraged and users are strongly encouraged to proper RFC7952 metadata
114 public static final QNameModule LEGACY_ATTRIBUTE_NAMESPACE = QNameModule.create(URI.create("")).intern();
116 private static final Logger LOG = LoggerFactory.getLogger(XmlParserStream.class);
117 private static final String XML_STANDARD_VERSION = "1.0";
118 private static final String COM_SUN_TRANSFORMER =
119 "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
121 private static final TransformerFactory TRANSFORMER_FACTORY;
124 TransformerFactory fa = TransformerFactory.newInstance();
125 if (!fa.getFeature(StAXSource.FEATURE)) {
126 LOG.warn("Platform-default TransformerFactory {} does not support StAXSource, attempting fallback to {}",
127 fa, COM_SUN_TRANSFORMER);
128 fa = TransformerFactory.newInstance(COM_SUN_TRANSFORMER, null);
129 if (!fa.getFeature(StAXSource.FEATURE)) {
130 throw new TransformerFactoryConfigurationError("No TransformerFactory supporting StAXResult found.");
134 TRANSFORMER_FACTORY = fa;
137 // Cache of nsUri Strings to QNameModules, as resolved in context
138 private final Map<String, Optional<QNameModule>> resolvedNamespaces = new HashMap<>();
139 // Cache of nsUri Strings to QNameModules, as inferred from document
140 private final Map<String, QNameModule> rawNamespaces = new HashMap<>();
141 private final NormalizedNodeStreamWriter writer;
142 private final XmlCodecFactory codecs;
143 private final DataSchemaNode parentNode;
144 private final boolean strictParsing;
146 private XmlParserStream(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
147 final DataSchemaNode parentNode, final boolean strictParsing) {
148 this.writer = requireNonNull(writer);
149 this.codecs = requireNonNull(codecs);
150 this.parentNode = parentNode;
151 this.strictParsing = strictParsing;
155 * Construct a new {@link XmlParserStream} with strict parsing mode switched on.
157 * @param writer Output writer
158 * @param codecs Shared codecs
159 * @param parentNode Parent root node
160 * @return A new stream instance
162 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
163 final SchemaNode parentNode) {
164 return create(writer, codecs, parentNode, true);
168 * Construct a new {@link XmlParserStream}.
170 * @param writer Output writer
171 * @param codecs Shared codecs
172 * @param parentNode Parent root node
173 * @param strictParsing parsing mode
174 * if set to true, the parser will throw an exception if it encounters unknown child nodes
175 * (nodes, that are not defined in the provided SchemaContext) in containers and lists
176 * if set to false, the parser will skip unknown child nodes
177 * @return A new stream instance
179 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
180 final SchemaNode parentNode, final boolean strictParsing) {
181 final DataSchemaNode parent;
182 if (parentNode instanceof DataSchemaNode) {
183 parent = (DataSchemaNode) parentNode;
184 } else if (parentNode instanceof OperationDefinition) {
185 parent = OperationAsContainer.of((OperationDefinition) parentNode);
187 throw new IllegalArgumentException("Illegal parent node " + parentNode);
189 return new XmlParserStream(writer, codecs, parent, strictParsing);
193 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
194 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
195 * maintain a {@link XmlCodecFactory} to match the current {@link EffectiveModelContext}.
197 public static XmlParserStream create(final NormalizedNodeStreamWriter writer,
198 final EffectiveModelContext schemaContext, final SchemaNode parentNode) {
199 return create(writer, schemaContext, parentNode, true);
203 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
204 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
205 * maintain a {@link XmlCodecFactory} to match the current {@link EffectiveModelContext}.
207 public static XmlParserStream create(final NormalizedNodeStreamWriter writer,
208 final EffectiveModelContext schemaContext, final SchemaNode parentNode, final boolean strictParsing) {
209 return create(writer, XmlCodecFactory.create(schemaContext), parentNode, strictParsing);
213 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
214 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
215 * maintain a {@link XmlCodecFactory} to match the current {@link MountPointContext}.
217 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
218 final SchemaNode parentNode) {
219 return create(writer, mountCtx, parentNode, true);
223 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
224 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
225 * maintain a {@link XmlCodecFactory} to match the current {@link MountPointContext}.
227 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
228 final SchemaNode parentNode, final boolean strictParsing) {
229 return create(writer, XmlCodecFactory.create(mountCtx), parentNode, strictParsing);
233 * This method parses the XML source and emits node events into a NormalizedNodeStreamWriter based on the
234 * YANG-modeled data contained in the XML source.
237 * StAX reader which is to used to walk through the XML source
239 * instance of XmlParserStream
240 * @throws XMLStreamException
241 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
242 * @throws URISyntaxException
243 * if the namespace URI of an XML element contains a syntax error
244 * @throws IOException
245 * if an error occurs while parsing the value of an anyxml node
246 * @throws SAXException
247 * if an error occurs while parsing the value of an anyxml node
249 public XmlParserStream parse(final XMLStreamReader reader) throws XMLStreamException, URISyntaxException,
250 IOException, SAXException {
251 if (reader.hasNext()) {
253 final AbstractNodeDataWithSchema<?> nodeDataWithSchema;
254 if (parentNode instanceof ContainerSchemaNode) {
255 nodeDataWithSchema = new ContainerNodeDataWithSchema((ContainerSchemaNode) parentNode);
256 } else if (parentNode instanceof ListSchemaNode) {
257 nodeDataWithSchema = new ListNodeDataWithSchema((ListSchemaNode) parentNode);
258 } else if (parentNode instanceof YangModeledAnyxmlSchemaNode) {
259 nodeDataWithSchema = new YangModeledAnyXmlNodeDataWithSchema((YangModeledAnyxmlSchemaNode) parentNode);
260 } else if (parentNode instanceof AnyxmlSchemaNode) {
261 nodeDataWithSchema = new AnyXmlNodeDataWithSchema((AnyxmlSchemaNode) parentNode);
262 } else if (parentNode instanceof LeafSchemaNode) {
263 nodeDataWithSchema = new LeafNodeDataWithSchema((LeafSchemaNode) parentNode);
264 } else if (parentNode instanceof LeafListSchemaNode) {
265 nodeDataWithSchema = new LeafListNodeDataWithSchema((LeafListSchemaNode) parentNode);
266 } else if (parentNode instanceof AnydataSchemaNode) {
267 nodeDataWithSchema = new AnydataNodeDataWithSchema((AnydataSchemaNode) parentNode);
269 throw new IllegalStateException("Unsupported schema node type " + parentNode.getClass() + ".");
272 read(reader, nodeDataWithSchema, reader.getLocalName());
273 nodeDataWithSchema.write(writer);
280 * This method traverses a {@link DOMSource} and emits node events into a NormalizedNodeStreamWriter based on the
281 * YANG-modeled data contained in the source.
284 * {@link DOMSource} to be traversed
286 * instance of XmlParserStream
287 * @throws XMLStreamException
288 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
289 * @throws URISyntaxException
290 * if the namespace URI of an XML element contains a syntax error
291 * @throws IOException
292 * if an error occurs while parsing the value of an anyxml node
293 * @throws SAXException
294 * if an error occurs while parsing the value of an anyxml node
297 public XmlParserStream traverse(final DOMSource src) throws XMLStreamException, URISyntaxException, IOException,
299 return parse(new DOMSourceXMLStreamReader(src));
302 private ImmutableMap<QName, Object> getElementAttributes(final XMLStreamReader in) {
303 checkState(in.isStartElement(), "Attributes can be extracted only from START_ELEMENT.");
304 final Map<QName, Object> attributes = new LinkedHashMap<>();
306 for (int attrIndex = 0; attrIndex < in.getAttributeCount(); attrIndex++) {
307 final String attributeNS = in.getAttributeNamespace(attrIndex);
309 // Skip namespace definitions
310 if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attributeNS)) {
314 final String localName = in.getAttributeLocalName(attrIndex);
315 final String attrValue = in.getAttributeValue(attrIndex);
316 if (Strings.isNullOrEmpty(attributeNS)) {
317 StreamWriterFacade.warnLegacyAttribute(localName);
318 attributes.put(QName.create(LEGACY_ATTRIBUTE_NAMESPACE, localName), attrValue);
322 // Cross-relate attribute namespace to the module
323 final Optional<QNameModule> optModule = resolveXmlNamespace(attributeNS);
324 if (optModule.isPresent()) {
325 final QName qname = QName.create(optModule.get(), localName);
326 final Optional<AnnotationSchemaNode> optAnnotation = AnnotationSchemaNode.find(
327 codecs.getSchemaContext(), qname);
328 if (optAnnotation.isPresent()) {
329 final AnnotationSchemaNode schema = optAnnotation.get();
330 final Object value = codecs.codecFor(schema).parseValue(in.getNamespaceContext(), attrValue);
331 attributes.put(schema.getQName(), value);
335 LOG.debug("Annotation for {} not found, using legacy QName", qname);
338 attributes.put(QName.create(rawXmlNamespace(attributeNS), localName), attrValue);
341 return ImmutableMap.copyOf(attributes);
344 private static Document readAnyXmlValue(final XMLStreamReader in) throws XMLStreamException {
345 // Underlying reader might return null when asked for version, however when such reader is plugged into
346 // Stax -> DOM transformer, it fails with NPE due to null version. Use default xml version in such case.
347 final XMLStreamReader inWrapper;
348 if (in.getVersion() == null) {
349 inWrapper = new StreamReaderDelegate(in) {
351 public String getVersion() {
352 final String ver = super.getVersion();
353 return ver != null ? ver : XML_STANDARD_VERSION;
360 final DOMResult result = new DOMResult();
362 TRANSFORMER_FACTORY.newTransformer().transform(new StAXSource(inWrapper), result);
363 } catch (final TransformerException e) {
364 throw new XMLStreamException("Unable to read anyxml value", e);
366 return (Document) result.getNode();
369 private void read(final XMLStreamReader in, final AbstractNodeDataWithSchema<?> parent, final String rootElement)
370 throws XMLStreamException {
375 if (parent instanceof LeafNodeDataWithSchema || parent instanceof LeafListEntryNodeDataWithSchema) {
376 parent.setAttributes(getElementAttributes(in));
377 setValue((SimpleNodeDataWithSchema<?>) parent, in.getElementText().trim(), in.getNamespaceContext());
378 if (isNextEndDocument(in)) {
382 if (!isAtElement(in)) {
388 if (parent instanceof ListEntryNodeDataWithSchema || parent instanceof ContainerNodeDataWithSchema) {
389 parent.setAttributes(getElementAttributes(in));
392 if (parent instanceof LeafListNodeDataWithSchema || parent instanceof ListNodeDataWithSchema) {
393 String xmlElementName = in.getLocalName();
394 while (xmlElementName.equals(parent.getSchema().getQName().getLocalName())) {
395 read(in, newEntryNode(parent), rootElement);
396 if (in.getEventType() == XMLStreamConstants.END_DOCUMENT
397 || in.getEventType() == XMLStreamConstants.END_ELEMENT) {
400 xmlElementName = in.getLocalName();
406 if (parent instanceof AnyXmlNodeDataWithSchema) {
407 setValue((AnyXmlNodeDataWithSchema) parent, readAnyXmlValue(in), in.getNamespaceContext());
408 if (isNextEndDocument(in)) {
412 if (!isAtElement(in)) {
419 if (parent instanceof AnydataNodeDataWithSchema) {
420 final AnydataNodeDataWithSchema anydata = (AnydataNodeDataWithSchema) parent;
421 anydata.setObjectModel(DOMSourceAnydata.class);
422 anydata.setAttributes(getElementAttributes(in));
423 setValue(anydata, readAnyXmlValue(in), in.getNamespaceContext());
424 if (isNextEndDocument(in)) {
428 if (!isAtElement(in)) {
435 if (parent instanceof YangModeledAnyxmlSchemaNode) {
436 parent.setAttributes(getElementAttributes(in));
439 switch (in.nextTag()) {
440 case XMLStreamConstants.START_ELEMENT:
441 // FIXME: 6.0.0: why do we even need this tracker? either document it or remove it.
442 // it looks like it is a crude duplicate finder, which should really be handled via
443 // ChildReusePolicy.REJECT
444 final Set<Entry<String, String>> namesakes = new HashSet<>();
445 while (in.hasNext()) {
446 final String xmlElementName = in.getLocalName();
448 DataSchemaNode parentSchema = parent.getSchema();
450 final String parentSchemaName = parentSchema.getQName().getLocalName();
451 if (parentSchemaName.equals(xmlElementName)
452 && in.getEventType() == XMLStreamConstants.END_ELEMENT) {
453 if (isNextEndDocument(in)) {
457 if (!isAtElement(in)) {
463 if (in.isEndElement() && rootElement.equals(xmlElementName)) {
467 if (parentSchema instanceof YangModeledAnyxmlSchemaNode) {
468 parentSchema = ((YangModeledAnyxmlSchemaNode) parentSchema).getSchemaOfAnyXmlData();
471 final String elementNS = in.getNamespaceURI();
472 final boolean added = namesakes.add(new SimpleImmutableEntry<>(elementNS, xmlElementName));
476 nsUri = rawXmlNamespace(elementNS).getNamespace();
477 } catch (IllegalArgumentException e) {
478 throw new XMLStreamException("Failed to convert namespace " + xmlElementName, in.getLocation(),
482 final Deque<DataSchemaNode> childDataSchemaNodes =
483 ParserStreamUtils.findSchemaNodeByNameAndNamespace(parentSchema, xmlElementName, nsUri);
484 if (!childDataSchemaNodes.isEmpty()) {
485 final boolean elementList = isElementList(childDataSchemaNodes);
486 if (!added && !elementList) {
487 throw new XMLStreamException(String.format(
488 "Duplicate element \"%s\" in namespace \"%s\" with parent \"%s\" in XML input",
489 xmlElementName, elementNS, parent.getSchema()), in.getLocation());
492 // We have a match, proceed with it
493 read(in, ((CompositeNodeDataWithSchema<?>) parent).addChild(childDataSchemaNodes,
494 elementList ? ChildReusePolicy.REUSE : ChildReusePolicy.NOOP), rootElement);
498 if (parent instanceof AbstractMountPointDataWithSchema) {
499 // Parent can potentially hold a mount point, let's see if there is a label present
500 final Optional<MountPointSchemaNode> optMount;
501 if (parentSchema instanceof ContainerSchemaNode) {
502 optMount = MountPointSchemaNode.streamAll((ContainerSchemaNode) parentSchema).findFirst();
503 } else if (parentSchema instanceof ListSchemaNode) {
504 optMount = MountPointSchemaNode.streamAll((ListSchemaNode) parentSchema).findFirst();
506 throw new XMLStreamException("Unhandled mount-aware schema " + parentSchema);
509 if (optMount.isPresent()) {
510 final MountPointIdentifier mountId = MountPointIdentifier.of(optMount.get().getQName());
511 LOG.debug("Assuming node {} and namespace {} belongs to mount point {}", xmlElementName,
514 final Optional<MountPointContextFactory> optFactory = codecs.mountPointContext()
515 .findMountPoint(mountId);
516 if (optFactory.isPresent()) {
517 final MountPointData mountData = ((AbstractMountPointDataWithSchema<?>) parent)
518 .getMountPointData(mountId, optFactory.get());
519 addMountPointChild(mountData, nsUri, xmlElementName,
520 new DOMSource(readAnyXmlValue(in).getDocumentElement()));
524 LOG.debug("Mount point {} not attached", mountId);
528 // We have not handled the node -- let's decide what to do about that
530 throw new XMLStreamException(String.format(
531 "Schema for node with name %s and namespace %s does not exist at %s", xmlElementName,
532 elementNS, parentSchema.getPath(), in.getLocation()));
535 LOG.debug("Skipping unknown node ns=\"{}\" localName=\"{}\" at path {}", elementNS, xmlElementName,
536 parentSchema.getPath());
540 case XMLStreamConstants.END_ELEMENT:
541 if (isNextEndDocument(in)) {
545 if (!isAtElement(in)) {
554 // Return true if schema represents a construct which uses multiple sibling elements to represent its content. The
555 // siblings MAY be interleaved as per RFC7950.
556 private static boolean isElementList(final Deque<DataSchemaNode> childDataSchemaNodes) {
557 final DataSchemaNode last = childDataSchemaNodes.getLast();
558 return last instanceof ListSchemaNode || last instanceof LeafListSchemaNode;
561 private static void addMountPointChild(final MountPointData mount, final URI namespace, final String localName,
562 final DOMSource source) {
563 final DOMSourceMountPointChild child = new DOMSourceMountPointChild(source);
564 if (YangLibraryConstants.MODULE_NAMESPACE.equals(namespace)) {
565 final Optional<ContainerName> optName = ContainerName.forLocalName(localName);
566 if (optName.isPresent()) {
567 mount.setContainer(optName.get(), child);
571 LOG.warn("Encountered unknown element {} from YANG Library namespace", localName);
572 } else if (SchemaMountConstants.RFC8528_MODULE.getNamespace().equals(namespace)) {
573 mount.setSchemaMounts(child);
577 mount.addChild(child);
580 private static boolean isNextEndDocument(final XMLStreamReader in) throws XMLStreamException {
581 return !in.hasNext() || in.next() == XMLStreamConstants.END_DOCUMENT;
584 private static boolean isAtElement(final XMLStreamReader in) {
585 return in.getEventType() == XMLStreamConstants.START_ELEMENT
586 || in.getEventType() == XMLStreamConstants.END_ELEMENT;
589 private static void skipUnknownNode(final XMLStreamReader in) throws XMLStreamException {
590 // in case when the unknown node and at least one of its descendant nodes have the same name
591 // we cannot properly reach the end just by checking if the current node is an end element and has the same name
592 // as the root unknown element. therefore we ignore the names completely and just track the level of nesting
593 int levelOfNesting = 0;
594 while (in.hasNext()) {
595 // in case there are text characters in an element, we cannot skip them by calling nextTag()
596 // therefore we skip them by calling next(), and then proceed to next element
598 if (!isAtElement(in)) {
601 if (in.isStartElement()) {
605 if (in.isEndElement()) {
606 if (levelOfNesting == 0) {
617 private void setValue(final SimpleNodeDataWithSchema<?> parent, final Object value,
618 final NamespaceContext nsContext) {
619 final DataSchemaNode schema = parent.getSchema();
620 final Object prev = parent.getValue();
621 checkArgument(prev == null, "Node '%s' has already set its value to '%s'", schema.getQName(), prev);
622 parent.setValue(translateValueByType(value, schema, nsContext));
625 private Object translateValueByType(final Object value, final DataSchemaNode node,
626 final NamespaceContext namespaceCtx) {
627 if (node instanceof AnyxmlSchemaNode) {
628 checkArgument(value instanceof Document);
630 * FIXME: Figure out some YANG extension dispatch, which will reuse JSON parsing or XML parsing -
631 * anyxml is not well-defined in JSON.
633 return new DOMSource(((Document) value).getDocumentElement());
635 if (node instanceof AnydataSchemaNode) {
636 checkArgument(value instanceof Document);
637 return new DOMSourceAnydata(new DOMSource(((Document) value).getDocumentElement()));
640 checkArgument(node instanceof TypedDataSchemaNode);
641 checkArgument(value instanceof String);
642 return codecs.codecFor((TypedDataSchemaNode) node).parseValue(namespaceCtx, (String) value);
645 private static AbstractNodeDataWithSchema<?> newEntryNode(final AbstractNodeDataWithSchema<?> parent) {
646 verify(parent instanceof MultipleEntryDataWithSchema, "Unexpected parent %s", parent);
647 return ((MultipleEntryDataWithSchema<?>) parent).newChildEntry();
651 public void close() throws IOException {
657 public void flush() throws IOException {
661 private Optional<QNameModule> resolveXmlNamespace(final String xmlNamespace) {
662 return resolvedNamespaces.computeIfAbsent(xmlNamespace, nsUri -> {
663 final Iterator<? extends Module> it = codecs.getSchemaContext().findModules(URI.create(nsUri)).iterator();
664 return it.hasNext() ? Optional.of(it.next().getQNameModule()) : Optional.empty();
668 private QNameModule rawXmlNamespace(final String xmlNamespace) {
669 return rawNamespaces.computeIfAbsent(xmlNamespace, nsUri -> QNameModule.create(URI.create(nsUri)));