2 * Copyright (c) 2016 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.restconf.nb.rfc8040.jersey.providers.patch;
10 import com.google.common.base.Splitter;
11 import com.google.common.collect.ImmutableList;
12 import java.io.IOException;
13 import java.io.InputStream;
15 import java.net.URISyntaxException;
16 import java.util.ArrayList;
17 import java.util.Iterator;
18 import java.util.List;
19 import java.util.Locale;
20 import javax.ws.rs.Consumes;
21 import javax.ws.rs.WebApplicationException;
22 import javax.ws.rs.ext.Provider;
23 import javax.xml.parsers.ParserConfigurationException;
24 import javax.xml.stream.XMLStreamException;
25 import javax.xml.transform.dom.DOMSource;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
28 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
29 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
30 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
31 import org.opendaylight.restconf.common.patch.PatchContext;
32 import org.opendaylight.restconf.common.patch.PatchEditOperation;
33 import org.opendaylight.restconf.common.patch.PatchEntity;
34 import org.opendaylight.restconf.nb.rfc8040.Rfc8040;
35 import org.opendaylight.restconf.nb.rfc8040.codecs.StringModuleInstanceIdentifierCodec;
36 import org.opendaylight.restconf.nb.rfc8040.handlers.DOMMountPointServiceHandler;
37 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
38 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
39 import org.opendaylight.yangtools.util.xml.UntrustedXML;
40 import org.opendaylight.yangtools.yang.common.QName;
41 import org.opendaylight.yangtools.yang.common.Revision;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
44 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
46 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
47 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
48 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
49 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
51 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.Module;
54 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
55 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58 import org.w3c.dom.Document;
59 import org.w3c.dom.Element;
60 import org.w3c.dom.Node;
61 import org.w3c.dom.NodeList;
62 import org.xml.sax.SAXException;
65 @Consumes({Rfc8040.MediaTypes.PATCH + RestconfConstants.XML})
66 public class XmlToPatchBodyReader extends AbstractToPatchBodyReader {
67 private static final Logger LOG = LoggerFactory.getLogger(XmlToPatchBodyReader.class);
68 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
70 public XmlToPatchBodyReader(SchemaContextHandler schemaContextHandler,
71 DOMMountPointServiceHandler mountPointServiceHandler) {
72 super(schemaContextHandler, mountPointServiceHandler);
75 @SuppressWarnings("checkstyle:IllegalCatch")
77 protected PatchContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
78 throws WebApplicationException {
80 final Document doc = UntrustedXML.newDocumentBuilder().parse(entityStream);
81 return parse(path, doc);
82 } catch (final RestconfDocumentedException e) {
84 } catch (final Exception e) {
85 LOG.debug("Error parsing xml input", e);
87 throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
88 ErrorTag.MALFORMED_MESSAGE, e);
92 private static PatchContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc)
93 throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
94 final List<PatchEntity> resultCollection = new ArrayList<>();
95 final String patchId = doc.getElementsByTagName("patch-id").item(0).getFirstChild().getNodeValue();
96 final NodeList editNodes = doc.getElementsByTagName("edit");
98 for (int i = 0; i < editNodes.getLength(); i++) {
99 DataSchemaNode schemaNode = (DataSchemaNode) pathContext.getSchemaNode();
100 final Element element = (Element) editNodes.item(i);
101 final String operation = element.getElementsByTagName("operation").item(0).getFirstChild().getNodeValue();
102 final PatchEditOperation oper = PatchEditOperation.valueOf(operation.toUpperCase(Locale.ROOT));
103 final String editId = element.getElementsByTagName("edit-id").item(0).getFirstChild().getNodeValue();
104 final String target = element.getElementsByTagName("target").item(0).getFirstChild().getNodeValue();
105 final List<Element> values = readValueNodes(element, oper);
106 final Element firstValueElement = values != null ? values.get(0) : null;
108 // get namespace according to schema node from path context or value
109 final String namespace = firstValueElement == null
110 ? schemaNode.getQName().getNamespace().toString() : firstValueElement.getNamespaceURI();
112 // find module according to namespace
113 final Module module = pathContext.getSchemaContext().findModules(URI.create(namespace)).iterator().next();
115 // initialize codec + set default prefix derived from module name
116 final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
117 pathContext.getSchemaContext(), module.getName());
119 // find complete path to target and target schema node
120 // target can be also empty (only slash)
121 YangInstanceIdentifier targetII;
122 final SchemaNode targetNode;
123 if (target.equals("/")) {
124 targetII = pathContext.getInstanceIdentifier();
125 targetNode = pathContext.getSchemaContext();
127 targetII = codec.deserialize(codec.serialize(pathContext.getInstanceIdentifier())
128 .concat(prepareNonCondXpath(schemaNode, target.replaceFirst("/", ""), firstValueElement,
130 module.getQNameModule().getRevision().map(Revision::toString).orElse(null))));
132 targetNode = SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(),
133 codec.getDataContextTree().getChild(targetII).getDataSchemaNode().getPath().getParent());
136 schemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(),
137 codec.getDataContextTree().getChild(targetII).getDataSchemaNode().getPath());
140 if (targetNode == null) {
141 LOG.debug("Target node {} not found in path {} ", target, pathContext.getSchemaNode());
142 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL,
143 ErrorTag.MALFORMED_MESSAGE);
146 if (oper.isWithValue()) {
147 final NormalizedNode<?, ?> parsed;
148 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
149 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
150 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
151 final XmlParserStream xmlParser = XmlParserStream.create(writer, pathContext.getSchemaContext(),
153 xmlParser.traverse(new DOMSource(firstValueElement));
154 parsed = resultHolder.getResult();
159 // for lists allow to manipulate with list items through their parent
160 if (targetII.getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
161 targetII = targetII.getParent();
164 resultCollection.add(new PatchEntity(editId, oper, targetII, parsed));
166 resultCollection.add(new PatchEntity(editId, oper, targetII));
170 return new PatchContext(pathContext, ImmutableList.copyOf(resultCollection), patchId);
176 * @param element Element of current edit operation
177 * @param operation Name of current operation
178 * @return List of value elements
180 private static List<Element> readValueNodes(final @NonNull Element element,
181 final @NonNull PatchEditOperation operation) {
182 final Node valueNode = element.getElementsByTagName("value").item(0);
184 if (operation.isWithValue() && valueNode == null) {
185 throw new RestconfDocumentedException("Error parsing input",
186 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
189 if (!operation.isWithValue() && valueNode != null) {
190 throw new RestconfDocumentedException("Error parsing input",
191 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
194 if (valueNode == null) {
198 final List<Element> result = new ArrayList<>();
199 final NodeList childNodes = valueNode.getChildNodes();
200 for (int i = 0; i < childNodes.getLength(); i++) {
201 if (childNodes.item(i) instanceof Element) {
202 result.add((Element) childNodes.item(i));
210 * Prepare non-conditional XPath suitable for deserialization with {@link StringModuleInstanceIdentifierCodec}.
212 * @param schemaNode Top schema node
213 * @param target Edit operation target
214 * @param value Element with value
215 * @param namespace Module namespace
216 * @param revision Module revision
217 * @return Non-conditional XPath
219 private static String prepareNonCondXpath(final @NonNull DataSchemaNode schemaNode, final @NonNull String target,
220 final @NonNull Element value, final @NonNull String namespace, final @NonNull String revision) {
221 final Iterator<String> args = SLASH_SPLITTER.split(target.substring(target.indexOf(':') + 1)).iterator();
223 final StringBuilder nonCondXpath = new StringBuilder();
224 SchemaNode childNode = schemaNode;
226 while (args.hasNext()) {
227 final String s = args.next();
228 nonCondXpath.append("/");
229 nonCondXpath.append(s);
230 childNode = ((DataNodeContainer) childNode).getDataChildByName(QName.create(namespace, revision, s));
232 if (childNode instanceof ListSchemaNode && args.hasNext()) {
233 appendKeys(nonCondXpath, ((ListSchemaNode) childNode).getKeyDefinition().iterator(), args);
237 if (childNode instanceof ListSchemaNode && value != null) {
238 final Iterator<String> keyValues = readKeyValues(value,
239 ((ListSchemaNode) childNode).getKeyDefinition().iterator());
240 appendKeys(nonCondXpath, ((ListSchemaNode) childNode).getKeyDefinition().iterator(), keyValues);
243 return nonCondXpath.toString();
247 * Read value for every list key.
249 * @param value Value element
250 * @param keys Iterator of list keys names
251 * @return Iterator of list keys values
253 private static Iterator<String> readKeyValues(final @NonNull Element value, final @NonNull Iterator<QName> keys) {
254 final List<String> result = new ArrayList<>();
256 while (keys.hasNext()) {
257 result.add(value.getElementsByTagName(keys.next().getLocalName()).item(0).getFirstChild().getNodeValue());
260 return result.iterator();
264 * Append key name - key value pairs for every list key to {@code nonCondXpath}.
266 * @param nonCondXpath Builder for creating non-conditional XPath
267 * @param keyNames Iterator of list keys names
268 * @param keyValues Iterator of list keys values
270 private static void appendKeys(final @NonNull StringBuilder nonCondXpath, final @NonNull Iterator<QName> keyNames,
271 final @NonNull Iterator<String> keyValues) {
272 while (keyNames.hasNext()) {
273 nonCondXpath.append('[').append(keyNames.next().getLocalName()).append("='").append(keyValues.next())