2 * Copyright (c) 2023 PANTHEON.tech, s.r.o. 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.restconf.nb.rfc8040.databind;
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.net.URISyntaxException;
13 import javax.xml.stream.XMLStreamException;
14 import javax.xml.transform.dom.DOMSource;
15 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
16 import org.opendaylight.yangtools.util.xml.UntrustedXML;
17 import org.opendaylight.yangtools.yang.common.ErrorTag;
18 import org.opendaylight.yangtools.yang.common.ErrorType;
19 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
20 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
21 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
22 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25 import org.xml.sax.SAXException;
28 * An XML-encoded {@link ResourceBody}.
30 public final class XmlResourceBody extends ResourceBody {
31 private static final Logger LOG = LoggerFactory.getLogger(XmlResourceBody.class);
33 public XmlResourceBody(final InputStream inputStream) {
38 void streamTo(final InputStream inputStream, final Inference inference, final PathArgument name,
39 final NormalizedNodeStreamWriter writer) throws IOException {
40 try (var xmlParser = XmlParserStream.create(writer, inference)) {
41 final var doc = UntrustedXML.newDocumentBuilder().parse(inputStream);
42 final var docRoot = doc.getDocumentElement();
43 final var docRootName = docRoot.getLocalName();
44 final var docRootNs = docRoot.getNamespaceURI();
45 final var qname = name.getNodeType();
46 final var pathName = qname.getLocalName();
47 final var pathNs = qname.getNamespace().toString();
48 if (!docRootName.equals(pathName) || !docRootNs.equals(pathNs)) {
49 throw new RestconfDocumentedException("Incorrect message root element (" + docRootNs + ")" + docRootName
50 + ", should be (" + pathNs + ")" + pathName, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
53 xmlParser.traverse(new DOMSource(docRoot));
54 } catch (SAXException | URISyntaxException | XMLStreamException e) {
55 LOG.debug("Error parsing XML input", e);
56 RestconfDocumentedException.throwIfYangError(e);
57 throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
58 ErrorTag.MALFORMED_MESSAGE, e);