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