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.ContainerNodeDataWithSchema;
63 import org.opendaylight.yangtools.yang.data.util.LeafListEntryNodeDataWithSchema;
64 import org.opendaylight.yangtools.yang.data.util.LeafListNodeDataWithSchema;
65 import org.opendaylight.yangtools.yang.data.util.LeafNodeDataWithSchema;
66 import org.opendaylight.yangtools.yang.data.util.ListEntryNodeDataWithSchema;
67 import org.opendaylight.yangtools.yang.data.util.ListNodeDataWithSchema;
68 import org.opendaylight.yangtools.yang.data.util.MountPointData;
69 import org.opendaylight.yangtools.yang.data.util.MultipleEntryDataWithSchema;
70 import org.opendaylight.yangtools.yang.data.util.OperationAsContainer;
71 import org.opendaylight.yangtools.yang.data.util.ParserStreamUtils;
72 import org.opendaylight.yangtools.yang.data.util.SimpleNodeDataWithSchema;
73 import org.opendaylight.yangtools.yang.data.util.YangModeledAnyXmlNodeDataWithSchema;
74 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
75 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
76 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
77 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
78 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
79 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
80 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.Module;
82 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
83 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
84 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
86 import org.slf4j.Logger;
87 import org.slf4j.LoggerFactory;
88 import org.w3c.dom.Document;
89 import org.xml.sax.SAXException;
92 * This class provides functionality for parsing an XML source containing YANG-modeled data. It disallows multiple
93 * instances of the same element except for leaf-list and list entries. It also expects that the YANG-modeled data in
94 * the XML source are wrapped in a root element. This class is NOT thread-safe.
97 * Due to backwards compatibility reasons, RFC7952 metadata emitted by this parser may include key QNames with empty URI
98 * (as exposed via {@link #LEGACY_ATTRIBUTE_NAMESPACE}) as their QNameModule. These indicate an unqualified XML
99 * attribute and their value can be assumed to be a String. Furthermore, this extends to qualified attributes, which
100 * uses the proper namespace, but will not bind to a proper module revision -- these need to be reconciled with a
101 * particular SchemaContext and are expected to either be fully decoded, or contain a String value. Handling of such
102 * annotations is at the discretion of the user encountering it: preferred way of handling is to either filter or
103 * normalize them to proper QNames/values when encountered. This caveat will be removed in a future version.
106 public final class XmlParserStream implements Closeable, Flushable {
108 * {@link QNameModule} for use with legacy XML attributes.
109 * @deprecated The use on this namespace is discouraged and users are strongly encouraged to proper RFC7952 metadata
113 public static final QNameModule LEGACY_ATTRIBUTE_NAMESPACE = QNameModule.create(URI.create("")).intern();
115 private static final Logger LOG = LoggerFactory.getLogger(XmlParserStream.class);
116 private static final String XML_STANDARD_VERSION = "1.0";
117 private static final String COM_SUN_TRANSFORMER =
118 "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
120 private static final TransformerFactory TRANSFORMER_FACTORY;
123 TransformerFactory fa = TransformerFactory.newInstance();
124 if (!fa.getFeature(StAXSource.FEATURE)) {
125 LOG.warn("Platform-default TransformerFactory {} does not support StAXSource, attempting fallback to {}",
126 fa, COM_SUN_TRANSFORMER);
127 fa = TransformerFactory.newInstance(COM_SUN_TRANSFORMER, null);
128 if (!fa.getFeature(StAXSource.FEATURE)) {
129 throw new TransformerFactoryConfigurationError("No TransformerFactory supporting StAXResult found.");
133 TRANSFORMER_FACTORY = fa;
136 // Cache of nsUri Strings to QNameModules, as resolved in context
137 private final Map<String, Optional<QNameModule>> resolvedNamespaces = new HashMap<>();
138 // Cache of nsUri Strings to QNameModules, as inferred from document
139 private final Map<String, QNameModule> rawNamespaces = new HashMap<>();
140 private final NormalizedNodeStreamWriter writer;
141 private final XmlCodecFactory codecs;
142 private final DataSchemaNode parentNode;
143 private final boolean strictParsing;
145 private XmlParserStream(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
146 final DataSchemaNode parentNode, final boolean strictParsing) {
147 this.writer = requireNonNull(writer);
148 this.codecs = requireNonNull(codecs);
149 this.parentNode = parentNode;
150 this.strictParsing = strictParsing;
154 * Construct a new {@link XmlParserStream} with strict parsing mode switched on.
156 * @param writer Output writer
157 * @param codecs Shared codecs
158 * @param parentNode Parent root node
159 * @return A new stream instance
161 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
162 final SchemaNode parentNode) {
163 return create(writer, codecs, parentNode, true);
167 * Construct a new {@link XmlParserStream}.
169 * @param writer Output writer
170 * @param codecs Shared codecs
171 * @param parentNode Parent root node
172 * @param strictParsing parsing mode
173 * if set to true, the parser will throw an exception if it encounters unknown child nodes
174 * (nodes, that are not defined in the provided SchemaContext) in containers and lists
175 * if set to false, the parser will skip unknown child nodes
176 * @return A new stream instance
178 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
179 final SchemaNode parentNode, final boolean strictParsing) {
180 final DataSchemaNode parent;
181 if (parentNode instanceof DataSchemaNode) {
182 parent = (DataSchemaNode) parentNode;
183 } else if (parentNode instanceof OperationDefinition) {
184 parent = OperationAsContainer.of((OperationDefinition) parentNode);
186 throw new IllegalArgumentException("Illegal parent node " + parentNode);
188 return new XmlParserStream(writer, codecs, parent, strictParsing);
192 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
193 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
194 * maintain a {@link XmlCodecFactory} to match the current {@link SchemaContext}.
196 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
197 final SchemaNode parentNode) {
198 return create(writer, schemaContext, parentNode, true);
202 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
203 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
204 * maintain a {@link XmlCodecFactory} to match the current {@link SchemaContext}.
206 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext,
207 final SchemaNode parentNode, final boolean strictParsing) {
208 return create(writer, XmlCodecFactory.create(schemaContext), parentNode, strictParsing);
212 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
213 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
214 * maintain a {@link XmlCodecFactory} to match the current {@link MountPointContext}.
216 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
217 final SchemaNode parentNode) {
218 return create(writer, mountCtx, parentNode, true);
222 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
223 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
224 * maintain a {@link XmlCodecFactory} to match the current {@link MountPointContext}.
226 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
227 final SchemaNode parentNode, final boolean strictParsing) {
228 return create(writer, XmlCodecFactory.create(mountCtx), parentNode, strictParsing);
232 * This method parses the XML source and emits node events into a NormalizedNodeStreamWriter based on the
233 * YANG-modeled data contained in the XML source.
236 * StAX reader which is to used to walk through the XML source
238 * instance of XmlParserStream
239 * @throws XMLStreamException
240 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
241 * @throws URISyntaxException
242 * if the namespace URI of an XML element contains a syntax error
243 * @throws IOException
244 * if an error occurs while parsing the value of an anyxml node
245 * @throws SAXException
246 * if an error occurs while parsing the value of an anyxml node
248 public XmlParserStream parse(final XMLStreamReader reader) throws XMLStreamException, URISyntaxException,
249 IOException, SAXException {
250 if (reader.hasNext()) {
252 final AbstractNodeDataWithSchema<?> nodeDataWithSchema;
253 if (parentNode instanceof ContainerSchemaNode) {
254 nodeDataWithSchema = new ContainerNodeDataWithSchema((ContainerSchemaNode) parentNode);
255 } else if (parentNode instanceof ListSchemaNode) {
256 nodeDataWithSchema = new ListNodeDataWithSchema((ListSchemaNode) parentNode);
257 } else if (parentNode instanceof YangModeledAnyxmlSchemaNode) {
258 nodeDataWithSchema = new YangModeledAnyXmlNodeDataWithSchema((YangModeledAnyxmlSchemaNode) parentNode);
259 } else if (parentNode instanceof AnyxmlSchemaNode) {
260 nodeDataWithSchema = new AnyXmlNodeDataWithSchema((AnyxmlSchemaNode) parentNode);
261 } else if (parentNode instanceof LeafSchemaNode) {
262 nodeDataWithSchema = new LeafNodeDataWithSchema((LeafSchemaNode) parentNode);
263 } else if (parentNode instanceof LeafListSchemaNode) {
264 nodeDataWithSchema = new LeafListNodeDataWithSchema((LeafListSchemaNode) parentNode);
265 } else if (parentNode instanceof AnydataSchemaNode) {
266 nodeDataWithSchema = new AnydataNodeDataWithSchema((AnydataSchemaNode) parentNode);
268 throw new IllegalStateException("Unsupported schema node type " + parentNode.getClass() + ".");
271 read(reader, nodeDataWithSchema, reader.getLocalName());
272 nodeDataWithSchema.write(writer);
279 * This method traverses a {@link DOMSource} and emits node events into a NormalizedNodeStreamWriter based on the
280 * YANG-modeled data contained in the source.
283 * {@link DOMSource} to be traversed
285 * instance of XmlParserStream
286 * @throws XMLStreamException
287 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
288 * @throws URISyntaxException
289 * if the namespace URI of an XML element contains a syntax error
290 * @throws IOException
291 * if an error occurs while parsing the value of an anyxml node
292 * @throws SAXException
293 * if an error occurs while parsing the value of an anyxml node
296 public XmlParserStream traverse(final DOMSource src) throws XMLStreamException, URISyntaxException, IOException,
298 return parse(new DOMSourceXMLStreamReader(src));
301 private ImmutableMap<QName, Object> getElementAttributes(final XMLStreamReader in) {
302 checkState(in.isStartElement(), "Attributes can be extracted only from START_ELEMENT.");
303 final Map<QName, Object> attributes = new LinkedHashMap<>();
305 for (int attrIndex = 0; attrIndex < in.getAttributeCount(); attrIndex++) {
306 final String attributeNS = in.getAttributeNamespace(attrIndex);
308 // Skip namespace definitions
309 if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attributeNS)) {
313 final String localName = in.getAttributeLocalName(attrIndex);
314 final String attrValue = in.getAttributeValue(attrIndex);
315 if (Strings.isNullOrEmpty(attributeNS)) {
316 StreamWriterFacade.warnLegacyAttribute(localName);
317 attributes.put(QName.create(LEGACY_ATTRIBUTE_NAMESPACE, localName), attrValue);
321 // Cross-relate attribute namespace to the module
322 final Optional<QNameModule> optModule = resolveXmlNamespace(attributeNS);
323 if (optModule.isPresent()) {
324 final QName qname = QName.create(optModule.get(), localName);
325 final Optional<AnnotationSchemaNode> optAnnotation = AnnotationSchemaNode.find(
326 codecs.getSchemaContext(), qname);
327 if (optAnnotation.isPresent()) {
328 final AnnotationSchemaNode schema = optAnnotation.get();
329 final Object value = codecs.codecFor(schema).parseValue(in.getNamespaceContext(), attrValue);
330 attributes.put(schema.getQName(), value);
334 LOG.debug("Annotation for {} not found, using legacy QName", qname);
337 attributes.put(QName.create(rawXmlNamespace(attributeNS), localName), attrValue);
340 return ImmutableMap.copyOf(attributes);
343 private static Document readAnyXmlValue(final XMLStreamReader in) throws XMLStreamException {
344 // Underlying reader might return null when asked for version, however when such reader is plugged into
345 // Stax -> DOM transformer, it fails with NPE due to null version. Use default xml version in such case.
346 final XMLStreamReader inWrapper;
347 if (in.getVersion() == null) {
348 inWrapper = new StreamReaderDelegate(in) {
350 public String getVersion() {
351 final String ver = super.getVersion();
352 return ver != null ? ver : XML_STANDARD_VERSION;
359 final DOMResult result = new DOMResult();
361 TRANSFORMER_FACTORY.newTransformer().transform(new StAXSource(inWrapper), result);
362 } catch (final TransformerException e) {
363 throw new XMLStreamException("Unable to read anyxml value", e);
365 return (Document) result.getNode();
368 private void read(final XMLStreamReader in, final AbstractNodeDataWithSchema<?> parent, final String rootElement)
369 throws XMLStreamException {
374 if (parent instanceof LeafNodeDataWithSchema || parent instanceof LeafListEntryNodeDataWithSchema) {
375 parent.setAttributes(getElementAttributes(in));
376 setValue((SimpleNodeDataWithSchema<?>) parent, in.getElementText().trim(), in.getNamespaceContext());
377 if (isNextEndDocument(in)) {
381 if (!isAtElement(in)) {
387 if (parent instanceof ListEntryNodeDataWithSchema || parent instanceof ContainerNodeDataWithSchema) {
388 parent.setAttributes(getElementAttributes(in));
391 if (parent instanceof LeafListNodeDataWithSchema || parent instanceof ListNodeDataWithSchema) {
392 String xmlElementName = in.getLocalName();
393 while (xmlElementName.equals(parent.getSchema().getQName().getLocalName())) {
394 read(in, newEntryNode(parent), rootElement);
395 if (in.getEventType() == XMLStreamConstants.END_DOCUMENT
396 || in.getEventType() == XMLStreamConstants.END_ELEMENT) {
399 xmlElementName = in.getLocalName();
405 if (parent instanceof AnyXmlNodeDataWithSchema) {
406 setValue((AnyXmlNodeDataWithSchema) parent, readAnyXmlValue(in), in.getNamespaceContext());
407 if (isNextEndDocument(in)) {
411 if (!isAtElement(in)) {
418 if (parent instanceof AnydataNodeDataWithSchema) {
419 final AnydataNodeDataWithSchema anydata = (AnydataNodeDataWithSchema) parent;
420 anydata.setObjectModel(DOMSourceAnydata.class);
421 anydata.setAttributes(getElementAttributes(in));
422 setValue(anydata, readAnyXmlValue(in), in.getNamespaceContext());
423 if (isNextEndDocument(in)) {
427 if (!isAtElement(in)) {
434 if (parent instanceof YangModeledAnyxmlSchemaNode) {
435 parent.setAttributes(getElementAttributes(in));
438 switch (in.nextTag()) {
439 case XMLStreamConstants.START_ELEMENT:
440 // FIXME: why do we even need this tracker? either document it or remove it
441 final Set<Entry<String, String>> namesakes = new HashSet<>();
442 while (in.hasNext()) {
443 final String xmlElementName = in.getLocalName();
445 DataSchemaNode parentSchema = parent.getSchema();
447 final String parentSchemaName = parentSchema.getQName().getLocalName();
448 if (parentSchemaName.equals(xmlElementName)
449 && in.getEventType() == XMLStreamConstants.END_ELEMENT) {
450 if (isNextEndDocument(in)) {
454 if (!isAtElement(in)) {
460 if (in.isEndElement() && rootElement.equals(xmlElementName)) {
464 if (parentSchema instanceof YangModeledAnyxmlSchemaNode) {
465 parentSchema = ((YangModeledAnyxmlSchemaNode) parentSchema).getSchemaOfAnyXmlData();
468 final String elementNS = in.getNamespaceURI();
469 if (!namesakes.add(new SimpleImmutableEntry<>(elementNS, xmlElementName))) {
470 throw new XMLStreamException(String.format(
471 "Duplicate namespace \"%s\" element \"%s\" in XML input", elementNS, xmlElementName),
477 nsUri = rawXmlNamespace(elementNS).getNamespace();
478 } catch (IllegalArgumentException e) {
479 throw new XMLStreamException("Failed to convert namespace " + xmlElementName, in.getLocation(),
483 final Deque<DataSchemaNode> childDataSchemaNodes =
484 ParserStreamUtils.findSchemaNodeByNameAndNamespace(parentSchema, xmlElementName, nsUri);
485 if (!childDataSchemaNodes.isEmpty()) {
486 // We have a match, proceed with it
487 read(in, ((CompositeNodeDataWithSchema<?>) parent).addChild(childDataSchemaNodes), rootElement);
491 if (parent instanceof AbstractMountPointDataWithSchema) {
492 // Parent can potentially hold a mount point, let's see if there is a label present
493 final Optional<MountPointSchemaNode> optMount;
494 if (parentSchema instanceof ContainerSchemaNode) {
495 optMount = MountPointSchemaNode.streamAll((ContainerSchemaNode) parentSchema).findFirst();
496 } else if (parentSchema instanceof ListSchemaNode) {
497 optMount = MountPointSchemaNode.streamAll((ListSchemaNode) parentSchema).findFirst();
499 throw new XMLStreamException("Unhandled mount-aware schema " + parentSchema);
502 if (optMount.isPresent()) {
503 final MountPointIdentifier mountId = MountPointIdentifier.of(optMount.get().getQName());
504 LOG.debug("Assuming node {} and namespace {} belongs to mount point {}", xmlElementName,
507 final Optional<MountPointContextFactory> optFactory = codecs.mountPointContext()
508 .findMountPoint(mountId);
509 if (optFactory.isPresent()) {
510 final MountPointData mountData = ((AbstractMountPointDataWithSchema<?>) parent)
511 .getMountPointData(mountId, optFactory.get());
512 addMountPointChild(mountData, nsUri, xmlElementName,
513 new DOMSource(readAnyXmlValue(in).getDocumentElement()));
517 LOG.debug("Mount point {} not attached", mountId);
521 // We have not handled the node -- let's decide what to do about that
523 throw new XMLStreamException(String.format(
524 "Schema for node with name %s and namespace %s does not exist at %s", xmlElementName,
525 elementNS, parentSchema.getPath(), in.getLocation()));
528 LOG.debug("Skipping unknown node ns=\"{}\" localName=\"{}\" at path {}", elementNS, xmlElementName,
529 parentSchema.getPath());
533 case XMLStreamConstants.END_ELEMENT:
534 if (isNextEndDocument(in)) {
538 if (!isAtElement(in)) {
547 private static void addMountPointChild(final MountPointData mount, final URI namespace, final String localName,
548 final DOMSource source) {
549 final DOMSourceMountPointChild child = new DOMSourceMountPointChild(source);
550 if (YangLibraryConstants.MODULE_NAMESPACE.equals(namespace)) {
551 final Optional<ContainerName> optName = ContainerName.forLocalName(localName);
552 if (optName.isPresent()) {
553 mount.setContainer(optName.get(), child);
557 LOG.warn("Encountered unknown element {} from YANG Library namespace", localName);
558 } else if (SchemaMountConstants.RFC8528_MODULE.getNamespace().equals(namespace)) {
559 mount.setSchemaMounts(child);
563 mount.addChild(child);
566 private static boolean isNextEndDocument(final XMLStreamReader in) throws XMLStreamException {
567 return !in.hasNext() || in.next() == XMLStreamConstants.END_DOCUMENT;
570 private static boolean isAtElement(final XMLStreamReader in) {
571 return in.getEventType() == XMLStreamConstants.START_ELEMENT
572 || in.getEventType() == XMLStreamConstants.END_ELEMENT;
575 private static void skipUnknownNode(final XMLStreamReader in) throws XMLStreamException {
576 // in case when the unknown node and at least one of its descendant nodes have the same name
577 // we cannot properly reach the end just by checking if the current node is an end element and has the same name
578 // as the root unknown element. therefore we ignore the names completely and just track the level of nesting
579 int levelOfNesting = 0;
580 while (in.hasNext()) {
581 // in case there are text characters in an element, we cannot skip them by calling nextTag()
582 // therefore we skip them by calling next(), and then proceed to next element
584 if (!isAtElement(in)) {
587 if (in.isStartElement()) {
591 if (in.isEndElement()) {
592 if (levelOfNesting == 0) {
603 private void setValue(final SimpleNodeDataWithSchema<?> parent, final Object value,
604 final NamespaceContext nsContext) {
605 final DataSchemaNode schema = parent.getSchema();
606 final Object prev = parent.getValue();
607 checkArgument(prev == null, "Node '%s' has already set its value to '%s'", schema.getQName(), prev);
608 parent.setValue(translateValueByType(value, schema, nsContext));
611 private Object translateValueByType(final Object value, final DataSchemaNode node,
612 final NamespaceContext namespaceCtx) {
613 if (node instanceof AnyxmlSchemaNode) {
614 checkArgument(value instanceof Document);
616 * FIXME: Figure out some YANG extension dispatch, which will reuse JSON parsing or XML parsing -
617 * anyxml is not well-defined in JSON.
619 return new DOMSource(((Document) value).getDocumentElement());
621 if (node instanceof AnydataSchemaNode) {
622 checkArgument(value instanceof Document);
623 return new DOMSourceAnydata(new DOMSource(((Document) value).getDocumentElement()));
626 checkArgument(node instanceof TypedDataSchemaNode);
627 checkArgument(value instanceof String);
628 return codecs.codecFor((TypedDataSchemaNode) node).parseValue(namespaceCtx, (String) value);
631 private static AbstractNodeDataWithSchema<?> newEntryNode(final AbstractNodeDataWithSchema<?> parent) {
632 verify(parent instanceof MultipleEntryDataWithSchema, "Unexpected parent %s", parent);
633 return ((MultipleEntryDataWithSchema<?>) parent).newChildEntry();
637 public void close() throws IOException {
643 public void flush() throws IOException {
647 private Optional<QNameModule> resolveXmlNamespace(final String xmlNamespace) {
648 return resolvedNamespaces.computeIfAbsent(xmlNamespace, nsUri -> {
649 final Iterator<Module> it = codecs.getSchemaContext().findModules(URI.create(nsUri)).iterator();
650 return it.hasNext() ? Optional.of(it.next().getQNameModule()) : Optional.empty();
654 private QNameModule rawXmlNamespace(final String xmlNamespace) {
655 return rawNamespaces.computeIfAbsent(xmlNamespace, nsUri -> QNameModule.create(URI.create(nsUri)));