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