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