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