8364572de4874a2e2b8ca807e07375e9805eab32
[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
9 package org.opendaylight.restconf.nb.rfc8040.jersey.providers.patch;
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.net.URI;
16 import java.net.URISyntaxException;
17 import java.util.ArrayList;
18 import java.util.Iterator;
19 import java.util.List;
20 import java.util.Locale;
21 import javax.annotation.Nonnull;
22 import javax.ws.rs.Consumes;
23 import javax.ws.rs.WebApplicationException;
24 import javax.ws.rs.ext.Provider;
25 import javax.xml.parsers.ParserConfigurationException;
26 import javax.xml.stream.XMLStreamException;
27 import javax.xml.transform.dom.DOMSource;
28 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
29 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
30 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
31 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
32 import org.opendaylight.restconf.common.patch.PatchContext;
33 import org.opendaylight.restconf.common.patch.PatchEditOperation;
34 import org.opendaylight.restconf.common.patch.PatchEntity;
35 import org.opendaylight.restconf.nb.rfc8040.Rfc8040;
36 import org.opendaylight.restconf.nb.rfc8040.codecs.StringModuleInstanceIdentifierCodec;
37 import org.opendaylight.restconf.nb.rfc8040.handlers.DOMMountPointServiceHandler;
38 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
39 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
40 import org.opendaylight.yangtools.util.xml.UntrustedXML;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.common.Revision;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
45 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
46 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
47 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
48 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
49 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
50 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
52 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.Module;
55 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
56 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59 import org.w3c.dom.Document;
60 import org.w3c.dom.Element;
61 import org.w3c.dom.Node;
62 import org.w3c.dom.NodeList;
63 import org.xml.sax.SAXException;
64
65 @Provider
66 @Consumes({Rfc8040.MediaTypes.PATCH + RestconfConstants.XML})
67 public class XmlToPatchBodyReader extends AbstractToPatchBodyReader {
68     private static final Logger LOG = LoggerFactory.getLogger(XmlToPatchBodyReader.class);
69     private static final Splitter SLASH_SPLITTER = Splitter.on('/');
70
71     public XmlToPatchBodyReader(SchemaContextHandler schemaContextHandler,
72             DOMMountPointServiceHandler mountPointServiceHandler) {
73         super(schemaContextHandler, mountPointServiceHandler);
74     }
75
76     @SuppressWarnings("checkstyle:IllegalCatch")
77     @Override
78     protected PatchContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
79             throws IOException, WebApplicationException {
80         try {
81             final Document doc = UntrustedXML.newDocumentBuilder().parse(entityStream);
82             return parse(path, doc);
83         } catch (final RestconfDocumentedException e) {
84             throw e;
85         } catch (final Exception e) {
86             LOG.debug("Error parsing xml input", e);
87
88             throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
89                     ErrorTag.MALFORMED_MESSAGE, e);
90         }
91     }
92
93     private static PatchContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc)
94             throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
95         final List<PatchEntity> resultCollection = new ArrayList<>();
96         final String patchId = doc.getElementsByTagName("patch-id").item(0).getFirstChild().getNodeValue();
97         final NodeList editNodes = doc.getElementsByTagName("edit");
98
99         for (int i = 0; i < editNodes.getLength(); i++) {
100             DataSchemaNode schemaNode = (DataSchemaNode) pathContext.getSchemaNode();
101             final Element element = (Element) editNodes.item(i);
102             final String operation = element.getElementsByTagName("operation").item(0).getFirstChild().getNodeValue();
103             final PatchEditOperation oper = PatchEditOperation.valueOf(operation.toUpperCase(Locale.ROOT));
104             final String editId = element.getElementsByTagName("edit-id").item(0).getFirstChild().getNodeValue();
105             final String target = element.getElementsByTagName("target").item(0).getFirstChild().getNodeValue();
106             final List<Element> values = readValueNodes(element, oper);
107             final Element firstValueElement = values != null ? values.get(0) : null;
108
109             // get namespace according to schema node from path context or value
110             final String namespace = firstValueElement == null
111                     ? schemaNode.getQName().getNamespace().toString() : firstValueElement.getNamespaceURI();
112
113             // find module according to namespace
114             final Module module = pathContext.getSchemaContext().findModules(URI.create(namespace)).iterator().next();
115
116             // initialize codec + set default prefix derived from module name
117             final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
118                     pathContext.getSchemaContext(), module.getName());
119
120             // find complete path to target and target schema node
121             // target can be also empty (only slash)
122             YangInstanceIdentifier targetII;
123             final SchemaNode targetNode;
124             if (target.equals("/")) {
125                 targetII = pathContext.getInstanceIdentifier();
126                 targetNode = pathContext.getSchemaContext();
127             } else {
128                 targetII = codec.deserialize(codec.serialize(pathContext.getInstanceIdentifier())
129                         .concat(prepareNonCondXpath(schemaNode, target.replaceFirst("/", ""), firstValueElement,
130                                 namespace,
131                                 module.getQNameModule().getRevision().map(Revision::toString).orElse(null))));
132
133                 targetNode = SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(),
134                         codec.getDataContextTree().getChild(targetII).getDataSchemaNode().getPath().getParent());
135
136                 // move schema node
137                 schemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(),
138                         codec.getDataContextTree().getChild(targetII).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(@Nonnull final Element element,
182             @Nonnull final 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(@Nonnull final DataSchemaNode schemaNode, @Nonnull final String target,
221             @Nonnull final Element value, @Nonnull final String namespace, @Nonnull final 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(@Nonnull final Element value, @Nonnull final 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(@Nonnull final StringBuilder nonCondXpath, @Nonnull final Iterator<QName> keyNames,
272                             @Nonnull final Iterator<String> keyValues) {
273         while (keyNames.hasNext()) {
274             nonCondXpath.append('[');
275             nonCondXpath.append(keyNames.next().getLocalName());
276             nonCondXpath.append("='");
277             nonCondXpath.append(keyValues.next());
278             nonCondXpath.append("']");
279         }
280     }
281 }