Bug 8988 - Check for empty payload properly
[netconf.git] / restconf / restconf-nb-bierman02 / src / main / java / org / opendaylight / netconf / sal / rest / impl / XmlToPatchBodyReader.java
1 /*
2  * Copyright (c) 2015 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.netconf.sal.rest.impl;
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.lang.annotation.Annotation;
16 import java.lang.reflect.Type;
17 import java.net.URI;
18 import java.net.URISyntaxException;
19 import java.util.ArrayList;
20 import java.util.Iterator;
21 import java.util.List;
22 import java.util.Optional;
23 import javax.annotation.Nonnull;
24 import javax.ws.rs.Consumes;
25 import javax.ws.rs.WebApplicationException;
26 import javax.ws.rs.core.MediaType;
27 import javax.ws.rs.core.MultivaluedMap;
28 import javax.ws.rs.ext.MessageBodyReader;
29 import javax.ws.rs.ext.Provider;
30 import javax.xml.parsers.ParserConfigurationException;
31 import javax.xml.stream.XMLStreamException;
32 import javax.xml.transform.dom.DOMSource;
33 import org.opendaylight.netconf.sal.rest.api.Draft02;
34 import org.opendaylight.netconf.sal.rest.api.RestconfService;
35 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
36 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
37 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
38 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
39 import org.opendaylight.restconf.common.patch.PatchContext;
40 import org.opendaylight.restconf.common.patch.PatchEditOperation;
41 import org.opendaylight.restconf.common.patch.PatchEntity;
42 import org.opendaylight.restconf.common.util.RestUtil;
43 import org.opendaylight.yangtools.util.xml.UntrustedXML;
44 import org.opendaylight.yangtools.yang.common.QName;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
47 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
49 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
50 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
51 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
52 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
54 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.Module;
57 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
58 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
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 /**
68  * Yang PATCH Reader for XML.
69  *
70  * @deprecated This class will be replaced by XmlToPatchBodyReader from restconf-nb-rfc8040
71  */
72 @Deprecated
73 @Provider
74 @Consumes({Draft02.MediaTypes.PATCH + RestconfService.XML})
75 public class XmlToPatchBodyReader extends AbstractIdentifierAwareJaxRsProvider implements
76         MessageBodyReader<PatchContext> {
77
78     private static final Logger LOG = LoggerFactory.getLogger(XmlToPatchBodyReader.class);
79
80     @Override
81     public boolean isReadable(final Class<?> type, final Type genericType,
82                               final Annotation[] annotations, final MediaType mediaType) {
83         return true;
84     }
85
86     @SuppressWarnings("checkstyle:IllegalCatch")
87     @Override
88     public PatchContext readFrom(final Class<PatchContext> type, final Type genericType,
89                                  final Annotation[] annotations, final MediaType mediaType,
90                                  final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream)
91             throws IOException, WebApplicationException {
92
93         try {
94             final InstanceIdentifierContext<?> path = getInstanceIdentifierContext();
95             final Optional<InputStream> nonEmptyInputStreamOptional = RestUtil.isInputStreamEmpty(entityStream);
96             if (!nonEmptyInputStreamOptional.isPresent()) {
97                 // represent empty nopayload input
98                 return new PatchContext(path, null, null);
99             }
100
101             final Document doc = UntrustedXML.newDocumentBuilder().parse(nonEmptyInputStreamOptional.get());
102             return parse(path, doc);
103         } catch (final RestconfDocumentedException e) {
104             throw e;
105         } catch (final Exception e) {
106             LOG.debug("Error parsing xml input", e);
107
108             throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
109                     ErrorTag.MALFORMED_MESSAGE);
110         }
111     }
112
113     private static PatchContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc)
114             throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
115         final List<PatchEntity> resultCollection = new ArrayList<>();
116         final String patchId = doc.getElementsByTagName("patch-id").item(0).getFirstChild().getNodeValue();
117         final NodeList editNodes = doc.getElementsByTagName("edit");
118
119         for (int i = 0; i < editNodes.getLength(); i++) {
120             DataSchemaNode schemaNode = (DataSchemaNode) pathContext.getSchemaNode();
121             final Element element = (Element) editNodes.item(i);
122             final String operation = element.getElementsByTagName("operation").item(0).getFirstChild().getNodeValue();
123             final PatchEditOperation oper = PatchEditOperation.valueOf(operation.toUpperCase());
124
125             final String editId = element.getElementsByTagName("edit-id").item(0).getFirstChild().getNodeValue();
126             final String target = element.getElementsByTagName("target").item(0).getFirstChild().getNodeValue();
127             final List<Element> values = readValueNodes(element, oper);
128             final Element firstValueElement = values != null ? values.get(0) : null;
129
130             // get namespace according to schema node from path context or value
131             final String namespace = firstValueElement == null
132                     ? schemaNode.getQName().getNamespace().toString() : firstValueElement.getNamespaceURI();
133
134             // find module according to namespace
135             final Module module = pathContext.getSchemaContext().findModuleByNamespace(
136                     URI.create(namespace)).iterator().next();
137
138             // initialize codec + set default prefix derived from module name
139             final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
140                     pathContext.getSchemaContext(), module.getName());
141
142             // find complete path to target and target schema node
143             // target can be also empty (only slash)
144             YangInstanceIdentifier targetII;
145             final SchemaNode targetNode;
146             if (target.equals("/")) {
147                 targetII = pathContext.getInstanceIdentifier();
148                 targetNode = pathContext.getSchemaContext();
149             } else {
150                 targetII = codec.deserialize(codec.serialize(pathContext.getInstanceIdentifier())
151                         .concat(prepareNonCondXpath(schemaNode, target.replaceFirst("/", ""), firstValueElement,
152                                 namespace, module.getQNameModule().getFormattedRevision())));
153
154                 targetNode = SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(),
155                         codec.getDataContextTree().getChild(targetII).getDataSchemaNode().getPath().getParent());
156
157                 // move schema node
158                 schemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(),
159                         codec.getDataContextTree().getChild(targetII).getDataSchemaNode().getPath());
160             }
161
162             if (targetNode == null) {
163                 LOG.debug("Target node {} not found in path {} ", target, pathContext.getSchemaNode());
164                 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL,
165                         ErrorTag.MALFORMED_MESSAGE);
166             }
167
168             if (oper.isWithValue()) {
169                 final NormalizedNode<?, ?> parsed;
170                 if (schemaNode instanceof  ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
171                     final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
172                     final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
173                     final XmlParserStream xmlParser = XmlParserStream.create(writer, pathContext.getSchemaContext(),
174                             schemaNode);
175                     xmlParser.traverse(new DOMSource(firstValueElement));
176                     parsed = resultHolder.getResult();
177                 } else {
178                     parsed = null;
179                 }
180
181                 // for lists allow to manipulate with list items through their parent
182                 if (targetII.getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
183                     targetII = targetII.getParent();
184                 }
185
186                 resultCollection.add(new PatchEntity(editId, oper, targetII, parsed));
187             } else {
188                 resultCollection.add(new PatchEntity(editId, oper, targetII));
189             }
190         }
191
192         return new PatchContext(pathContext, ImmutableList.copyOf(resultCollection), patchId);
193     }
194
195     /**
196      * Read value nodes.
197      *
198      * @param element Element of current edit operation
199      * @param operation Name of current operation
200      * @return List of value elements
201      */
202     private static List<Element> readValueNodes(@Nonnull final Element element,
203             @Nonnull final PatchEditOperation operation) {
204         final Node valueNode = element.getElementsByTagName("value").item(0);
205
206         if (operation.isWithValue() && valueNode == null) {
207             throw new RestconfDocumentedException("Error parsing input",
208                     ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
209         }
210
211         if (!operation.isWithValue() && valueNode != null) {
212             throw new RestconfDocumentedException("Error parsing input",
213                     ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
214         }
215
216         if (valueNode == null) {
217             return null;
218         }
219
220         final List<Element> result = new ArrayList<>();
221         final NodeList childNodes = valueNode.getChildNodes();
222         for (int i = 0; i < childNodes.getLength(); i++) {
223             if (childNodes.item(i) instanceof Element) {
224                 result.add((Element) childNodes.item(i));
225             }
226         }
227
228         return result;
229     }
230
231     /**
232      * Prepare non-conditional XPath suitable for deserialization with {@link StringModuleInstanceIdentifierCodec}.
233      *
234      * @param schemaNode Top schema node
235      * @param target Edit operation target
236      * @param value Element with value
237      * @param namespace Module namespace
238      * @param revision Module revision
239      * @return Non-conditional XPath
240      */
241     private static String prepareNonCondXpath(@Nonnull final DataSchemaNode schemaNode, @Nonnull final String target,
242             @Nonnull final Element value, @Nonnull final String namespace, @Nonnull final String revision) {
243         final Iterator<String> args = Splitter.on("/").split(target.substring(target.indexOf(':') + 1)).iterator();
244
245         final StringBuilder nonCondXpath = new StringBuilder();
246         SchemaNode childNode = schemaNode;
247
248         while (args.hasNext()) {
249             final String s = args.next();
250             nonCondXpath.append("/");
251             nonCondXpath.append(s);
252             childNode = ((DataNodeContainer) childNode).getDataChildByName(QName.create(namespace, revision, s));
253
254             if (childNode instanceof ListSchemaNode && args.hasNext()) {
255                 appendKeys(nonCondXpath, ((ListSchemaNode) childNode).getKeyDefinition().iterator(), args);
256             }
257         }
258
259         if (childNode instanceof ListSchemaNode && value != null) {
260             final Iterator<String> keyValues = readKeyValues(value,
261                     ((ListSchemaNode) childNode).getKeyDefinition().iterator());
262             appendKeys(nonCondXpath, ((ListSchemaNode) childNode).getKeyDefinition().iterator(), keyValues);
263         }
264
265         return nonCondXpath.toString();
266     }
267
268     /**
269      * Read value for every list key.
270      *
271      * @param value Value element
272      * @param keys Iterator of list keys names
273      * @return Iterator of list keys values
274      */
275     private static Iterator<String> readKeyValues(@Nonnull final Element value, @Nonnull final Iterator<QName> keys) {
276         final List<String> result = new ArrayList<>();
277
278         while (keys.hasNext()) {
279             result.add(value.getElementsByTagName(keys.next().getLocalName()).item(0).getFirstChild().getNodeValue());
280         }
281
282         return result.iterator();
283     }
284
285     /**
286      * Append key name - key value pairs for every list key to {@code nonCondXpath}.
287      *
288      * @param nonCondXpath Builder for creating non-conditional XPath
289      * @param keyNames Iterator of list keys names
290      * @param keyValues Iterator of list keys values
291      */
292     private static void appendKeys(@Nonnull final StringBuilder nonCondXpath, @Nonnull final Iterator<QName> keyNames,
293                             @Nonnull final Iterator<String> keyValues) {
294         while (keyNames.hasNext()) {
295             nonCondXpath.append("[");
296             nonCondXpath.append(keyNames.next().getLocalName());
297             nonCondXpath.append("=");
298             nonCondXpath.append("'");
299             nonCondXpath.append(keyValues.next());
300             nonCondXpath.append("'");
301             nonCondXpath.append("]");
302         }
303     }
304 }