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