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