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