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
8 package org.opendaylight.restconf.nb.rfc8040.jersey.providers.patch;
10 import static com.google.common.base.Verify.verify;
11 import static com.google.common.base.Verify.verifyNotNull;
13 import com.google.common.collect.ImmutableList;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.net.URISyntaxException;
17 import java.util.ArrayList;
18 import java.util.List;
19 import java.util.Locale;
20 import javax.ws.rs.Consumes;
21 import javax.ws.rs.WebApplicationException;
22 import javax.ws.rs.ext.Provider;
23 import javax.xml.parsers.ParserConfigurationException;
24 import javax.xml.stream.XMLStreamException;
25 import javax.xml.transform.dom.DOMSource;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
28 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
29 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
30 import org.opendaylight.restconf.common.patch.PatchContext;
31 import org.opendaylight.restconf.common.patch.PatchEditOperation;
32 import org.opendaylight.restconf.common.patch.PatchEntity;
33 import org.opendaylight.restconf.nb.rfc8040.MediaTypes;
34 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
35 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
36 import org.opendaylight.yangtools.util.xml.UntrustedXML;
37 import org.opendaylight.yangtools.yang.common.ErrorTag;
38 import org.opendaylight.yangtools.yang.common.ErrorType;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
41 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
43 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
44 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
45 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
46 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
47 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
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.SchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
52 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
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;
59 import org.xml.sax.SAXException;
62 @Consumes(MediaTypes.APPLICATION_YANG_PATCH_XML)
63 public class XmlPatchBodyReader extends AbstractPatchBodyReader {
64 private static final Logger LOG = LoggerFactory.getLogger(XmlPatchBodyReader.class);
66 public XmlPatchBodyReader(final SchemaContextHandler schemaContextHandler,
67 final DOMMountPointService mountPointService) {
68 super(schemaContextHandler, mountPointService);
71 @SuppressWarnings("checkstyle:IllegalCatch")
73 protected PatchContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
74 throws WebApplicationException {
76 final Document doc = UntrustedXML.newDocumentBuilder().parse(entityStream);
77 return parse(path, doc);
78 } catch (final RestconfDocumentedException e) {
80 } catch (final Exception e) {
81 LOG.debug("Error parsing xml input", e);
83 throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
84 ErrorTag.MALFORMED_MESSAGE, e);
88 private static PatchContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc)
89 throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
90 final List<PatchEntity> resultCollection = new ArrayList<>();
91 final String patchId = doc.getElementsByTagName("patch-id").item(0).getFirstChild().getNodeValue();
92 final NodeList editNodes = doc.getElementsByTagName("edit");
94 for (int i = 0; i < editNodes.getLength(); i++) {
95 DataSchemaNode schemaNode = (DataSchemaNode) pathContext.getSchemaNode();
96 final Element element = (Element) editNodes.item(i);
97 final String operation = element.getElementsByTagName("operation").item(0).getFirstChild().getNodeValue();
98 final PatchEditOperation oper = PatchEditOperation.valueOf(operation.toUpperCase(Locale.ROOT));
99 final String editId = element.getElementsByTagName("edit-id").item(0).getFirstChild().getNodeValue();
100 final String target = element.getElementsByTagName("target").item(0).getFirstChild().getNodeValue();
101 final List<Element> values = readValueNodes(element, oper);
102 final Element firstValueElement = values != null ? values.get(0) : null;
104 // find complete path to target and target schema node
105 // target can be also empty (only slash)
106 YangInstanceIdentifier targetII;
107 final SchemaNode targetNode;
108 if (target.equals("/")) {
109 targetII = pathContext.getInstanceIdentifier();
110 targetNode = pathContext.getSchemaContext();
112 // interpret as simple context
113 targetII = ParserIdentifier.parserPatchTarget(pathContext, target);
116 schemaNode = verifyNotNull(DataSchemaContextTree.from(pathContext.getSchemaContext())
117 .findChild(targetII).orElseThrow().getDataSchemaNode());
119 final EffectiveStatement<?, ?> parentStmt = SchemaInferenceStack.ofInstantiatedPath(
120 pathContext.getSchemaContext(), schemaNode.getPath().getParent()).currentStatement();
121 verify(parentStmt instanceof SchemaNode, "Unexpected parent %s", parentStmt);
122 targetNode = (SchemaNode) parentStmt;
125 if (targetNode == null) {
126 LOG.debug("Target node {} not found in path {} ", target, pathContext.getSchemaNode());
127 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL,
128 ErrorTag.MALFORMED_MESSAGE);
131 if (oper.isWithValue()) {
132 final NormalizedNode parsed;
133 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
134 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
135 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
136 final XmlParserStream xmlParser = XmlParserStream.create(writer,
137 SchemaInferenceStack.ofInstantiatedPath(pathContext.getSchemaContext(), schemaNode.getPath())
139 xmlParser.traverse(new DOMSource(firstValueElement));
140 parsed = resultHolder.getResult();
145 // for lists allow to manipulate with list items through their parent
146 if (targetII.getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
147 targetII = targetII.getParent();
150 resultCollection.add(new PatchEntity(editId, oper, targetII, parsed));
152 resultCollection.add(new PatchEntity(editId, oper, targetII));
156 return new PatchContext(pathContext, ImmutableList.copyOf(resultCollection), patchId);
162 * @param element Element of current edit operation
163 * @param operation Name of current operation
164 * @return List of value elements
166 private static List<Element> readValueNodes(final @NonNull Element element,
167 final @NonNull PatchEditOperation operation) {
168 final Node valueNode = element.getElementsByTagName("value").item(0);
170 if (operation.isWithValue() && valueNode == null) {
171 throw new RestconfDocumentedException("Error parsing input",
172 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
175 if (!operation.isWithValue() && valueNode != null) {
176 throw new RestconfDocumentedException("Error parsing input",
177 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
180 if (valueNode == null) {
184 final List<Element> result = new ArrayList<>();
185 final NodeList childNodes = valueNode.getChildNodes();
186 for (int i = 0; i < childNodes.getLength(); i++) {
187 if (childNodes.item(i) instanceof Element) {
188 result.add((Element) childNodes.item(i));