Fix patch target parsing
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / jersey / providers / patch / XmlToPatchBodyReader.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.restconf.nb.rfc8040.jersey.providers.patch;
9
10 import static com.google.common.base.Verify.verifyNotNull;
11
12 import com.google.common.base.Splitter;
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.restconf.common.context.InstanceIdentifierContext;
28 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
29 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
30 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
31 import org.opendaylight.restconf.common.patch.PatchContext;
32 import org.opendaylight.restconf.common.patch.PatchEditOperation;
33 import org.opendaylight.restconf.common.patch.PatchEntity;
34 import org.opendaylight.restconf.nb.rfc8040.Rfc8040;
35 import org.opendaylight.restconf.nb.rfc8040.handlers.DOMMountPointServiceHandler;
36 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
37 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
38 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
39 import org.opendaylight.yangtools.util.xml.UntrustedXML;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
42 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
43 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
44 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
45 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
46 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
47 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
48 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
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.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;
59 import org.xml.sax.SAXException;
60
61 @Provider
62 @Consumes({
63     Rfc8040.MediaTypes.YANG_PATCH + RestconfConstants.XML,
64     Rfc8040.MediaTypes.YANG_PATCH_RFC8072 + RestconfConstants.XML
65 })
66 public class XmlToPatchBodyReader extends AbstractToPatchBodyReader {
67     private static final Logger LOG = LoggerFactory.getLogger(XmlToPatchBodyReader.class);
68     private static final Splitter SLASH_SPLITTER = Splitter.on('/');
69
70     public XmlToPatchBodyReader(final SchemaContextHandler schemaContextHandler,
71             final DOMMountPointServiceHandler mountPointServiceHandler) {
72         super(schemaContextHandler, mountPointServiceHandler);
73     }
74
75     @SuppressWarnings("checkstyle:IllegalCatch")
76     @Override
77     protected PatchContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
78             throws WebApplicationException {
79         try {
80             final Document doc = UntrustedXML.newDocumentBuilder().parse(entityStream);
81             return parse(path, doc);
82         } catch (final RestconfDocumentedException e) {
83             throw e;
84         } catch (final Exception e) {
85             LOG.debug("Error parsing xml input", e);
86
87             throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
88                     ErrorTag.MALFORMED_MESSAGE, e);
89         }
90     }
91
92     private static PatchContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc)
93             throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
94         final List<PatchEntity> resultCollection = new ArrayList<>();
95         final String patchId = doc.getElementsByTagName("patch-id").item(0).getFirstChild().getNodeValue();
96         final NodeList editNodes = doc.getElementsByTagName("edit");
97
98         for (int i = 0; i < editNodes.getLength(); i++) {
99             DataSchemaNode schemaNode = (DataSchemaNode) pathContext.getSchemaNode();
100             final Element element = (Element) editNodes.item(i);
101             final String operation = element.getElementsByTagName("operation").item(0).getFirstChild().getNodeValue();
102             final PatchEditOperation oper = PatchEditOperation.valueOf(operation.toUpperCase(Locale.ROOT));
103             final String editId = element.getElementsByTagName("edit-id").item(0).getFirstChild().getNodeValue();
104             final String target = element.getElementsByTagName("target").item(0).getFirstChild().getNodeValue();
105             final List<Element> values = readValueNodes(element, oper);
106             final Element firstValueElement = values != null ? values.get(0) : null;
107
108             // find complete path to target and target schema node
109             // target can be also empty (only slash)
110             YangInstanceIdentifier targetII;
111             final SchemaNode targetNode;
112             if (target.equals("/")) {
113                 targetII = pathContext.getInstanceIdentifier();
114                 targetNode = pathContext.getSchemaContext();
115             } else {
116                 // interpret as simple context
117                 targetII = ParserIdentifier.parserPatchTarget(pathContext, target);
118
119                 // move schema node
120                 final DataSchemaContextTree tree = DataSchemaContextTree.from(pathContext.getSchemaContext());
121                 schemaNode = verifyNotNull(tree.findChild(targetII).orElseThrow().getDataSchemaNode());
122
123                 targetNode = SchemaContextUtil.findDataSchemaNode(pathContext.getSchemaContext(),
124                     schemaNode.getPath().getParent());
125             }
126
127             if (targetNode == null) {
128                 LOG.debug("Target node {} not found in path {} ", target, pathContext.getSchemaNode());
129                 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL,
130                         ErrorTag.MALFORMED_MESSAGE);
131             }
132
133             if (oper.isWithValue()) {
134                 final NormalizedNode<?, ?> parsed;
135                 if (schemaNode instanceof  ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
136                     final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
137                     final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
138                     final XmlParserStream xmlParser = XmlParserStream.create(writer, pathContext.getSchemaContext(),
139                             schemaNode);
140                     xmlParser.traverse(new DOMSource(firstValueElement));
141                     parsed = resultHolder.getResult();
142                 } else {
143                     parsed = null;
144                 }
145
146                 // for lists allow to manipulate with list items through their parent
147                 if (targetII.getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
148                     targetII = targetII.getParent();
149                 }
150
151                 resultCollection.add(new PatchEntity(editId, oper, targetII, parsed));
152             } else {
153                 resultCollection.add(new PatchEntity(editId, oper, targetII));
154             }
155         }
156
157         return new PatchContext(pathContext, ImmutableList.copyOf(resultCollection), patchId);
158     }
159
160     /**
161      * Read value nodes.
162      *
163      * @param element Element of current edit operation
164      * @param operation Name of current operation
165      * @return List of value elements
166      */
167     private static List<Element> readValueNodes(final @NonNull Element element,
168             final @NonNull PatchEditOperation operation) {
169         final Node valueNode = element.getElementsByTagName("value").item(0);
170
171         if (operation.isWithValue() && valueNode == null) {
172             throw new RestconfDocumentedException("Error parsing input",
173                     ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
174         }
175
176         if (!operation.isWithValue() && valueNode != null) {
177             throw new RestconfDocumentedException("Error parsing input",
178                     ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
179         }
180
181         if (valueNode == null) {
182             return null;
183         }
184
185         final List<Element> result = new ArrayList<>();
186         final NodeList childNodes = valueNode.getChildNodes();
187         for (int i = 0; i < childNodes.getLength(); i++) {
188             if (childNodes.item(i) instanceof Element) {
189                 result.add((Element) childNodes.item(i));
190             }
191         }
192
193         return result;
194     }
195 }