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 * Reader of XML to Patch.
63 * @deprecated move to splitted module restconf-nb-rfc8040
67 @Consumes({Rfc8040.MediaTypes.PATCH + RestconfConstants.XML})
68 public class XmlToPatchBodyReader extends AbstractToPatchBodyReader {
69 private static final Logger LOG = LoggerFactory.getLogger(XmlToPatchBodyReader.class);
70 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
72 @SuppressWarnings("checkstyle:IllegalCatch")
74 protected PatchContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
75 throws IOException, WebApplicationException {
77 final Document doc = UntrustedXML.newDocumentBuilder().parse(entityStream);
78 return parse(path, doc);
79 } catch (final RestconfDocumentedException e) {
81 } catch (final Exception e) {
82 LOG.debug("Error parsing xml input", e);
84 throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
85 ErrorTag.MALFORMED_MESSAGE);
89 private static PatchContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc)
90 throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
91 final List<PatchEntity> resultCollection = new ArrayList<>();
92 final String patchId = doc.getElementsByTagName("patch-id").item(0).getFirstChild().getNodeValue();
93 final NodeList editNodes = doc.getElementsByTagName("edit");
95 for (int i = 0; i < editNodes.getLength(); i++) {
96 DataSchemaNode schemaNode = (DataSchemaNode) pathContext.getSchemaNode();
97 final Element element = (Element) editNodes.item(i);
98 final String operation = element.getElementsByTagName("operation").item(0).getFirstChild().getNodeValue();
99 final PatchEditOperation oper = PatchEditOperation.valueOf(operation.toUpperCase());
100 final String editId = element.getElementsByTagName("edit-id").item(0).getFirstChild().getNodeValue();
101 final String target = element.getElementsByTagName("target").item(0).getFirstChild().getNodeValue();
102 final List<Element> values = readValueNodes(element, oper);
103 final Element firstValueElement = values != null ? values.get(0) : null;
105 // get namespace according to schema node from path context or value
106 final String namespace = firstValueElement == null
107 ? schemaNode.getQName().getNamespace().toString() : firstValueElement.getNamespaceURI();
109 // find module according to namespace
110 final Module module = pathContext.getSchemaContext().findModuleByNamespace(
111 URI.create(namespace)).iterator().next();
113 // initialize codec + set default prefix derived from module name
114 final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
115 pathContext.getSchemaContext(), module.getName());
117 // find complete path to target and target schema node
118 // target can be also empty (only slash)
119 YangInstanceIdentifier targetII;
120 final SchemaNode targetNode;
121 if (target.equals("/")) {
122 targetII = pathContext.getInstanceIdentifier();
123 targetNode = pathContext.getSchemaContext();
125 targetII = codec.deserialize(codec.serialize(pathContext.getInstanceIdentifier())
126 .concat(prepareNonCondXpath(schemaNode, target.replaceFirst("/", ""), firstValueElement,
127 namespace, module.getQNameModule().getFormattedRevision())));
129 targetNode = SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(),
130 codec.getDataContextTree().getChild(targetII).getDataSchemaNode().getPath().getParent());
133 schemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(),
134 codec.getDataContextTree().getChild(targetII).getDataSchemaNode().getPath());
137 if (targetNode == null) {
138 LOG.debug("Target node {} not found in path {} ", target, pathContext.getSchemaNode());
139 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL,
140 ErrorTag.MALFORMED_MESSAGE);
143 if (oper.isWithValue()) {
144 final NormalizedNode<?, ?> parsed;
145 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
146 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
147 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
148 final XmlParserStream xmlParser = XmlParserStream.create(writer, pathContext.getSchemaContext(),
150 xmlParser.traverse(new DOMSource(firstValueElement));
151 parsed = resultHolder.getResult();
156 // for lists allow to manipulate with list items through their parent
157 if (targetII.getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
158 targetII = targetII.getParent();
161 resultCollection.add(new PatchEntity(editId, oper, targetII, parsed));
163 resultCollection.add(new PatchEntity(editId, oper, targetII));
167 return new PatchContext(pathContext, ImmutableList.copyOf(resultCollection), patchId);
173 * @param element Element of current edit operation
174 * @param operation Name of current operation
175 * @return List of value elements
177 private static List<Element> readValueNodes(@Nonnull final Element element,
178 @Nonnull final PatchEditOperation operation) {
179 final Node valueNode = element.getElementsByTagName("value").item(0);
181 if (operation.isWithValue() && valueNode == null) {
182 throw new RestconfDocumentedException("Error parsing input",
183 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
186 if (!operation.isWithValue() && valueNode != null) {
187 throw new RestconfDocumentedException("Error parsing input",
188 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
191 if (valueNode == null) {
195 final List<Element> result = new ArrayList<>();
196 final NodeList childNodes = valueNode.getChildNodes();
197 for (int i = 0; i < childNodes.getLength(); i++) {
198 if (childNodes.item(i) instanceof Element) {
199 result.add((Element) childNodes.item(i));
207 * Prepare non-conditional XPath suitable for deserialization with {@link StringModuleInstanceIdentifierCodec}.
209 * @param schemaNode Top schema node
210 * @param target Edit operation target
211 * @param value Element with value
212 * @param namespace Module namespace
213 * @param revision Module revision
214 * @return Non-conditional XPath
216 private static String prepareNonCondXpath(@Nonnull final DataSchemaNode schemaNode, @Nonnull final String target,
217 @Nonnull final Element value, @Nonnull final String namespace, @Nonnull final String revision) {
218 final Iterator<String> args = SLASH_SPLITTER.split(target.substring(target.indexOf(':') + 1)).iterator();
220 final StringBuilder nonCondXpath = new StringBuilder();
221 SchemaNode childNode = schemaNode;
223 while (args.hasNext()) {
224 final String s = args.next();
225 nonCondXpath.append("/");
226 nonCondXpath.append(s);
227 childNode = ((DataNodeContainer) childNode).getDataChildByName(QName.create(namespace, revision, s));
229 if (childNode instanceof ListSchemaNode && args.hasNext()) {
230 appendKeys(nonCondXpath, ((ListSchemaNode) childNode).getKeyDefinition().iterator(), args);
234 if (childNode instanceof ListSchemaNode && value != null) {
235 final Iterator<String> keyValues = readKeyValues(value,
236 ((ListSchemaNode) childNode).getKeyDefinition().iterator());
237 appendKeys(nonCondXpath, ((ListSchemaNode) childNode).getKeyDefinition().iterator(), keyValues);
240 return nonCondXpath.toString();
244 * Read value for every list key.
246 * @param value Value element
247 * @param keys Iterator of list keys names
248 * @return Iterator of list keys values
250 private static Iterator<String> readKeyValues(@Nonnull final Element value, @Nonnull final Iterator<QName> keys) {
251 final List<String> result = new ArrayList<>();
253 while (keys.hasNext()) {
254 result.add(value.getElementsByTagName(keys.next().getLocalName()).item(0).getFirstChild().getNodeValue());
257 return result.iterator();
261 * Append key name - key value pairs for every list key to {@code nonCondXpath}.
263 * @param nonCondXpath Builder for creating non-conditional XPath
264 * @param keyNames Iterator of list keys names
265 * @param keyValues Iterator of list keys values
267 private static void appendKeys(@Nonnull final StringBuilder nonCondXpath, @Nonnull final Iterator<QName> keyNames,
268 @Nonnull final Iterator<String> keyValues) {
269 while (keyNames.hasNext()) {
270 nonCondXpath.append('[');
271 nonCondXpath.append(keyNames.next().getLocalName());
272 nonCondXpath.append("='");
273 nonCondXpath.append(keyValues.next());
274 nonCondXpath.append("']");