Remove "/" sign in AbstractRestconfStreamRegistry
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / server / api / 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.server.api;
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.errors.RestconfDocumentedException;
21 import org.opendaylight.restconf.common.patch.PatchContext;
22 import org.opendaylight.restconf.common.patch.PatchEntity;
23 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.patch.rev170222.yang.patch.yang.patch.Edit.Operation;
24 import org.opendaylight.yangtools.util.xml.UntrustedXML;
25 import org.opendaylight.yangtools.yang.common.ErrorTag;
26 import org.opendaylight.yangtools.yang.common.ErrorType;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
28 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
29 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
30 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizationResultHolder;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33 import org.w3c.dom.Document;
34 import org.w3c.dom.Element;
35 import org.w3c.dom.Node;
36 import org.xml.sax.SAXException;
37
38 public final class XmlPatchBody extends PatchBody {
39     private static final Logger LOG = LoggerFactory.getLogger(XmlPatchBody.class);
40
41     public XmlPatchBody(final InputStream inputStream) {
42         super(inputStream);
43     }
44
45     @Override
46     PatchContext toPatchContext(final ResourceContext resource, final InputStream inputStream) throws IOException {
47         try {
48             return parse(resource, UntrustedXML.newDocumentBuilder().parse(inputStream));
49         } catch (XMLStreamException | SAXException | URISyntaxException e) {
50             LOG.debug("Failed to parse YANG Patch XML", e);
51             throw new RestconfDocumentedException("Error parsing YANG Patch XML: " + e.getMessage(), ErrorType.PROTOCOL,
52                 ErrorTag.MALFORMED_MESSAGE, e);
53         }
54     }
55
56     private static @NonNull PatchContext parse(final ResourceContext resource, final Document doc)
57             throws XMLStreamException, IOException, SAXException, URISyntaxException {
58         final var entities = ImmutableList.<PatchEntity>builder();
59         final var patchId = doc.getElementsByTagName("patch-id").item(0).getFirstChild().getNodeValue();
60         final var editNodes = doc.getElementsByTagName("edit");
61
62         for (int i = 0; i < editNodes.getLength(); i++) {
63             final Element element = (Element) editNodes.item(i);
64             final String operation = element.getElementsByTagName("operation").item(0).getFirstChild().getNodeValue();
65             final Operation oper = Operation.ofName(operation);
66             final String editId = element.getElementsByTagName("edit-id").item(0).getFirstChild().getNodeValue();
67             final String target = element.getElementsByTagName("target").item(0).getFirstChild().getNodeValue();
68             final List<Element> values = readValueNodes(element, oper);
69             final Element firstValueElement = values != null ? values.get(0) : null;
70
71             // find complete path to target, it can be also empty (only slash)
72             final var targetData = parsePatchTarget(resource, target);
73             final var inference = targetData.inference();
74             final var stack = inference.toSchemaInferenceStack();
75             if (!stack.isEmpty()) {
76                 stack.exit();
77             }
78
79             final var targetPath = targetData.instance();
80
81             if (requiresValue(oper)) {
82                 final var resultHolder = new NormalizationResultHolder();
83                 final var writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
84                 final var xmlParser = XmlParserStream.create(writer, resource.path.databind().xmlCodecs(), inference);
85                 xmlParser.traverse(new DOMSource(firstValueElement));
86
87                 final var result = resultHolder.getResult().data();
88                 // for lists allow to manipulate with list items through their parent
89                 if (targetPath.getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
90                     entities.add(new PatchEntity(editId, oper, targetPath.getParent(), result));
91                 } else {
92                     entities.add(new PatchEntity(editId, oper, targetPath, result));
93                 }
94             } else {
95                 entities.add(new PatchEntity(editId, oper, targetPath));
96             }
97         }
98
99         return new PatchContext(patchId, entities.build());
100     }
101
102     /**
103      * Read value nodes.
104      *
105      * @param element Element of current edit operation
106      * @param operation Name of current operation
107      * @return List of value elements
108      */
109     private static List<Element> readValueNodes(final @NonNull Element element, final @NonNull Operation operation) {
110         final Node valueNode = element.getElementsByTagName("value").item(0);
111
112         final boolean isWithValue = requiresValue(operation);
113         if (isWithValue && valueNode == null) {
114             throw new RestconfDocumentedException("Error parsing input",
115                     ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
116         }
117
118         if (!isWithValue && valueNode != null) {
119             throw new RestconfDocumentedException("Error parsing input",
120                     ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
121         }
122
123         if (valueNode == null) {
124             return null;
125         }
126
127         final var result = new ArrayList<Element>();
128         final var childNodes = valueNode.getChildNodes();
129         for (int i = 0; i < childNodes.getLength(); i++) {
130             if (childNodes.item(i) instanceof Element childElement) {
131                 result.add(childElement);
132             }
133         }
134
135         return result;
136     }
137 }