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