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