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