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