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