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