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.jersey.providers;
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 javax.annotation.Nonnull;
21 import javax.ws.rs.Consumes;
22 import javax.ws.rs.WebApplicationException;
23 import javax.ws.rs.ext.Provider;
24 import javax.xml.parsers.ParserConfigurationException;
25 import javax.xml.stream.XMLStreamException;
26 import javax.xml.transform.dom.DOMSource;
27 import org.opendaylight.restconf.Rfc8040;
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.utils.RestconfConstants;
36 import org.opendaylight.yangtools.util.xml.UntrustedXML;
37 import org.opendaylight.yangtools.yang.common.QName;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
40 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
42 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
43 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
44 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
45 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
47 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.Module;
50 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
51 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import org.w3c.dom.Document;
55 import org.w3c.dom.Element;
56 import org.w3c.dom.Node;
57 import org.w3c.dom.NodeList;
58 import org.xml.sax.SAXException;
61 @Consumes({Rfc8040.MediaTypes.PATCH + RestconfConstants.XML})
62 public class XmlToPatchBodyReader extends AbstractToPatchBodyReader {
63 private static final Logger LOG = LoggerFactory.getLogger(XmlToPatchBodyReader.class);
64 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
66 @SuppressWarnings("checkstyle:IllegalCatch")
68 protected PatchContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
69 throws IOException, WebApplicationException {
71 final Document doc = UntrustedXML.newDocumentBuilder().parse(entityStream);
72 return parse(path, doc);
73 } catch (final RestconfDocumentedException e) {
75 } catch (final Exception e) {
76 LOG.debug("Error parsing xml input", e);
78 throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
79 ErrorTag.MALFORMED_MESSAGE);
83 private static PatchContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc)
84 throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
85 final List<PatchEntity> resultCollection = new ArrayList<>();
86 final String patchId = doc.getElementsByTagName("patch-id").item(0).getFirstChild().getNodeValue();
87 final NodeList editNodes = doc.getElementsByTagName("edit");
89 for (int i = 0; i < editNodes.getLength(); i++) {
90 DataSchemaNode schemaNode = (DataSchemaNode) pathContext.getSchemaNode();
91 final Element element = (Element) editNodes.item(i);
92 final String operation = element.getElementsByTagName("operation").item(0).getFirstChild().getNodeValue();
93 final PatchEditOperation oper = PatchEditOperation.valueOf(operation.toUpperCase());
94 final String editId = element.getElementsByTagName("edit-id").item(0).getFirstChild().getNodeValue();
95 final String target = element.getElementsByTagName("target").item(0).getFirstChild().getNodeValue();
96 final List<Element> values = readValueNodes(element, oper);
97 final Element firstValueElement = values != null ? values.get(0) : null;
99 // get namespace according to schema node from path context or value
100 final String namespace = firstValueElement == null
101 ? schemaNode.getQName().getNamespace().toString() : firstValueElement.getNamespaceURI();
103 // find module according to namespace
104 final Module module = pathContext.getSchemaContext().findModuleByNamespace(
105 URI.create(namespace)).iterator().next();
107 // initialize codec + set default prefix derived from module name
108 final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
109 pathContext.getSchemaContext(), module.getName());
111 // find complete path to target and target schema node
112 // target can be also empty (only slash)
113 YangInstanceIdentifier targetII;
114 final SchemaNode targetNode;
115 if (target.equals("/")) {
116 targetII = pathContext.getInstanceIdentifier();
117 targetNode = pathContext.getSchemaContext();
119 targetII = codec.deserialize(codec.serialize(pathContext.getInstanceIdentifier())
120 .concat(prepareNonCondXpath(schemaNode, target.replaceFirst("/", ""), firstValueElement,
121 namespace, module.getQNameModule().getFormattedRevision())));
123 targetNode = SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(),
124 codec.getDataContextTree().getChild(targetII).getDataSchemaNode().getPath().getParent());
127 schemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(),
128 codec.getDataContextTree().getChild(targetII).getDataSchemaNode().getPath());
131 if (targetNode == null) {
132 LOG.debug("Target node {} not found in path {} ", target, pathContext.getSchemaNode());
133 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL,
134 ErrorTag.MALFORMED_MESSAGE);
137 if (oper.isWithValue()) {
138 final NormalizedNode<?, ?> parsed;
139 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
140 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
141 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
142 final XmlParserStream xmlParser = XmlParserStream.create(writer, pathContext.getSchemaContext(),
144 xmlParser.traverse(new DOMSource(firstValueElement));
145 parsed = resultHolder.getResult();
150 // for lists allow to manipulate with list items through their parent
151 if (targetII.getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
152 targetII = targetII.getParent();
155 resultCollection.add(new PatchEntity(editId, oper, targetII, parsed));
157 resultCollection.add(new PatchEntity(editId, oper, targetII));
161 return new PatchContext(pathContext, ImmutableList.copyOf(resultCollection), patchId);
167 * @param element Element of current edit operation
168 * @param operation Name of current operation
169 * @return List of value elements
171 private static List<Element> readValueNodes(@Nonnull final Element element,
172 @Nonnull final PatchEditOperation operation) {
173 final Node valueNode = element.getElementsByTagName("value").item(0);
175 if (operation.isWithValue() && valueNode == null) {
176 throw new RestconfDocumentedException("Error parsing input",
177 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
180 if (!operation.isWithValue() && valueNode != null) {
181 throw new RestconfDocumentedException("Error parsing input",
182 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
185 if (valueNode == null) {
189 final List<Element> result = new ArrayList<>();
190 final NodeList childNodes = valueNode.getChildNodes();
191 for (int i = 0; i < childNodes.getLength(); i++) {
192 if (childNodes.item(i) instanceof Element) {
193 result.add((Element) childNodes.item(i));
201 * Prepare non-conditional XPath suitable for deserialization with {@link StringModuleInstanceIdentifierCodec}.
203 * @param schemaNode Top schema node
204 * @param target Edit operation target
205 * @param value Element with value
206 * @param namespace Module namespace
207 * @param revision Module revision
208 * @return Non-conditional XPath
210 private static String prepareNonCondXpath(@Nonnull final DataSchemaNode schemaNode, @Nonnull final String target,
211 @Nonnull final Element value, @Nonnull final String namespace, @Nonnull final String revision) {
212 final Iterator<String> args = SLASH_SPLITTER.split(target.substring(target.indexOf(':') + 1)).iterator();
214 final StringBuilder nonCondXpath = new StringBuilder();
215 SchemaNode childNode = schemaNode;
217 while (args.hasNext()) {
218 final String s = args.next();
219 nonCondXpath.append("/");
220 nonCondXpath.append(s);
221 childNode = ((DataNodeContainer) childNode).getDataChildByName(QName.create(namespace, revision, s));
223 if (childNode instanceof ListSchemaNode && args.hasNext()) {
224 appendKeys(nonCondXpath, ((ListSchemaNode) childNode).getKeyDefinition().iterator(), args);
228 if (childNode instanceof ListSchemaNode && value != null) {
229 final Iterator<String> keyValues = readKeyValues(value,
230 ((ListSchemaNode) childNode).getKeyDefinition().iterator());
231 appendKeys(nonCondXpath, ((ListSchemaNode) childNode).getKeyDefinition().iterator(), keyValues);
234 return nonCondXpath.toString();
238 * Read value for every list key.
240 * @param value Value element
241 * @param keys Iterator of list keys names
242 * @return Iterator of list keys values
244 private static Iterator<String> readKeyValues(@Nonnull final Element value, @Nonnull final Iterator<QName> keys) {
245 final List<String> result = new ArrayList<>();
247 while (keys.hasNext()) {
248 result.add(value.getElementsByTagName(keys.next().getLocalName()).item(0).getFirstChild().getNodeValue());
251 return result.iterator();
255 * Append key name - key value pairs for every list key to {@code nonCondXpath}.
257 * @param nonCondXpath Builder for creating non-conditional XPath
258 * @param keyNames Iterator of list keys names
259 * @param keyValues Iterator of list keys values
261 private static void appendKeys(@Nonnull final StringBuilder nonCondXpath, @Nonnull final Iterator<QName> keyNames,
262 @Nonnull final Iterator<String> keyValues) {
263 while (keyNames.hasNext()) {
264 nonCondXpath.append('[');
265 nonCondXpath.append(keyNames.next().getLocalName());
266 nonCondXpath.append("='");
267 nonCondXpath.append(keyValues.next());
268 nonCondXpath.append("']");