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