Add Child Nodes Only query parameter to SSE events
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / nb / rfc8040 / databind / XmlPatchBody.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  * Copyright (c) 2023 PANTHEON.tech, s.r.o.
4  *
5  * This program and the accompanying materials are made available under the
6  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7  * and is available at http://www.eclipse.org/legal/epl-v10.html
8  */
9 package org.opendaylight.restconf.nb.rfc8040.databind;
10
11 import com.google.common.collect.ImmutableList;
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.net.URISyntaxException;
15 import java.util.ArrayList;
16 import java.util.List;
17 import javax.xml.stream.XMLStreamException;
18 import javax.xml.transform.dom.DOMSource;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
21 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
22 import org.opendaylight.restconf.common.patch.PatchContext;
23 import org.opendaylight.restconf.common.patch.PatchEntity;
24 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.patch.rev170222.yang.patch.yang.patch.Edit.Operation;
25 import org.opendaylight.yangtools.util.xml.UntrustedXML;
26 import org.opendaylight.yangtools.yang.common.ErrorTag;
27 import org.opendaylight.yangtools.yang.common.ErrorType;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
29 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
30 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
31 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
32 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizationResultHolder;
33 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.w3c.dom.Document;
37 import org.w3c.dom.Element;
38 import org.w3c.dom.Node;
39 import org.xml.sax.SAXException;
40
41 public final class XmlPatchBody extends PatchBody {
42     private static final Logger LOG = LoggerFactory.getLogger(XmlPatchBody.class);
43
44     public XmlPatchBody(final InputStream inputStream) {
45         super(inputStream);
46     }
47
48     @Override
49     PatchContext toPatchContext(final InstanceIdentifierContext targetResource, final InputStream inputStream)
50             throws IOException {
51         try {
52             return parse(targetResource, UntrustedXML.newDocumentBuilder().parse(inputStream));
53         } catch (XMLStreamException | SAXException | URISyntaxException e) {
54             LOG.debug("Failed to parse YANG Patch XML", e);
55             throw new RestconfDocumentedException("Error parsing YANG Patch XML: " + e.getMessage(), ErrorType.PROTOCOL,
56                 ErrorTag.MALFORMED_MESSAGE, e);
57         }
58     }
59
60     private static @NonNull PatchContext parse(final InstanceIdentifierContext targetResource, final Document doc)
61             throws XMLStreamException, IOException, SAXException, URISyntaxException {
62         final var resultCollection = new ArrayList<PatchEntity>();
63         final var patchId = doc.getElementsByTagName("patch-id").item(0).getFirstChild().getNodeValue();
64         final var editNodes = doc.getElementsByTagName("edit");
65         final var schemaTree = DataSchemaContextTree.from(targetResource.getSchemaContext());
66
67         for (int i = 0; i < editNodes.getLength(); i++) {
68             final Element element = (Element) editNodes.item(i);
69             final String operation = element.getElementsByTagName("operation").item(0).getFirstChild().getNodeValue();
70             final Operation oper = Operation.ofName(operation);
71             final String editId = element.getElementsByTagName("edit-id").item(0).getFirstChild().getNodeValue();
72             final String target = element.getElementsByTagName("target").item(0).getFirstChild().getNodeValue();
73             final List<Element> values = readValueNodes(element, oper);
74             final Element firstValueElement = values != null ? values.get(0) : null;
75
76             // find complete path to target, it can be also empty (only slash)
77             final var targetII = parsePatchTarget(targetResource, target);
78             // move schema node
79             final var lookup = schemaTree.enterPath(targetII).orElseThrow();
80
81             final var stack = lookup.stack();
82             final var inference = stack.toInference();
83             if (!stack.isEmpty()) {
84                 stack.exit();
85             }
86
87             if (requiresValue(oper)) {
88                 final NormalizationResultHolder resultHolder = new NormalizationResultHolder();
89                 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
90                 final XmlParserStream xmlParser = XmlParserStream.create(writer, inference);
91                 xmlParser.traverse(new DOMSource(firstValueElement));
92
93                 final var result = resultHolder.getResult().data();
94                 // for lists allow to manipulate with list items through their parent
95                 if (targetII.getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
96                     resultCollection.add(new PatchEntity(editId, oper, targetII.getParent(), result));
97                 } else {
98                     resultCollection.add(new PatchEntity(editId, oper, targetII, result));
99                 }
100             } else {
101                 resultCollection.add(new PatchEntity(editId, oper, targetII));
102             }
103         }
104
105         return new PatchContext(targetResource, ImmutableList.copyOf(resultCollection), patchId);
106     }
107
108     /**
109      * Read value nodes.
110      *
111      * @param element Element of current edit operation
112      * @param operation Name of current operation
113      * @return List of value elements
114      */
115     private static List<Element> readValueNodes(final @NonNull Element element, final @NonNull Operation operation) {
116         final Node valueNode = element.getElementsByTagName("value").item(0);
117
118         final boolean isWithValue = requiresValue(operation);
119         if (isWithValue && valueNode == null) {
120             throw new RestconfDocumentedException("Error parsing input",
121                     ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
122         }
123
124         if (!isWithValue && valueNode != null) {
125             throw new RestconfDocumentedException("Error parsing input",
126                     ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
127         }
128
129         if (valueNode == null) {
130             return null;
131         }
132
133         final var result = new ArrayList<Element>();
134         final var childNodes = valueNode.getChildNodes();
135         for (int i = 0; i < childNodes.getLength(); i++) {
136             if (childNodes.item(i) instanceof Element childElement) {
137                 result.add(childElement);
138             }
139         }
140
141         return result;
142     }
143 }