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.utils.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;
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.restconf.impl.InstanceIdentifierContext;
32 import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
33 import org.opendaylight.netconf.sal.restconf.impl.PATCHEditOperation;
34 import org.opendaylight.netconf.sal.restconf.impl.PATCHEntity;
35 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
36 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
37 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
38 import org.opendaylight.restconf.Draft17;
39 import org.opendaylight.restconf.utils.RestconfConstants;
40 import org.opendaylight.yangtools.yang.common.QName;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
43 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
44 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
45 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
46 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
48 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.Module;
51 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
52 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.w3c.dom.Document;
56 import org.w3c.dom.Element;
57 import org.w3c.dom.Node;
58 import org.w3c.dom.NodeList;
61 @Consumes({Draft17.MediaTypes.PATCH + RestconfConstants.XML})
62 public class XmlToPATCHBodyReader extends AbstractIdentifierAwareJaxRsProvider implements
63 MessageBodyReader<PATCHContext> {
65 private final static Logger LOG = LoggerFactory.getLogger(XmlToPATCHBodyReader.class);
66 private static final DocumentBuilderFactory BUILDERFACTORY;
69 final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
71 factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
72 factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
73 factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
74 factory.setXIncludeAware(false);
75 factory.setExpandEntityReferences(false);
76 } catch (final ParserConfigurationException e) {
77 throw new ExceptionInInitializerError(e);
79 factory.setNamespaceAware(true);
80 factory.setCoalescing(true);
81 factory.setIgnoringElementContentWhitespace(true);
82 factory.setIgnoringComments(true);
83 BUILDERFACTORY = factory;
87 public boolean isReadable(final Class<?> type, final Type genericType,
88 final Annotation[] annotations, final MediaType mediaType) {
93 public PATCHContext readFrom(final Class<PATCHContext> type, final Type genericType,
94 final Annotation[] annotations, final MediaType mediaType,
95 final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream)
96 throws IOException, WebApplicationException {
99 final InstanceIdentifierContext<?> path = getInstanceIdentifierContext();
101 if (entityStream.available() < 1) {
102 // represent empty nopayload input
103 return new PATCHContext(path, null, null);
106 final DocumentBuilder dBuilder;
108 dBuilder = BUILDERFACTORY.newDocumentBuilder();
109 } catch (final ParserConfigurationException e) {
110 throw new IllegalStateException("Failed to parse XML document", e);
112 final Document doc = dBuilder.parse(entityStream);
114 return parse(path, doc);
115 } catch (final RestconfDocumentedException e) {
117 } catch (final Exception e) {
118 LOG.debug("Error parsing xml input", e);
120 throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
121 ErrorTag.MALFORMED_MESSAGE);
125 private PATCHContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc) {
126 final List<PATCHEntity> resultCollection = new ArrayList<>();
127 final String patchId = doc.getElementsByTagName("patch-id").item(0).getFirstChild().getNodeValue();
128 final NodeList editNodes = doc.getElementsByTagName("edit");
129 final DomToNormalizedNodeParserFactory parserFactory =
130 DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER,
131 pathContext.getSchemaContext());
133 for (int i = 0; i < editNodes.getLength(); i++) {
134 DataSchemaNode schemaNode = (DataSchemaNode) pathContext.getSchemaNode();
135 final Element element = (Element) editNodes.item(i);
136 final String operation = element.getElementsByTagName("operation").item(0).getFirstChild().getNodeValue();
137 final String editId = element.getElementsByTagName("edit-id").item(0).getFirstChild().getNodeValue();
138 final String target = element.getElementsByTagName("target").item(0).getFirstChild().getNodeValue();
139 final List<Element> values = readValueNodes(element, operation);
140 final Element firstValueElement = values != null ? values.get(0) : null;
142 // get namespace according to schema node from path context or value
143 final String namespace = (firstValueElement == null) ?
144 schemaNode.getQName().getNamespace().toString() : firstValueElement.getNamespaceURI();
146 // find module according to namespace
147 final Module module = pathContext.getSchemaContext().findModuleByNamespace(
148 URI.create(namespace)).iterator().next();
150 // initialize codec + set default prefix derived from module name
151 final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
152 pathContext.getSchemaContext(), module.getName());
154 // find complete path to target and target schema node
155 // target can be also empty (only slash)
156 YangInstanceIdentifier targetII;
157 final SchemaNode targetNode;
158 if (target.equals("/")) {
159 targetII = pathContext.getInstanceIdentifier();
160 targetNode = pathContext.getSchemaContext();
162 targetII = codec.deserialize(codec.serialize(pathContext.getInstanceIdentifier())
163 .concat(prepareNonCondXpath(schemaNode, target.replaceFirst("/", ""), firstValueElement,
164 namespace, module.getQNameModule().getFormattedRevision())));
166 targetNode = SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(),
167 codec.getDataContextTree().getChild(targetII).getDataSchemaNode().getPath().getParent());
170 schemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(),
171 codec.getDataContextTree().getChild(targetII).getDataSchemaNode().getPath());
174 if (targetNode == null) {
175 LOG.debug("Target node {} not found in path {} ", target, pathContext.getSchemaNode());
176 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL,
177 ErrorTag.MALFORMED_MESSAGE);
179 if (PATCHEditOperation.isPatchOperationWithValue(operation)) {
180 NormalizedNode<?, ?> parsed = null;
181 if (schemaNode instanceof ContainerSchemaNode) {
182 parsed = parserFactory.getContainerNodeParser().parse(values, (ContainerSchemaNode) schemaNode);
183 } else if (schemaNode instanceof ListSchemaNode) {
184 parsed = parserFactory.getMapNodeParser().parse(values, (ListSchemaNode) schemaNode);
187 // for lists allow to manipulate with list items through their parent
188 if (targetII.getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
189 targetII = targetII.getParent();
192 resultCollection.add(new PATCHEntity(editId, operation, targetII, parsed));
194 resultCollection.add(new PATCHEntity(editId, operation, targetII));
199 return new PATCHContext(pathContext, ImmutableList.copyOf(resultCollection), patchId);
204 * @param element Element of current edit operation
205 * @param operation Name of current operation
206 * @return List of value elements
208 private List<Element> readValueNodes(@Nonnull final Element element, @Nonnull final String operation) {
209 final Node valueNode = element.getElementsByTagName("value").item(0);
211 if (PATCHEditOperation.isPatchOperationWithValue(operation) && valueNode == null) {
212 throw new RestconfDocumentedException("Error parsing input",
213 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
216 if (!PATCHEditOperation.isPatchOperationWithValue(operation) && valueNode != null) {
217 throw new RestconfDocumentedException("Error parsing input",
218 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
221 if (valueNode == null) {
225 final List<Element> result = new ArrayList<>();
226 final NodeList childNodes = valueNode.getChildNodes();
227 for (int i = 0; i < childNodes.getLength(); i++) {
228 if (childNodes.item(i) instanceof Element) {
229 result.add((Element) childNodes.item(i));
237 * Prepare non-conditional XPath suitable for deserialization
238 * with {@link StringModuleInstanceIdentifierCodec}
239 * @param schemaNode Top schema node
240 * @param target Edit operation target
241 * @param value Element with value
242 * @param namespace Module namespace
243 * @param revision Module revision
244 * @return Non-conditional XPath
246 private String prepareNonCondXpath(@Nonnull final DataSchemaNode schemaNode, @Nonnull final String target,
247 @Nonnull final Element value, @Nonnull final String namespace,
248 @Nonnull String revision) {
249 final Iterator<String> args = Splitter.on("/").split(target.substring(target.indexOf(':') + 1)).iterator();
251 final StringBuilder nonCondXpath = new StringBuilder();
252 SchemaNode childNode = schemaNode;
254 while (args.hasNext()) {
255 final String s = args.next();
256 nonCondXpath.append("/");
257 nonCondXpath.append(s);
258 childNode = ((DataNodeContainer) childNode).getDataChildByName(QName.create(namespace, revision, s));
260 if (childNode instanceof ListSchemaNode && args.hasNext()) {
261 appendKeys(nonCondXpath, ((ListSchemaNode) childNode).getKeyDefinition().iterator(), args);
265 if (childNode instanceof ListSchemaNode && value != null) {
266 final Iterator<String> keyValues = readKeyValues(value,
267 ((ListSchemaNode) childNode).getKeyDefinition().iterator());
268 appendKeys(nonCondXpath, ((ListSchemaNode) childNode).getKeyDefinition().iterator(), keyValues);
271 return nonCondXpath.toString();
275 * Read value for every list key
276 * @param value Value element
277 * @param keys Iterator of list keys names
278 * @return Iterator of list keys values
280 private Iterator<String> readKeyValues(@Nonnull final Element value, @Nonnull final Iterator<QName> keys) {
281 final List<String> result = new ArrayList<>();
283 while (keys.hasNext()) {
284 result.add(value.getElementsByTagName(keys.next().getLocalName()).item(0).getFirstChild().getNodeValue());
287 return result.iterator();
291 * Append key name - key value pairs for every list key to {@code nonCondXpath}
292 * @param nonCondXpath Builder for creating non-conditional XPath
293 * @param keyNames Iterator of list keys names
294 * @param keyValues Iterator of list keys values
296 private void appendKeys(@Nonnull final StringBuilder nonCondXpath, @Nonnull final Iterator<QName> keyNames,
297 @Nonnull final Iterator<String> keyValues) {
298 while (keyNames.hasNext()) {
299 nonCondXpath.append("[");
300 nonCondXpath.append(keyNames.next().getLocalName());
301 nonCondXpath.append("=");
302 nonCondXpath.append("'");
303 nonCondXpath.append(keyValues.next());
304 nonCondXpath.append("'");
305 nonCondXpath.append("]");