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