2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.netconf.sal.rest.impl;
10 import com.google.common.base.Splitter;
11 import com.google.common.collect.ImmutableList;
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.lang.annotation.Annotation;
15 import java.lang.reflect.Type;
17 import java.net.URISyntaxException;
18 import java.util.ArrayList;
19 import java.util.Iterator;
20 import java.util.List;
21 import java.util.Locale;
22 import java.util.Optional;
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.eclipse.jdt.annotation.NonNull;
33 import org.opendaylight.netconf.sal.rest.api.Draft02;
34 import org.opendaylight.netconf.sal.rest.api.RestconfService;
35 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
36 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
37 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
38 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
39 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
40 import org.opendaylight.restconf.common.patch.PatchContext;
41 import org.opendaylight.restconf.common.patch.PatchEditOperation;
42 import org.opendaylight.restconf.common.patch.PatchEntity;
43 import org.opendaylight.restconf.common.util.RestUtil;
44 import org.opendaylight.yangtools.util.xml.UntrustedXML;
45 import org.opendaylight.yangtools.yang.common.QName;
46 import org.opendaylight.yangtools.yang.common.Revision;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
49 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
51 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
52 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
53 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
54 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
56 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.Module;
59 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
60 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63 import org.w3c.dom.Document;
64 import org.w3c.dom.Element;
65 import org.w3c.dom.Node;
66 import org.w3c.dom.NodeList;
67 import org.xml.sax.SAXException;
70 * Yang PATCH Reader for XML.
72 * @deprecated This class will be replaced by XmlToPatchBodyReader from restconf-nb-rfc8040
76 @Consumes({Draft02.MediaTypes.PATCH + RestconfService.XML})
77 public class XmlToPatchBodyReader extends AbstractIdentifierAwareJaxRsProvider implements
78 MessageBodyReader<PatchContext> {
80 private static final Logger LOG = LoggerFactory.getLogger(XmlToPatchBodyReader.class);
82 public XmlToPatchBodyReader(ControllerContext controllerContext) {
83 super(controllerContext);
87 public boolean isReadable(final Class<?> type, final Type genericType,
88 final Annotation[] annotations, final MediaType mediaType) {
92 @SuppressWarnings("checkstyle:IllegalCatch")
94 public PatchContext readFrom(final Class<PatchContext> type, final Type genericType,
95 final Annotation[] annotations, final MediaType mediaType,
96 final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream)
97 throws WebApplicationException {
100 final InstanceIdentifierContext<?> path = getInstanceIdentifierContext();
101 final Optional<InputStream> nonEmptyInputStreamOptional = RestUtil.isInputStreamEmpty(entityStream);
102 if (!nonEmptyInputStreamOptional.isPresent()) {
103 // represent empty nopayload input
104 return new PatchContext(path, null, null);
107 final Document doc = UntrustedXML.newDocumentBuilder().parse(nonEmptyInputStreamOptional.get());
108 return parse(path, doc);
109 } catch (final RestconfDocumentedException e) {
111 } catch (final Exception e) {
112 LOG.debug("Error parsing xml input", e);
114 throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
115 ErrorTag.MALFORMED_MESSAGE, e);
119 private static PatchContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc)
120 throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
121 final List<PatchEntity> resultCollection = new ArrayList<>();
122 final String patchId = doc.getElementsByTagName("patch-id").item(0).getFirstChild().getNodeValue();
123 final NodeList editNodes = doc.getElementsByTagName("edit");
125 for (int i = 0; i < editNodes.getLength(); i++) {
126 DataSchemaNode schemaNode = (DataSchemaNode) pathContext.getSchemaNode();
127 final Element element = (Element) editNodes.item(i);
128 final String operation = element.getElementsByTagName("operation").item(0).getFirstChild().getNodeValue();
129 final PatchEditOperation oper = PatchEditOperation.valueOf(operation.toUpperCase(Locale.ROOT));
131 final String editId = element.getElementsByTagName("edit-id").item(0).getFirstChild().getNodeValue();
132 final String target = element.getElementsByTagName("target").item(0).getFirstChild().getNodeValue();
133 final List<Element> values = readValueNodes(element, oper);
134 final Element firstValueElement = values != null ? values.get(0) : null;
136 // get namespace according to schema node from path context or value
137 final String namespace = firstValueElement == null
138 ? schemaNode.getQName().getNamespace().toString() : firstValueElement.getNamespaceURI();
140 // find module according to namespace
141 final Module module = pathContext.getSchemaContext().findModules(URI.create(namespace)).iterator().next();
143 // initialize codec + set default prefix derived from module name
144 final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
145 pathContext.getSchemaContext(), module.getName());
147 // find complete path to target and target schema node
148 // target can be also empty (only slash)
149 YangInstanceIdentifier targetII;
150 final SchemaNode targetNode;
151 if (target.equals("/")) {
152 targetII = pathContext.getInstanceIdentifier();
153 targetNode = pathContext.getSchemaContext();
155 targetII = codec.deserialize(codec.serialize(pathContext.getInstanceIdentifier())
156 .concat(prepareNonCondXpath(schemaNode, target.replaceFirst("/", ""), firstValueElement,
158 module.getQNameModule().getRevision().map(Revision::toString).orElse(null))));
160 targetNode = SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(),
161 codec.getDataContextTree().getChild(targetII).getDataSchemaNode().getPath().getParent());
164 schemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(),
165 codec.getDataContextTree().getChild(targetII).getDataSchemaNode().getPath());
168 if (targetNode == null) {
169 LOG.debug("Target node {} not found in path {} ", target, pathContext.getSchemaNode());
170 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL,
171 ErrorTag.MALFORMED_MESSAGE);
174 if (oper.isWithValue()) {
175 final NormalizedNode<?, ?> parsed;
176 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
177 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
178 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
179 final XmlParserStream xmlParser = XmlParserStream.create(writer, pathContext.getSchemaContext(),
181 xmlParser.traverse(new DOMSource(firstValueElement));
182 parsed = resultHolder.getResult();
187 // for lists allow to manipulate with list items through their parent
188 if (targetII.getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
189 targetII = targetII.getParent();
192 resultCollection.add(new PatchEntity(editId, oper, targetII, parsed));
194 resultCollection.add(new PatchEntity(editId, oper, targetII));
198 return new PatchContext(pathContext, ImmutableList.copyOf(resultCollection), patchId);
204 * @param element Element of current edit operation
205 * @param operation Name of current operation
206 * @return List of value elements
208 private static List<Element> readValueNodes(final @NonNull Element element,
209 final @NonNull PatchEditOperation operation) {
210 final Node valueNode = element.getElementsByTagName("value").item(0);
212 if (operation.isWithValue() && valueNode == null) {
213 throw new RestconfDocumentedException("Error parsing input",
214 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
217 if (!operation.isWithValue() && valueNode != null) {
218 throw new RestconfDocumentedException("Error parsing input",
219 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
222 if (valueNode == null) {
226 final List<Element> result = new ArrayList<>();
227 final NodeList childNodes = valueNode.getChildNodes();
228 for (int i = 0; i < childNodes.getLength(); i++) {
229 if (childNodes.item(i) instanceof Element) {
230 result.add((Element) childNodes.item(i));
238 * Prepare non-conditional XPath suitable for deserialization with {@link StringModuleInstanceIdentifierCodec}.
240 * @param schemaNode Top schema node
241 * @param target Edit operation target
242 * @param value Element with value
243 * @param namespace Module namespace
244 * @param revision Module revision
245 * @return Non-conditional XPath
247 private static String prepareNonCondXpath(final @NonNull DataSchemaNode schemaNode, final @NonNull String target,
248 final @NonNull Element value, final @NonNull String namespace, final @NonNull String revision) {
249 final Iterator<String> args = Splitter.on("/").split(target.substring(target.indexOf(':') + 1)).iterator();
251 final StringBuilder nonCondXpath = new StringBuilder();
252 SchemaNode childNode = schemaNode;
254 while (args.hasNext()) {
255 final String s = args.next();
256 nonCondXpath.append("/");
257 nonCondXpath.append(s);
258 childNode = ((DataNodeContainer) childNode).getDataChildByName(QName.create(namespace, revision, s));
260 if (childNode instanceof ListSchemaNode && args.hasNext()) {
261 appendKeys(nonCondXpath, ((ListSchemaNode) childNode).getKeyDefinition().iterator(), args);
265 if (childNode instanceof ListSchemaNode && value != null) {
266 final Iterator<String> keyValues = readKeyValues(value,
267 ((ListSchemaNode) childNode).getKeyDefinition().iterator());
268 appendKeys(nonCondXpath, ((ListSchemaNode) childNode).getKeyDefinition().iterator(), keyValues);
271 return nonCondXpath.toString();
275 * Read value for every list key.
277 * @param value Value element
278 * @param keys Iterator of list keys names
279 * @return Iterator of list keys values
281 private static Iterator<String> readKeyValues(final @NonNull Element value, final @NonNull Iterator<QName> keys) {
282 final List<String> result = new ArrayList<>();
284 while (keys.hasNext()) {
285 result.add(value.getElementsByTagName(keys.next().getLocalName()).item(0).getFirstChild().getNodeValue());
288 return result.iterator();
292 * Append key name - key value pairs for every list key to {@code nonCondXpath}.
294 * @param nonCondXpath Builder for creating non-conditional XPath
295 * @param keyNames Iterator of list keys names
296 * @param keyValues Iterator of list keys values
298 private static void appendKeys(final @NonNull StringBuilder nonCondXpath, final @NonNull Iterator<QName> keyNames,
299 final @NonNull Iterator<String> keyValues) {
300 while (keyNames.hasNext()) {
301 nonCondXpath.append("[").append(keyNames.next().getLocalName()).append("='").append(keyValues.next())