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.util.ArrayList;
19 import java.util.Iterator;
20 import java.util.List;
21 import javax.annotation.Nonnull;
22 import javax.ws.rs.Consumes;
23 import javax.ws.rs.WebApplicationException;
24 import javax.ws.rs.core.MediaType;
25 import javax.ws.rs.core.MultivaluedMap;
26 import javax.ws.rs.ext.MessageBodyReader;
27 import javax.ws.rs.ext.Provider;
28 import javax.xml.parsers.DocumentBuilder;
29 import javax.xml.parsers.DocumentBuilderFactory;
30 import javax.xml.parsers.ParserConfigurationException;
31 import org.opendaylight.netconf.sal.rest.api.Draft02;
32 import org.opendaylight.netconf.sal.rest.api.RestconfService;
33 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
34 import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
35 import org.opendaylight.netconf.sal.restconf.impl.PATCHEditOperation;
36 import org.opendaylight.netconf.sal.restconf.impl.PATCHEntity;
37 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
38 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
39 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
40 import org.opendaylight.restconf.utils.patch.Draft11XmlToPATCHBodyReader;
41 import org.opendaylight.yangtools.yang.common.QName;
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.impl.codec.xml.XmlUtils;
46 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
47 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
49 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.Module;
52 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
53 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56 import org.w3c.dom.Document;
57 import org.w3c.dom.Element;
58 import org.w3c.dom.Node;
59 import org.w3c.dom.NodeList;
62 * @deprecated This class will be replaced by {@link Draft11XmlToPATCHBodyReader}
66 @Consumes({Draft02.MediaTypes.PATCH + RestconfService.XML})
67 public class XmlToPATCHBodyReader extends AbstractIdentifierAwareJaxRsProvider implements
68 MessageBodyReader<PATCHContext> {
70 private final static Logger LOG = LoggerFactory.getLogger(XmlToPATCHBodyReader.class);
71 private static final DocumentBuilderFactory BUILDERFACTORY;
74 final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
76 factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
77 factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
78 factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
79 factory.setXIncludeAware(false);
80 factory.setExpandEntityReferences(false);
81 } catch (final ParserConfigurationException e) {
82 throw new ExceptionInInitializerError(e);
84 factory.setNamespaceAware(true);
85 factory.setCoalescing(true);
86 factory.setIgnoringElementContentWhitespace(true);
87 factory.setIgnoringComments(true);
88 BUILDERFACTORY = factory;
92 public boolean isReadable(final Class<?> type, final Type genericType,
93 final Annotation[] annotations, final MediaType mediaType) {
98 public PATCHContext readFrom(final Class<PATCHContext> type, final Type genericType,
99 final Annotation[] annotations, final MediaType mediaType,
100 final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream)
101 throws IOException, WebApplicationException {
104 final InstanceIdentifierContext<?> path = getInstanceIdentifierContext();
106 if (entityStream.available() < 1) {
107 // represent empty nopayload input
108 return new PATCHContext(path, null, null);
111 final DocumentBuilder dBuilder;
113 dBuilder = BUILDERFACTORY.newDocumentBuilder();
114 } catch (final ParserConfigurationException e) {
115 throw new IllegalStateException("Failed to parse XML document", e);
117 final Document doc = dBuilder.parse(entityStream);
119 return parse(path, doc);
120 } catch (final RestconfDocumentedException e) {
122 } catch (final Exception e) {
123 LOG.debug("Error parsing xml input", e);
125 throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
126 ErrorTag.MALFORMED_MESSAGE);
130 private PATCHContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc) {
131 final List<PATCHEntity> resultCollection = new ArrayList<>();
132 final String patchId = doc.getElementsByTagName("patch-id").item(0).getFirstChild().getNodeValue();
133 final NodeList editNodes = doc.getElementsByTagName("edit");
134 final DomToNormalizedNodeParserFactory parserFactory =
135 DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER,
136 pathContext.getSchemaContext());
138 for (int i = 0; i < editNodes.getLength(); i++) {
139 DataSchemaNode schemaNode = (DataSchemaNode) pathContext.getSchemaNode();
140 final Element element = (Element) editNodes.item(i);
141 final String operation = element.getElementsByTagName("operation").item(0).getFirstChild().getNodeValue();
142 final String editId = element.getElementsByTagName("edit-id").item(0).getFirstChild().getNodeValue();
143 final String target = element.getElementsByTagName("target").item(0).getFirstChild().getNodeValue();
144 final List<Element> values = readValueNodes(element, operation);
145 final Element firstValueElement = values != null ? values.get(0) : null;
147 // get namespace according to schema node from path context or value
148 final String namespace = (firstValueElement == null) ?
149 schemaNode.getQName().getNamespace().toString() : firstValueElement.getNamespaceURI();
151 // find module according to namespace
152 final Module module = pathContext.getSchemaContext().findModuleByNamespace(
153 URI.create(namespace)).iterator().next();
155 // initialize codec + set default prefix derived from module name
156 final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
157 pathContext.getSchemaContext(), module.getName());
159 // find complete path to target and target schema node
160 // target can be also empty (only slash)
161 YangInstanceIdentifier targetII;
162 final SchemaNode targetNode;
163 if (target.equals("/")) {
164 targetII = pathContext.getInstanceIdentifier();
165 targetNode = pathContext.getSchemaContext();
167 targetII = codec.deserialize(codec.serialize(pathContext.getInstanceIdentifier())
168 .concat(prepareNonCondXpath(schemaNode, target.replaceFirst("/", ""), firstValueElement,
169 namespace, module.getQNameModule().getFormattedRevision())));
171 targetNode = SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(),
172 codec.getDataContextTree().getChild(targetII).getDataSchemaNode().getPath().getParent());
175 schemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(),
176 codec.getDataContextTree().getChild(targetII).getDataSchemaNode().getPath());
179 if (targetNode == null) {
180 LOG.debug("Target node {} not found in path {} ", target, pathContext.getSchemaNode());
181 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL,
182 ErrorTag.MALFORMED_MESSAGE);
184 if (PATCHEditOperation.isPatchOperationWithValue(operation)) {
185 NormalizedNode<?, ?> parsed = null;
186 if (schemaNode instanceof ContainerSchemaNode) {
187 parsed = parserFactory.getContainerNodeParser().parse(values, (ContainerSchemaNode) schemaNode);
188 } else if (schemaNode instanceof ListSchemaNode) {
189 parsed = parserFactory.getMapNodeParser().parse(values, (ListSchemaNode) schemaNode);
192 // for lists allow to manipulate with list items through their parent
193 if (targetII.getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
194 targetII = targetII.getParent();
197 resultCollection.add(new PATCHEntity(editId, operation, targetII, parsed));
199 resultCollection.add(new PATCHEntity(editId, operation, targetII));
204 return new PATCHContext(pathContext, ImmutableList.copyOf(resultCollection), patchId);
209 * @param element Element of current edit operation
210 * @param operation Name of current operation
211 * @return List of value elements
213 private List<Element> readValueNodes(@Nonnull final Element element, @Nonnull final String operation) {
214 final Node valueNode = element.getElementsByTagName("value").item(0);
216 if (PATCHEditOperation.isPatchOperationWithValue(operation) && valueNode == null) {
217 throw new RestconfDocumentedException("Error parsing input",
218 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
221 if (!PATCHEditOperation.isPatchOperationWithValue(operation) && valueNode != null) {
222 throw new RestconfDocumentedException("Error parsing input",
223 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
226 if (valueNode == null) {
230 final List<Element> result = new ArrayList<>();
231 final NodeList childNodes = valueNode.getChildNodes();
232 for (int i = 0; i < childNodes.getLength(); i++) {
233 if (childNodes.item(i) instanceof Element) {
234 result.add((Element) childNodes.item(i));
242 * Prepare non-conditional XPath suitable for deserialization
243 * with {@link StringModuleInstanceIdentifierCodec}
244 * @param schemaNode Top schema node
245 * @param target Edit operation target
246 * @param value Element with value
247 * @param namespace Module namespace
248 * @param revision Module revision
249 * @return Non-conditional XPath
251 private String prepareNonCondXpath(@Nonnull final DataSchemaNode schemaNode, @Nonnull final String target,
252 @Nonnull final Element value, @Nonnull final String namespace,
253 @Nonnull String revision) {
254 final Iterator<String> args = Splitter.on("/").split(target.substring(target.indexOf(':') + 1)).iterator();
256 final StringBuilder nonCondXpath = new StringBuilder();
257 SchemaNode childNode = schemaNode;
259 while (args.hasNext()) {
260 final String s = args.next();
261 nonCondXpath.append("/");
262 nonCondXpath.append(s);
263 childNode = ((DataNodeContainer) childNode).getDataChildByName(QName.create(namespace, revision, s));
265 if (childNode instanceof ListSchemaNode && args.hasNext()) {
266 appendKeys(nonCondXpath, ((ListSchemaNode) childNode).getKeyDefinition().iterator(), args);
270 if (childNode instanceof ListSchemaNode && value != null) {
271 final Iterator<String> keyValues = readKeyValues(value,
272 ((ListSchemaNode) childNode).getKeyDefinition().iterator());
273 appendKeys(nonCondXpath, ((ListSchemaNode) childNode).getKeyDefinition().iterator(), keyValues);
276 return nonCondXpath.toString();
280 * Read value for every list key
281 * @param value Value element
282 * @param keys Iterator of list keys names
283 * @return Iterator of list keys values
285 private Iterator<String> readKeyValues(@Nonnull final Element value, @Nonnull final Iterator<QName> keys) {
286 final List<String> result = new ArrayList<>();
288 while (keys.hasNext()) {
289 result.add(value.getElementsByTagName(keys.next().getLocalName()).item(0).getFirstChild().getNodeValue());
292 return result.iterator();
296 * Append key name - key value pairs for every list key to {@code nonCondXpath}
297 * @param nonCondXpath Builder for creating non-conditional XPath
298 * @param keyNames Iterator of list keys names
299 * @param keyValues Iterator of list keys values
301 private void appendKeys(@Nonnull final StringBuilder nonCondXpath, @Nonnull final Iterator<QName> keyNames,
302 @Nonnull final Iterator<String> keyValues) {
303 while (keyNames.hasNext()) {
304 nonCondXpath.append("[");
305 nonCondXpath.append(keyNames.next().getLocalName());
306 nonCondXpath.append("=");
307 nonCondXpath.append("'");
308 nonCondXpath.append(keyValues.next());
309 nonCondXpath.append("'");
310 nonCondXpath.append("]");