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