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
9 package org.opendaylight.netconf.sal.rest.impl;
11 import com.google.common.base.Splitter;
12 import com.google.common.collect.ImmutableList;
13 import java.io.IOException;
14 import java.io.InputStream;
15 import java.lang.annotation.Annotation;
16 import java.lang.reflect.Type;
18 import java.net.URISyntaxException;
19 import java.util.ArrayList;
20 import java.util.Iterator;
21 import java.util.List;
22 import javax.annotation.Nonnull;
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.opendaylight.netconf.sal.rest.api.Draft02;
33 import org.opendaylight.netconf.sal.rest.api.RestconfService;
34 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
35 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
36 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
37 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
38 import org.opendaylight.restconf.common.patch.PatchContext;
39 import org.opendaylight.restconf.common.patch.PatchEditOperation;
40 import org.opendaylight.restconf.common.patch.PatchEntity;
41 import org.opendaylight.yangtools.util.xml.UntrustedXML;
42 import org.opendaylight.yangtools.yang.common.QName;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
45 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
46 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
47 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
48 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
49 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
50 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
52 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.Module;
55 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
56 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59 import org.w3c.dom.Document;
60 import org.w3c.dom.Element;
61 import org.w3c.dom.Node;
62 import org.w3c.dom.NodeList;
63 import org.xml.sax.SAXException;
66 * Yang PATCH Reader for XML.
68 * @deprecated This class will be replaced by
69 * {@link org.opendaylight.restconf.jersey.providers.XmlToPatchBodyReader}
73 @Consumes({Draft02.MediaTypes.PATCH + RestconfService.XML})
74 public class XmlToPatchBodyReader extends AbstractIdentifierAwareJaxRsProvider implements
75 MessageBodyReader<PatchContext> {
77 private static final Logger LOG = LoggerFactory.getLogger(XmlToPatchBodyReader.class);
80 public boolean isReadable(final Class<?> type, final Type genericType,
81 final Annotation[] annotations, final MediaType mediaType) {
85 @SuppressWarnings("checkstyle:IllegalCatch")
87 public PatchContext readFrom(final Class<PatchContext> type, final Type genericType,
88 final Annotation[] annotations, final MediaType mediaType,
89 final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream)
90 throws IOException, WebApplicationException {
93 final InstanceIdentifierContext<?> path = getInstanceIdentifierContext();
95 if (entityStream.available() < 1) {
96 // represent empty nopayload input
97 return new PatchContext(path, null, null);
100 final Document doc = UntrustedXML.newDocumentBuilder().parse(entityStream);
101 return parse(path, doc);
102 } catch (final RestconfDocumentedException e) {
104 } catch (final Exception e) {
105 LOG.debug("Error parsing xml input", e);
107 throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
108 ErrorTag.MALFORMED_MESSAGE);
112 private static PatchContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc)
113 throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
114 final List<PatchEntity> resultCollection = new ArrayList<>();
115 final String patchId = doc.getElementsByTagName("patch-id").item(0).getFirstChild().getNodeValue();
116 final NodeList editNodes = doc.getElementsByTagName("edit");
118 for (int i = 0; i < editNodes.getLength(); i++) {
119 DataSchemaNode schemaNode = (DataSchemaNode) pathContext.getSchemaNode();
120 final Element element = (Element) editNodes.item(i);
121 final String operation = element.getElementsByTagName("operation").item(0).getFirstChild().getNodeValue();
122 final PatchEditOperation oper = PatchEditOperation.valueOf(operation.toUpperCase());
124 final String editId = element.getElementsByTagName("edit-id").item(0).getFirstChild().getNodeValue();
125 final String target = element.getElementsByTagName("target").item(0).getFirstChild().getNodeValue();
126 final List<Element> values = readValueNodes(element, oper);
127 final Element firstValueElement = values != null ? values.get(0) : null;
129 // get namespace according to schema node from path context or value
130 final String namespace = firstValueElement == null
131 ? schemaNode.getQName().getNamespace().toString() : firstValueElement.getNamespaceURI();
133 // find module according to namespace
134 final Module module = pathContext.getSchemaContext().findModuleByNamespace(
135 URI.create(namespace)).iterator().next();
137 // initialize codec + set default prefix derived from module name
138 final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
139 pathContext.getSchemaContext(), module.getName());
141 // find complete path to target and target schema node
142 // target can be also empty (only slash)
143 YangInstanceIdentifier targetII;
144 final SchemaNode targetNode;
145 if (target.equals("/")) {
146 targetII = pathContext.getInstanceIdentifier();
147 targetNode = pathContext.getSchemaContext();
149 targetII = codec.deserialize(codec.serialize(pathContext.getInstanceIdentifier())
150 .concat(prepareNonCondXpath(schemaNode, target.replaceFirst("/", ""), firstValueElement,
151 namespace, module.getQNameModule().getFormattedRevision())));
153 targetNode = SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(),
154 codec.getDataContextTree().getChild(targetII).getDataSchemaNode().getPath().getParent());
157 schemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(),
158 codec.getDataContextTree().getChild(targetII).getDataSchemaNode().getPath());
161 if (targetNode == null) {
162 LOG.debug("Target node {} not found in path {} ", target, pathContext.getSchemaNode());
163 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL,
164 ErrorTag.MALFORMED_MESSAGE);
167 if (oper.isWithValue()) {
168 final NormalizedNode<?, ?> parsed;
169 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
170 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
171 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
172 final XmlParserStream xmlParser = XmlParserStream.create(writer, pathContext.getSchemaContext(),
174 xmlParser.traverse(new DOMSource(firstValueElement));
175 parsed = resultHolder.getResult();
180 // for lists allow to manipulate with list items through their parent
181 if (targetII.getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
182 targetII = targetII.getParent();
185 resultCollection.add(new PatchEntity(editId, oper, targetII, parsed));
187 resultCollection.add(new PatchEntity(editId, oper, targetII));
191 return new PatchContext(pathContext, ImmutableList.copyOf(resultCollection), patchId);
197 * @param element Element of current edit operation
198 * @param operation Name of current operation
199 * @return List of value elements
201 private static List<Element> readValueNodes(@Nonnull final Element element,
202 @Nonnull final PatchEditOperation operation) {
203 final Node valueNode = element.getElementsByTagName("value").item(0);
205 if (operation.isWithValue() && valueNode == null) {
206 throw new RestconfDocumentedException("Error parsing input",
207 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
210 if (!operation.isWithValue() && valueNode != null) {
211 throw new RestconfDocumentedException("Error parsing input",
212 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
215 if (valueNode == null) {
219 final List<Element> result = new ArrayList<>();
220 final NodeList childNodes = valueNode.getChildNodes();
221 for (int i = 0; i < childNodes.getLength(); i++) {
222 if (childNodes.item(i) instanceof Element) {
223 result.add((Element) childNodes.item(i));
231 * Prepare non-conditional XPath suitable for deserialization with {@link StringModuleInstanceIdentifierCodec}.
233 * @param schemaNode Top schema node
234 * @param target Edit operation target
235 * @param value Element with value
236 * @param namespace Module namespace
237 * @param revision Module revision
238 * @return Non-conditional XPath
240 private static String prepareNonCondXpath(@Nonnull final DataSchemaNode schemaNode, @Nonnull final String target,
241 @Nonnull final Element value, @Nonnull final String namespace, @Nonnull final String revision) {
242 final Iterator<String> args = Splitter.on("/").split(target.substring(target.indexOf(':') + 1)).iterator();
244 final StringBuilder nonCondXpath = new StringBuilder();
245 SchemaNode childNode = schemaNode;
247 while (args.hasNext()) {
248 final String s = args.next();
249 nonCondXpath.append("/");
250 nonCondXpath.append(s);
251 childNode = ((DataNodeContainer) childNode).getDataChildByName(QName.create(namespace, revision, s));
253 if (childNode instanceof ListSchemaNode && args.hasNext()) {
254 appendKeys(nonCondXpath, ((ListSchemaNode) childNode).getKeyDefinition().iterator(), args);
258 if (childNode instanceof ListSchemaNode && value != null) {
259 final Iterator<String> keyValues = readKeyValues(value,
260 ((ListSchemaNode) childNode).getKeyDefinition().iterator());
261 appendKeys(nonCondXpath, ((ListSchemaNode) childNode).getKeyDefinition().iterator(), keyValues);
264 return nonCondXpath.toString();
268 * Read value for every list key.
270 * @param value Value element
271 * @param keys Iterator of list keys names
272 * @return Iterator of list keys values
274 private static Iterator<String> readKeyValues(@Nonnull final Element value, @Nonnull final Iterator<QName> keys) {
275 final List<String> result = new ArrayList<>();
277 while (keys.hasNext()) {
278 result.add(value.getElementsByTagName(keys.next().getLocalName()).item(0).getFirstChild().getNodeValue());
281 return result.iterator();
285 * Append key name - key value pairs for every list key to {@code nonCondXpath}.
287 * @param nonCondXpath Builder for creating non-conditional XPath
288 * @param keyNames Iterator of list keys names
289 * @param keyValues Iterator of list keys values
291 private static void appendKeys(@Nonnull final StringBuilder nonCondXpath, @Nonnull final Iterator<QName> keyNames,
292 @Nonnull final Iterator<String> keyValues) {
293 while (keyNames.hasNext()) {
294 nonCondXpath.append("[");
295 nonCondXpath.append(keyNames.next().getLocalName());
296 nonCondXpath.append("=");
297 nonCondXpath.append("'");
298 nonCondXpath.append(keyValues.next());
299 nonCondXpath.append("'");
300 nonCondXpath.append("]");