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