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