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