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