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.ContainerLike;
78 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
79 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
80 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
81 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.Module;
85 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
86 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
88 import org.slf4j.Logger;
89 import org.slf4j.LoggerFactory;
90 import org.w3c.dom.Document;
91 import org.xml.sax.SAXException;
94 * This class provides functionality for parsing an XML source containing YANG-modeled data. It disallows multiple
95 * instances of the same element except for leaf-list and list entries. It also expects that the YANG-modeled data in
96 * the XML source are wrapped in a root element. This class is NOT thread-safe.
99 * Due to backwards compatibility reasons, RFC7952 metadata emitted by this parser may include key QNames with empty URI
100 * (as exposed via {@link #LEGACY_ATTRIBUTE_NAMESPACE}) as their QNameModule. These indicate an unqualified XML
101 * attribute and their value can be assumed to be a String. Furthermore, this extends to qualified attributes, which
102 * uses the proper namespace, but will not bind to a proper module revision -- these need to be reconciled with a
103 * particular SchemaContext and are expected to either be fully decoded, or contain a String value. Handling of such
104 * annotations is at the discretion of the user encountering it: preferred way of handling is to either filter or
105 * normalize them to proper QNames/values when encountered. This caveat will be removed in a future version.
108 public final class XmlParserStream implements Closeable, Flushable {
110 * {@link QNameModule} for use with legacy XML attributes.
111 * @deprecated The use on this namespace is discouraged and users are strongly encouraged to proper RFC7952 metadata
115 public static final QNameModule LEGACY_ATTRIBUTE_NAMESPACE = QNameModule.create(URI.create("")).intern();
117 private static final Logger LOG = LoggerFactory.getLogger(XmlParserStream.class);
118 private static final String XML_STANDARD_VERSION = "1.0";
119 private static final String COM_SUN_TRANSFORMER =
120 "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
122 private static final TransformerFactory TRANSFORMER_FACTORY;
125 TransformerFactory fa = TransformerFactory.newInstance();
126 if (!fa.getFeature(StAXSource.FEATURE)) {
127 LOG.warn("Platform-default TransformerFactory {} does not support StAXSource, attempting fallback to {}",
128 fa, COM_SUN_TRANSFORMER);
129 fa = TransformerFactory.newInstance(COM_SUN_TRANSFORMER, null);
130 if (!fa.getFeature(StAXSource.FEATURE)) {
131 throw new TransformerFactoryConfigurationError("No TransformerFactory supporting StAXResult found.");
135 TRANSFORMER_FACTORY = fa;
138 // Cache of nsUri Strings to QNameModules, as resolved in context
139 private final Map<String, Optional<QNameModule>> resolvedNamespaces = new HashMap<>();
140 // Cache of nsUri Strings to QNameModules, as inferred from document
141 private final Map<String, QNameModule> rawNamespaces = new HashMap<>();
142 private final NormalizedNodeStreamWriter writer;
143 private final XmlCodecFactory codecs;
144 private final DataSchemaNode parentNode;
145 private final boolean strictParsing;
147 private XmlParserStream(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
148 final DataSchemaNode parentNode, final boolean strictParsing) {
149 this.writer = requireNonNull(writer);
150 this.codecs = requireNonNull(codecs);
151 this.parentNode = parentNode;
152 this.strictParsing = strictParsing;
156 * Construct a new {@link XmlParserStream} with strict parsing mode switched on.
158 * @param writer Output writer
159 * @param codecs Shared codecs
160 * @param parentNode Parent root node
161 * @return A new stream instance
163 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
164 final SchemaNode parentNode) {
165 return create(writer, codecs, parentNode, true);
169 * Construct a new {@link XmlParserStream}.
171 * @param writer Output writer
172 * @param codecs Shared codecs
173 * @param parentNode Parent root node
174 * @param strictParsing parsing mode
175 * if set to true, the parser will throw an exception if it encounters unknown child nodes
176 * (nodes, that are not defined in the provided SchemaContext) in containers and lists
177 * if set to false, the parser will skip unknown child nodes
178 * @return A new stream instance
180 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final XmlCodecFactory codecs,
181 final SchemaNode parentNode, final boolean strictParsing) {
182 final DataSchemaNode parent;
183 if (parentNode instanceof DataSchemaNode) {
184 parent = (DataSchemaNode) parentNode;
185 } else if (parentNode instanceof OperationDefinition) {
186 parent = OperationAsContainer.of((OperationDefinition) parentNode);
188 throw new IllegalArgumentException("Illegal parent node " + parentNode);
190 return new XmlParserStream(writer, codecs, parent, strictParsing);
194 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
195 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
196 * maintain a {@link XmlCodecFactory} to match the current {@link EffectiveModelContext}.
198 public static XmlParserStream create(final NormalizedNodeStreamWriter writer,
199 final EffectiveModelContext schemaContext, final SchemaNode parentNode) {
200 return create(writer, schemaContext, parentNode, true);
204 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
205 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
206 * maintain a {@link XmlCodecFactory} to match the current {@link EffectiveModelContext}.
208 public static XmlParserStream create(final NormalizedNodeStreamWriter writer,
209 final EffectiveModelContext schemaContext, final SchemaNode parentNode, final boolean strictParsing) {
210 return create(writer, XmlCodecFactory.create(schemaContext), parentNode, strictParsing);
214 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
215 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
216 * maintain a {@link XmlCodecFactory} to match the current {@link MountPointContext}.
218 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
219 final SchemaNode parentNode) {
220 return create(writer, mountCtx, parentNode, true);
224 * Utility method for use when caching {@link XmlCodecFactory} is not feasible. Users with high performance
225 * requirements should use {@link #create(NormalizedNodeStreamWriter, XmlCodecFactory, SchemaNode)} instead and
226 * maintain a {@link XmlCodecFactory} to match the current {@link MountPointContext}.
228 public static XmlParserStream create(final NormalizedNodeStreamWriter writer, final MountPointContext mountCtx,
229 final SchemaNode parentNode, final boolean strictParsing) {
230 return create(writer, XmlCodecFactory.create(mountCtx), parentNode, strictParsing);
234 * This method parses the XML source and emits node events into a NormalizedNodeStreamWriter based on the
235 * YANG-modeled data contained in the XML source.
238 * StAX reader which is to used to walk through the XML source
240 * instance of XmlParserStream
241 * @throws XMLStreamException
242 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
243 * @throws URISyntaxException
244 * if the namespace URI of an XML element contains a syntax error
245 * @throws IOException
246 * if an error occurs while parsing the value of an anyxml node
247 * @throws SAXException
248 * if an error occurs while parsing the value of an anyxml node
250 public XmlParserStream parse(final XMLStreamReader reader) throws XMLStreamException, URISyntaxException,
251 IOException, SAXException {
252 if (reader.hasNext()) {
254 final AbstractNodeDataWithSchema<?> nodeDataWithSchema;
255 if (parentNode instanceof ContainerLike) {
256 nodeDataWithSchema = new ContainerNodeDataWithSchema((ContainerLike) parentNode);
257 } else if (parentNode instanceof ListSchemaNode) {
258 nodeDataWithSchema = new ListNodeDataWithSchema((ListSchemaNode) parentNode);
259 } else if (parentNode instanceof YangModeledAnyxmlSchemaNode) {
260 nodeDataWithSchema = new YangModeledAnyXmlNodeDataWithSchema((YangModeledAnyxmlSchemaNode) parentNode);
261 } else if (parentNode instanceof AnyxmlSchemaNode) {
262 nodeDataWithSchema = new AnyXmlNodeDataWithSchema((AnyxmlSchemaNode) parentNode);
263 } else if (parentNode instanceof LeafSchemaNode) {
264 nodeDataWithSchema = new LeafNodeDataWithSchema((LeafSchemaNode) parentNode);
265 } else if (parentNode instanceof LeafListSchemaNode) {
266 nodeDataWithSchema = new LeafListNodeDataWithSchema((LeafListSchemaNode) parentNode);
267 } else if (parentNode instanceof AnydataSchemaNode) {
268 nodeDataWithSchema = new AnydataNodeDataWithSchema((AnydataSchemaNode) parentNode);
270 throw new IllegalStateException("Unsupported schema node type " + parentNode.getClass() + ".");
273 read(reader, nodeDataWithSchema, reader.getLocalName());
274 nodeDataWithSchema.write(writer);
281 * This method traverses a {@link DOMSource} and emits node events into a NormalizedNodeStreamWriter based on the
282 * YANG-modeled data contained in the source.
285 * {@link DOMSource} to be traversed
287 * instance of XmlParserStream
288 * @throws XMLStreamException
289 * if a well-formedness error or an unexpected processing condition occurs while parsing the XML
290 * @throws URISyntaxException
291 * if the namespace URI of an XML element contains a syntax error
292 * @throws IOException
293 * if an error occurs while parsing the value of an anyxml node
294 * @throws SAXException
295 * if an error occurs while parsing the value of an anyxml node
298 public XmlParserStream traverse(final DOMSource src) throws XMLStreamException, URISyntaxException, IOException,
300 return parse(new DOMSourceXMLStreamReader(src));
303 private ImmutableMap<QName, Object> getElementAttributes(final XMLStreamReader in) {
304 checkState(in.isStartElement(), "Attributes can be extracted only from START_ELEMENT.");
305 final Map<QName, Object> attributes = new LinkedHashMap<>();
307 for (int attrIndex = 0; attrIndex < in.getAttributeCount(); attrIndex++) {
308 final String attributeNS = in.getAttributeNamespace(attrIndex);
310 // Skip namespace definitions
311 if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attributeNS)) {
315 final String localName = in.getAttributeLocalName(attrIndex);
316 final String attrValue = in.getAttributeValue(attrIndex);
317 if (Strings.isNullOrEmpty(attributeNS)) {
318 StreamWriterFacade.warnLegacyAttribute(localName);
319 attributes.put(QName.create(LEGACY_ATTRIBUTE_NAMESPACE, localName), attrValue);
323 // Cross-relate attribute namespace to the module
324 final Optional<QNameModule> optModule = resolveXmlNamespace(attributeNS);
325 if (optModule.isPresent()) {
326 final QName qname = QName.create(optModule.get(), localName);
327 final Optional<AnnotationSchemaNode> optAnnotation = AnnotationSchemaNode.find(
328 codecs.getEffectiveModelContext(), qname);
329 if (optAnnotation.isPresent()) {
330 final AnnotationSchemaNode schema = optAnnotation.get();
331 final Object value = codecs.codecFor(schema).parseValue(in.getNamespaceContext(), attrValue);
332 attributes.put(schema.getQName(), value);
336 LOG.debug("Annotation for {} not found, using legacy QName", qname);
339 attributes.put(QName.create(rawXmlNamespace(attributeNS), localName), attrValue);
342 return ImmutableMap.copyOf(attributes);
345 private static Document readAnyXmlValue(final XMLStreamReader in) throws XMLStreamException {
346 // Underlying reader might return null when asked for version, however when such reader is plugged into
347 // Stax -> DOM transformer, it fails with NPE due to null version. Use default xml version in such case.
348 final XMLStreamReader inWrapper;
349 if (in.getVersion() == null) {
350 inWrapper = new StreamReaderDelegate(in) {
352 public String getVersion() {
353 final String ver = super.getVersion();
354 return ver != null ? ver : XML_STANDARD_VERSION;
361 final DOMResult result = new DOMResult();
363 TRANSFORMER_FACTORY.newTransformer().transform(new StAXSource(inWrapper), result);
364 } catch (final TransformerException e) {
365 throw new XMLStreamException("Unable to read anyxml value", e);
367 return (Document) result.getNode();
370 private void read(final XMLStreamReader in, final AbstractNodeDataWithSchema<?> parent, final String rootElement)
371 throws XMLStreamException {
376 if (parent instanceof LeafNodeDataWithSchema || parent instanceof LeafListEntryNodeDataWithSchema) {
377 parent.setAttributes(getElementAttributes(in));
378 setValue((SimpleNodeDataWithSchema<?>) parent, in.getElementText().trim(), in.getNamespaceContext());
379 if (isNextEndDocument(in)) {
383 if (!isAtElement(in)) {
389 if (parent instanceof ListEntryNodeDataWithSchema || parent instanceof ContainerNodeDataWithSchema) {
390 parent.setAttributes(getElementAttributes(in));
393 if (parent instanceof LeafListNodeDataWithSchema || parent instanceof ListNodeDataWithSchema) {
394 String xmlElementName = in.getLocalName();
395 while (xmlElementName.equals(parent.getSchema().getQName().getLocalName())) {
396 read(in, newEntryNode(parent), rootElement);
397 if (in.getEventType() == XMLStreamConstants.END_DOCUMENT
398 || in.getEventType() == XMLStreamConstants.END_ELEMENT) {
401 xmlElementName = in.getLocalName();
407 if (parent instanceof AnyXmlNodeDataWithSchema) {
408 setValue((AnyXmlNodeDataWithSchema) parent, readAnyXmlValue(in), in.getNamespaceContext());
409 if (isNextEndDocument(in)) {
413 if (!isAtElement(in)) {
420 if (parent instanceof AnydataNodeDataWithSchema) {
421 final AnydataNodeDataWithSchema anydata = (AnydataNodeDataWithSchema) parent;
422 anydata.setObjectModel(DOMSourceAnydata.class);
423 anydata.setAttributes(getElementAttributes(in));
424 setValue(anydata, readAnyXmlValue(in), in.getNamespaceContext());
425 if (isNextEndDocument(in)) {
429 if (!isAtElement(in)) {
436 if (parent instanceof YangModeledAnyxmlSchemaNode) {
437 parent.setAttributes(getElementAttributes(in));
440 switch (in.nextTag()) {
441 case XMLStreamConstants.START_ELEMENT:
442 // FIXME: 7.0.0: why do we even need this tracker? either document it or remove it.
443 // it looks like it is a crude duplicate finder, which should really be handled via
444 // ChildReusePolicy.REJECT
445 final Set<Entry<String, String>> namesakes = new HashSet<>();
446 while (in.hasNext()) {
447 final String xmlElementName = in.getLocalName();
449 DataSchemaNode parentSchema = parent.getSchema();
451 final String parentSchemaName = parentSchema.getQName().getLocalName();
452 if (parentSchemaName.equals(xmlElementName)
453 && in.getEventType() == XMLStreamConstants.END_ELEMENT) {
454 if (isNextEndDocument(in)) {
458 if (!isAtElement(in)) {
464 if (in.isEndElement() && rootElement.equals(xmlElementName)) {
468 if (parentSchema instanceof YangModeledAnyxmlSchemaNode) {
469 parentSchema = ((YangModeledAnyxmlSchemaNode) parentSchema).getSchemaOfAnyXmlData();
472 final String elementNS = in.getNamespaceURI();
473 final boolean added = namesakes.add(new SimpleImmutableEntry<>(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 final boolean elementList = isElementList(childDataSchemaNodes);
487 if (!added && !elementList) {
488 throw new XMLStreamException(String.format(
489 "Duplicate element \"%s\" in namespace \"%s\" with parent \"%s\" in XML input",
490 xmlElementName, elementNS, parent.getSchema()), in.getLocation());
493 // We have a match, proceed with it
494 read(in, ((CompositeNodeDataWithSchema<?>) parent).addChild(childDataSchemaNodes,
495 elementList ? ChildReusePolicy.REUSE : ChildReusePolicy.NOOP), rootElement);
499 if (parent instanceof AbstractMountPointDataWithSchema) {
500 // Parent can potentially hold a mount point, let's see if there is a label present
501 final Optional<MountPointSchemaNode> optMount;
502 if (parentSchema instanceof ContainerSchemaNode) {
503 optMount = MountPointSchemaNode.streamAll((ContainerSchemaNode) parentSchema).findFirst();
504 } else if (parentSchema instanceof ListSchemaNode) {
505 optMount = MountPointSchemaNode.streamAll((ListSchemaNode) parentSchema).findFirst();
507 throw new XMLStreamException("Unhandled mount-aware schema " + parentSchema);
510 if (optMount.isPresent()) {
511 final MountPointIdentifier mountId = MountPointIdentifier.of(optMount.get().getQName());
512 LOG.debug("Assuming node {} and namespace {} belongs to mount point {}", xmlElementName,
515 final Optional<MountPointContextFactory> optFactory = codecs.mountPointContext()
516 .findMountPoint(mountId);
517 if (optFactory.isPresent()) {
518 final MountPointData mountData = ((AbstractMountPointDataWithSchema<?>) parent)
519 .getMountPointData(mountId, optFactory.get());
520 addMountPointChild(mountData, nsUri, xmlElementName,
521 new DOMSource(readAnyXmlValue(in).getDocumentElement()));
525 LOG.debug("Mount point {} not attached", mountId);
529 // We have not handled the node -- let's decide what to do about that
531 throw new XMLStreamException(String.format(
532 "Schema for node with name %s and namespace %s does not exist at %s", xmlElementName,
533 elementNS, parentSchema.getPath(), in.getLocation()));
536 LOG.debug("Skipping unknown node ns=\"{}\" localName=\"{}\" at path {}", elementNS, xmlElementName,
537 parentSchema.getPath());
541 case XMLStreamConstants.END_ELEMENT:
542 if (isNextEndDocument(in)) {
546 if (!isAtElement(in)) {
555 // Return true if schema represents a construct which uses multiple sibling elements to represent its content. The
556 // siblings MAY be interleaved as per RFC7950.
557 private static boolean isElementList(final Deque<DataSchemaNode> childDataSchemaNodes) {
558 final DataSchemaNode last = childDataSchemaNodes.getLast();
559 return last instanceof ListSchemaNode || last instanceof LeafListSchemaNode;
562 private static void addMountPointChild(final MountPointData mount, final URI namespace, final String localName,
563 final DOMSource source) {
564 final DOMSourceMountPointChild child = new DOMSourceMountPointChild(source);
565 if (YangLibraryConstants.MODULE_NAMESPACE.equals(namespace)) {
566 final Optional<ContainerName> optName = ContainerName.forLocalName(localName);
567 if (optName.isPresent()) {
568 mount.setContainer(optName.get(), child);
572 LOG.warn("Encountered unknown element {} from YANG Library namespace", localName);
573 } else if (SchemaMountConstants.RFC8528_MODULE.getNamespace().equals(namespace)) {
574 mount.setSchemaMounts(child);
578 mount.addChild(child);
581 private static boolean isNextEndDocument(final XMLStreamReader in) throws XMLStreamException {
582 return !in.hasNext() || in.next() == XMLStreamConstants.END_DOCUMENT;
585 private static boolean isAtElement(final XMLStreamReader in) {
586 return in.getEventType() == XMLStreamConstants.START_ELEMENT
587 || in.getEventType() == XMLStreamConstants.END_ELEMENT;
590 private static void skipUnknownNode(final XMLStreamReader in) throws XMLStreamException {
591 // in case when the unknown node and at least one of its descendant nodes have the same name
592 // we cannot properly reach the end just by checking if the current node is an end element and has the same name
593 // as the root unknown element. therefore we ignore the names completely and just track the level of nesting
594 int levelOfNesting = 0;
595 while (in.hasNext()) {
596 // in case there are text characters in an element, we cannot skip them by calling nextTag()
597 // therefore we skip them by calling next(), and then proceed to next element
599 if (!isAtElement(in)) {
602 if (in.isStartElement()) {
606 if (in.isEndElement()) {
607 if (levelOfNesting == 0) {
618 private void setValue(final SimpleNodeDataWithSchema<?> parent, final Object value,
619 final NamespaceContext nsContext) {
620 final DataSchemaNode schema = parent.getSchema();
621 final Object prev = parent.getValue();
622 checkArgument(prev == null, "Node '%s' has already set its value to '%s'", schema.getQName(), prev);
623 parent.setValue(translateValueByType(value, schema, nsContext));
626 private Object translateValueByType(final Object value, final DataSchemaNode node,
627 final NamespaceContext namespaceCtx) {
628 if (node instanceof AnyxmlSchemaNode) {
629 checkArgument(value instanceof Document);
631 * FIXME: Figure out some YANG extension dispatch, which will reuse JSON parsing or XML parsing -
632 * anyxml is not well-defined in JSON.
634 return new DOMSource(((Document) value).getDocumentElement());
636 if (node instanceof AnydataSchemaNode) {
637 checkArgument(value instanceof Document);
638 return new DOMSourceAnydata(new DOMSource(((Document) value).getDocumentElement()));
641 checkArgument(node instanceof TypedDataSchemaNode);
642 checkArgument(value instanceof String);
643 return codecs.codecFor((TypedDataSchemaNode) node).parseValue(namespaceCtx, (String) value);
646 private static AbstractNodeDataWithSchema<?> newEntryNode(final AbstractNodeDataWithSchema<?> parent) {
647 verify(parent instanceof MultipleEntryDataWithSchema, "Unexpected parent %s", parent);
648 return ((MultipleEntryDataWithSchema<?>) parent).newChildEntry();
652 public void close() throws IOException {
658 public void flush() throws IOException {
662 private Optional<QNameModule> resolveXmlNamespace(final String xmlNamespace) {
663 return resolvedNamespaces.computeIfAbsent(xmlNamespace, nsUri -> {
664 final Iterator<? extends Module> it = codecs.getEffectiveModelContext().findModules(URI.create(nsUri))
666 return it.hasNext() ? Optional.of(it.next().getQNameModule()) : Optional.empty();
670 private QNameModule rawXmlNamespace(final String xmlNamespace) {
671 return rawNamespaces.computeIfAbsent(xmlNamespace, nsUri -> QNameModule.create(URI.create(nsUri)));