Bump MRI upstreams
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / jersey / providers / patch / XmlToPatchBodyReader.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.restconf.nb.rfc8040.jersey.providers.patch;
9
10 import static com.google.common.base.Verify.verify;
11 import static com.google.common.base.Verify.verifyNotNull;
12
13 import com.google.common.base.Splitter;
14 import com.google.common.collect.ImmutableList;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.net.URISyntaxException;
18 import java.util.ArrayList;
19 import java.util.Iterator;
20 import java.util.List;
21 import java.util.Locale;
22 import javax.ws.rs.Consumes;
23 import javax.ws.rs.WebApplicationException;
24 import javax.ws.rs.ext.Provider;
25 import javax.xml.parsers.ParserConfigurationException;
26 import javax.xml.stream.XMLStreamException;
27 import javax.xml.transform.dom.DOMSource;
28 import org.eclipse.jdt.annotation.NonNull;
29 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
30 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
31 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
32 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
33 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
34 import org.opendaylight.restconf.common.patch.PatchContext;
35 import org.opendaylight.restconf.common.patch.PatchEditOperation;
36 import org.opendaylight.restconf.common.patch.PatchEntity;
37 import org.opendaylight.restconf.nb.rfc8040.MediaTypes;
38 import org.opendaylight.restconf.nb.rfc8040.codecs.StringModuleInstanceIdentifierCodec;
39 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
40 import org.opendaylight.yangtools.util.xml.UntrustedXML;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.common.Revision;
43 import org.opendaylight.yangtools.yang.common.XMLNamespace;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
46 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
48 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
49 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
50 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
51 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
53 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.Module;
56 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
58 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61 import org.w3c.dom.Document;
62 import org.w3c.dom.Element;
63 import org.w3c.dom.Node;
64 import org.w3c.dom.NodeList;
65 import org.xml.sax.SAXException;
66
67 @Provider
68 @Consumes(MediaTypes.APPLICATION_YANG_PATCH_XML)
69 public class XmlToPatchBodyReader extends AbstractToPatchBodyReader {
70     private static final Logger LOG = LoggerFactory.getLogger(XmlToPatchBodyReader.class);
71     private static final Splitter SLASH_SPLITTER = Splitter.on('/');
72
73     public XmlToPatchBodyReader(final SchemaContextHandler schemaContextHandler,
74             final DOMMountPointService mountPointService) {
75         super(schemaContextHandler, mountPointService);
76     }
77
78     @SuppressWarnings("checkstyle:IllegalCatch")
79     @Override
80     protected PatchContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
81             throws WebApplicationException {
82         try {
83             final Document doc = UntrustedXML.newDocumentBuilder().parse(entityStream);
84             return parse(path, doc);
85         } catch (final RestconfDocumentedException e) {
86             throw e;
87         } catch (final Exception e) {
88             LOG.debug("Error parsing xml input", e);
89
90             throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
91                     ErrorTag.MALFORMED_MESSAGE, e);
92         }
93     }
94
95     private static PatchContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc)
96             throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
97         final List<PatchEntity> resultCollection = new ArrayList<>();
98         final String patchId = doc.getElementsByTagName("patch-id").item(0).getFirstChild().getNodeValue();
99         final NodeList editNodes = doc.getElementsByTagName("edit");
100
101         for (int i = 0; i < editNodes.getLength(); i++) {
102             DataSchemaNode schemaNode = (DataSchemaNode) pathContext.getSchemaNode();
103             final Element element = (Element) editNodes.item(i);
104             final String operation = element.getElementsByTagName("operation").item(0).getFirstChild().getNodeValue();
105             final PatchEditOperation oper = PatchEditOperation.valueOf(operation.toUpperCase(Locale.ROOT));
106             final String editId = element.getElementsByTagName("edit-id").item(0).getFirstChild().getNodeValue();
107             final String target = element.getElementsByTagName("target").item(0).getFirstChild().getNodeValue();
108             final List<Element> values = readValueNodes(element, oper);
109             final Element firstValueElement = values != null ? values.get(0) : null;
110
111             // get namespace according to schema node from path context or value
112             final String namespace = firstValueElement == null
113                     ? schemaNode.getQName().getNamespace().toString() : firstValueElement.getNamespaceURI();
114
115             // find module according to namespace
116             final Module module = pathContext.getSchemaContext().findModules(XMLNamespace.of(namespace)).iterator()
117                 .next();
118
119             // initialize codec + set default prefix derived from module name
120             final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
121                     pathContext.getSchemaContext(), module.getName());
122
123             // find complete path to target and target schema node
124             // target can be also empty (only slash)
125             YangInstanceIdentifier targetII;
126             final SchemaNode targetNode;
127             if (target.equals("/")) {
128                 targetII = pathContext.getInstanceIdentifier();
129                 targetNode = pathContext.getSchemaContext();
130             } else {
131                 targetII = codec.deserialize(codec.serialize(pathContext.getInstanceIdentifier())
132                         .concat(prepareNonCondXpath(schemaNode, target.replaceFirst("/", ""), firstValueElement,
133                                 namespace,
134                                 module.getQNameModule().getRevision().map(Revision::toString).orElse(null))));
135
136                 // move schema node
137                 schemaNode = verifyNotNull(codec.getDataContextTree().findChild(targetII).orElseThrow()
138                     .getDataSchemaNode());
139
140                 final EffectiveStatement<?, ?> parentStmt = SchemaInferenceStack.ofInstantiatedPath(
141                     pathContext.getSchemaContext(), schemaNode.getPath().getParent()).currentStatement();
142                 verify(parentStmt instanceof SchemaNode, "Unexpected parent %s", parentStmt);
143                 targetNode = (SchemaNode) parentStmt;
144             }
145
146             if (targetNode == null) {
147                 LOG.debug("Target node {} not found in path {} ", target, pathContext.getSchemaNode());
148                 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL,
149                         ErrorTag.MALFORMED_MESSAGE);
150             }
151
152             if (oper.isWithValue()) {
153                 final NormalizedNode parsed;
154                 if (schemaNode instanceof  ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
155                     final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
156                     final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
157                     final XmlParserStream xmlParser = XmlParserStream.create(writer,
158                         SchemaInferenceStack.ofInstantiatedPath(pathContext.getSchemaContext(), schemaNode.getPath())
159                             .toInference());
160                     xmlParser.traverse(new DOMSource(firstValueElement));
161                     parsed = resultHolder.getResult();
162                 } else {
163                     parsed = null;
164                 }
165
166                 // for lists allow to manipulate with list items through their parent
167                 if (targetII.getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
168                     targetII = targetII.getParent();
169                 }
170
171                 resultCollection.add(new PatchEntity(editId, oper, targetII, parsed));
172             } else {
173                 resultCollection.add(new PatchEntity(editId, oper, targetII));
174             }
175         }
176
177         return new PatchContext(pathContext, ImmutableList.copyOf(resultCollection), patchId);
178     }
179
180     /**
181      * Read value nodes.
182      *
183      * @param element Element of current edit operation
184      * @param operation Name of current operation
185      * @return List of value elements
186      */
187     private static List<Element> readValueNodes(final @NonNull Element element,
188             final @NonNull PatchEditOperation operation) {
189         final Node valueNode = element.getElementsByTagName("value").item(0);
190
191         if (operation.isWithValue() && valueNode == null) {
192             throw new RestconfDocumentedException("Error parsing input",
193                     ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
194         }
195
196         if (!operation.isWithValue() && valueNode != null) {
197             throw new RestconfDocumentedException("Error parsing input",
198                     ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
199         }
200
201         if (valueNode == null) {
202             return null;
203         }
204
205         final List<Element> result = new ArrayList<>();
206         final NodeList childNodes = valueNode.getChildNodes();
207         for (int i = 0; i < childNodes.getLength(); i++) {
208             if (childNodes.item(i) instanceof Element) {
209                 result.add((Element) childNodes.item(i));
210             }
211         }
212
213         return result;
214     }
215
216     /**
217      * Prepare non-conditional XPath suitable for deserialization with {@link StringModuleInstanceIdentifierCodec}.
218      *
219      * @param schemaNode Top schema node
220      * @param target Edit operation target
221      * @param value Element with value
222      * @param namespace Module namespace
223      * @param revision Module revision
224      * @return Non-conditional XPath
225      */
226     private static String prepareNonCondXpath(final @NonNull DataSchemaNode schemaNode, final @NonNull String target,
227             final @NonNull Element value, final @NonNull String namespace, final @NonNull String revision) {
228         final Iterator<String> args = SLASH_SPLITTER.split(target.substring(target.indexOf(':') + 1)).iterator();
229
230         final StringBuilder nonCondXpath = new StringBuilder();
231         SchemaNode childNode = schemaNode;
232
233         while (args.hasNext()) {
234             final String s = args.next();
235             nonCondXpath.append("/");
236             nonCondXpath.append(s);
237             childNode = ((DataNodeContainer) childNode).getDataChildByName(QName.create(namespace, revision, s));
238
239             if (childNode instanceof ListSchemaNode && args.hasNext()) {
240                 appendKeys(nonCondXpath, ((ListSchemaNode) childNode).getKeyDefinition().iterator(), args);
241             }
242         }
243
244         if (childNode instanceof ListSchemaNode && value != null) {
245             final Iterator<String> keyValues = readKeyValues(value,
246                     ((ListSchemaNode) childNode).getKeyDefinition().iterator());
247             appendKeys(nonCondXpath, ((ListSchemaNode) childNode).getKeyDefinition().iterator(), keyValues);
248         }
249
250         return nonCondXpath.toString();
251     }
252
253     /**
254      * Read value for every list key.
255      *
256      * @param value Value element
257      * @param keys Iterator of list keys names
258      * @return Iterator of list keys values
259      */
260     private static Iterator<String> readKeyValues(final @NonNull Element value, final @NonNull Iterator<QName> keys) {
261         final List<String> result = new ArrayList<>();
262
263         while (keys.hasNext()) {
264             result.add(value.getElementsByTagName(keys.next().getLocalName()).item(0).getFirstChild().getNodeValue());
265         }
266
267         return result.iterator();
268     }
269
270     /**
271      * Append key name - key value pairs for every list key to {@code nonCondXpath}.
272      *
273      * @param nonCondXpath Builder for creating non-conditional XPath
274      * @param keyNames Iterator of list keys names
275      * @param keyValues Iterator of list keys values
276      */
277     private static void appendKeys(final @NonNull StringBuilder nonCondXpath, final @NonNull Iterator<QName> keyNames,
278             final @NonNull Iterator<String> keyValues) {
279         while (keyNames.hasNext()) {
280             nonCondXpath.append('[').append(keyNames.next().getLocalName()).append("='").append(keyValues.next())
281                 .append("']");
282         }
283     }
284 }