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