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
9 package org.opendaylight.restconf.nb.rfc8040.jersey.providers.patch;
11 import com.google.common.base.Splitter;
12 import com.google.common.collect.ImmutableList;
13 import java.io.IOException;
14 import java.io.InputStream;
16 import java.net.URISyntaxException;
17 import java.util.ArrayList;
18 import java.util.Iterator;
19 import java.util.List;
20 import java.util.Locale;
21 import javax.annotation.Nonnull;
22 import javax.ws.rs.Consumes;
23 import javax.ws.rs.WebApplicationException;
24 import javax.ws.rs.ext.Provider;
25 import javax.xml.parsers.ParserConfigurationException;
26 import javax.xml.stream.XMLStreamException;
27 import javax.xml.transform.dom.DOMSource;
28 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
29 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
30 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
31 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
32 import org.opendaylight.restconf.common.patch.PatchContext;
33 import org.opendaylight.restconf.common.patch.PatchEditOperation;
34 import org.opendaylight.restconf.common.patch.PatchEntity;
35 import org.opendaylight.restconf.nb.rfc8040.Rfc8040;
36 import org.opendaylight.restconf.nb.rfc8040.codecs.StringModuleInstanceIdentifierCodec;
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 super(schemaContextHandler);
74 @SuppressWarnings("checkstyle:IllegalCatch")
76 protected PatchContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
77 throws IOException, WebApplicationException {
79 final Document doc = UntrustedXML.newDocumentBuilder().parse(entityStream);
80 return parse(path, doc);
81 } catch (final RestconfDocumentedException e) {
83 } catch (final Exception e) {
84 LOG.debug("Error parsing xml input", e);
86 throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
87 ErrorTag.MALFORMED_MESSAGE, e);
91 private static PatchContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc)
92 throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
93 final List<PatchEntity> resultCollection = new ArrayList<>();
94 final String patchId = doc.getElementsByTagName("patch-id").item(0).getFirstChild().getNodeValue();
95 final NodeList editNodes = doc.getElementsByTagName("edit");
97 for (int i = 0; i < editNodes.getLength(); i++) {
98 DataSchemaNode schemaNode = (DataSchemaNode) pathContext.getSchemaNode();
99 final Element element = (Element) editNodes.item(i);
100 final String operation = element.getElementsByTagName("operation").item(0).getFirstChild().getNodeValue();
101 final PatchEditOperation oper = PatchEditOperation.valueOf(operation.toUpperCase(Locale.ROOT));
102 final String editId = element.getElementsByTagName("edit-id").item(0).getFirstChild().getNodeValue();
103 final String target = element.getElementsByTagName("target").item(0).getFirstChild().getNodeValue();
104 final List<Element> values = readValueNodes(element, oper);
105 final Element firstValueElement = values != null ? values.get(0) : null;
107 // get namespace according to schema node from path context or value
108 final String namespace = firstValueElement == null
109 ? schemaNode.getQName().getNamespace().toString() : firstValueElement.getNamespaceURI();
111 // find module according to namespace
112 final Module module = pathContext.getSchemaContext().findModules(URI.create(namespace)).iterator().next();
114 // initialize codec + set default prefix derived from module name
115 final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
116 pathContext.getSchemaContext(), module.getName());
118 // find complete path to target and target schema node
119 // target can be also empty (only slash)
120 YangInstanceIdentifier targetII;
121 final SchemaNode targetNode;
122 if (target.equals("/")) {
123 targetII = pathContext.getInstanceIdentifier();
124 targetNode = pathContext.getSchemaContext();
126 targetII = codec.deserialize(codec.serialize(pathContext.getInstanceIdentifier())
127 .concat(prepareNonCondXpath(schemaNode, target.replaceFirst("/", ""), firstValueElement,
129 module.getQNameModule().getRevision().map(Revision::toString).orElse(null))));
131 targetNode = SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(),
132 codec.getDataContextTree().getChild(targetII).getDataSchemaNode().getPath().getParent());
135 schemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(),
136 codec.getDataContextTree().getChild(targetII).getDataSchemaNode().getPath());
139 if (targetNode == null) {
140 LOG.debug("Target node {} not found in path {} ", target, pathContext.getSchemaNode());
141 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL,
142 ErrorTag.MALFORMED_MESSAGE);
145 if (oper.isWithValue()) {
146 final NormalizedNode<?, ?> parsed;
147 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
148 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
149 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
150 final XmlParserStream xmlParser = XmlParserStream.create(writer, pathContext.getSchemaContext(),
152 xmlParser.traverse(new DOMSource(firstValueElement));
153 parsed = resultHolder.getResult();
158 // for lists allow to manipulate with list items through their parent
159 if (targetII.getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
160 targetII = targetII.getParent();
163 resultCollection.add(new PatchEntity(editId, oper, targetII, parsed));
165 resultCollection.add(new PatchEntity(editId, oper, targetII));
169 return new PatchContext(pathContext, ImmutableList.copyOf(resultCollection), patchId);
175 * @param element Element of current edit operation
176 * @param operation Name of current operation
177 * @return List of value elements
179 private static List<Element> readValueNodes(@Nonnull final Element element,
180 @Nonnull final PatchEditOperation operation) {
181 final Node valueNode = element.getElementsByTagName("value").item(0);
183 if (operation.isWithValue() && valueNode == null) {
184 throw new RestconfDocumentedException("Error parsing input",
185 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
188 if (!operation.isWithValue() && valueNode != null) {
189 throw new RestconfDocumentedException("Error parsing input",
190 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
193 if (valueNode == null) {
197 final List<Element> result = new ArrayList<>();
198 final NodeList childNodes = valueNode.getChildNodes();
199 for (int i = 0; i < childNodes.getLength(); i++) {
200 if (childNodes.item(i) instanceof Element) {
201 result.add((Element) childNodes.item(i));
209 * Prepare non-conditional XPath suitable for deserialization with {@link StringModuleInstanceIdentifierCodec}.
211 * @param schemaNode Top schema node
212 * @param target Edit operation target
213 * @param value Element with value
214 * @param namespace Module namespace
215 * @param revision Module revision
216 * @return Non-conditional XPath
218 private static String prepareNonCondXpath(@Nonnull final DataSchemaNode schemaNode, @Nonnull final String target,
219 @Nonnull final Element value, @Nonnull final String namespace, @Nonnull final String revision) {
220 final Iterator<String> args = SLASH_SPLITTER.split(target.substring(target.indexOf(':') + 1)).iterator();
222 final StringBuilder nonCondXpath = new StringBuilder();
223 SchemaNode childNode = schemaNode;
225 while (args.hasNext()) {
226 final String s = args.next();
227 nonCondXpath.append("/");
228 nonCondXpath.append(s);
229 childNode = ((DataNodeContainer) childNode).getDataChildByName(QName.create(namespace, revision, s));
231 if (childNode instanceof ListSchemaNode && args.hasNext()) {
232 appendKeys(nonCondXpath, ((ListSchemaNode) childNode).getKeyDefinition().iterator(), args);
236 if (childNode instanceof ListSchemaNode && value != null) {
237 final Iterator<String> keyValues = readKeyValues(value,
238 ((ListSchemaNode) childNode).getKeyDefinition().iterator());
239 appendKeys(nonCondXpath, ((ListSchemaNode) childNode).getKeyDefinition().iterator(), keyValues);
242 return nonCondXpath.toString();
246 * Read value for every list key.
248 * @param value Value element
249 * @param keys Iterator of list keys names
250 * @return Iterator of list keys values
252 private static Iterator<String> readKeyValues(@Nonnull final Element value, @Nonnull final Iterator<QName> keys) {
253 final List<String> result = new ArrayList<>();
255 while (keys.hasNext()) {
256 result.add(value.getElementsByTagName(keys.next().getLocalName()).item(0).getFirstChild().getNodeValue());
259 return result.iterator();
263 * Append key name - key value pairs for every list key to {@code nonCondXpath}.
265 * @param nonCondXpath Builder for creating non-conditional XPath
266 * @param keyNames Iterator of list keys names
267 * @param keyValues Iterator of list keys values
269 private static void appendKeys(@Nonnull final StringBuilder nonCondXpath, @Nonnull final Iterator<QName> keyNames,
270 @Nonnull final Iterator<String> keyValues) {
271 while (keyNames.hasNext()) {
272 nonCondXpath.append('[');
273 nonCondXpath.append(keyNames.next().getLocalName());
274 nonCondXpath.append("='");
275 nonCondXpath.append(keyValues.next());
276 nonCondXpath.append("']");