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.isEmpty()) {
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().findChild(targetII).orElseThrow().getDataSchemaNode().getPath()
165 schemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(),
166 codec.getDataContextTree().findChild(targetII).orElseThrow().getDataSchemaNode().getPath());
169 if (targetNode == null) {
170 LOG.debug("Target node {} not found in path {} ", target, pathContext.getSchemaNode());
171 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL,
172 ErrorTag.MALFORMED_MESSAGE);
175 if (oper.isWithValue()) {
176 final NormalizedNode<?, ?> parsed;
177 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
178 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
179 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
180 final XmlParserStream xmlParser = XmlParserStream.create(writer, pathContext.getSchemaContext(),
182 xmlParser.traverse(new DOMSource(firstValueElement));
183 parsed = resultHolder.getResult();
188 // for lists allow to manipulate with list items through their parent
189 if (targetII.getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
190 targetII = targetII.getParent();
193 resultCollection.add(new PatchEntity(editId, oper, targetII, parsed));
195 resultCollection.add(new PatchEntity(editId, oper, targetII));
199 return new PatchContext(pathContext, ImmutableList.copyOf(resultCollection), patchId);
205 * @param element Element of current edit operation
206 * @param operation Name of current operation
207 * @return List of value elements
209 private static List<Element> readValueNodes(final @NonNull Element element,
210 final @NonNull PatchEditOperation operation) {
211 final Node valueNode = element.getElementsByTagName("value").item(0);
213 if (operation.isWithValue() && valueNode == null) {
214 throw new RestconfDocumentedException("Error parsing input",
215 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
218 if (!operation.isWithValue() && valueNode != null) {
219 throw new RestconfDocumentedException("Error parsing input",
220 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
223 if (valueNode == null) {
227 final List<Element> result = new ArrayList<>();
228 final NodeList childNodes = valueNode.getChildNodes();
229 for (int i = 0; i < childNodes.getLength(); i++) {
230 if (childNodes.item(i) instanceof Element) {
231 result.add((Element) childNodes.item(i));
239 * Prepare non-conditional XPath suitable for deserialization with {@link StringModuleInstanceIdentifierCodec}.
241 * @param schemaNode Top schema node
242 * @param target Edit operation target
243 * @param value Element with value
244 * @param namespace Module namespace
245 * @param revision Module revision
246 * @return Non-conditional XPath
248 private static String prepareNonCondXpath(final @NonNull DataSchemaNode schemaNode, final @NonNull String target,
249 final @NonNull Element value, final @NonNull String namespace, final @NonNull String revision) {
250 final Iterator<String> args = Splitter.on("/").split(target.substring(target.indexOf(':') + 1)).iterator();
252 final StringBuilder nonCondXpath = new StringBuilder();
253 SchemaNode childNode = schemaNode;
255 while (args.hasNext()) {
256 final String s = args.next();
257 nonCondXpath.append("/");
258 nonCondXpath.append(s);
259 childNode = ((DataNodeContainer) childNode).getDataChildByName(QName.create(namespace, revision, s));
261 if (childNode instanceof ListSchemaNode && args.hasNext()) {
262 appendKeys(nonCondXpath, ((ListSchemaNode) childNode).getKeyDefinition().iterator(), args);
266 if (childNode instanceof ListSchemaNode && value != null) {
267 final Iterator<String> keyValues = readKeyValues(value,
268 ((ListSchemaNode) childNode).getKeyDefinition().iterator());
269 appendKeys(nonCondXpath, ((ListSchemaNode) childNode).getKeyDefinition().iterator(), keyValues);
272 return nonCondXpath.toString();
276 * Read value for every list key.
278 * @param value Value element
279 * @param keys Iterator of list keys names
280 * @return Iterator of list keys values
282 private static Iterator<String> readKeyValues(final @NonNull Element value, final @NonNull Iterator<QName> keys) {
283 final List<String> result = new ArrayList<>();
285 while (keys.hasNext()) {
286 result.add(value.getElementsByTagName(keys.next().getLocalName()).item(0).getFirstChild().getNodeValue());
289 return result.iterator();
293 * Append key name - key value pairs for every list key to {@code nonCondXpath}.
295 * @param nonCondXpath Builder for creating non-conditional XPath
296 * @param keyNames Iterator of list keys names
297 * @param keyValues Iterator of list keys values
299 private static void appendKeys(final @NonNull StringBuilder nonCondXpath, final @NonNull Iterator<QName> keyNames,
300 final @NonNull Iterator<String> keyValues) {
301 while (keyNames.hasNext()) {
302 nonCondXpath.append("[").append(keyNames.next().getLocalName()).append("='").append(keyValues.next())