f6138d109cd023ec9a63b475f11a67f42e3d36ce
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / jersey / providers / patch / XmlPatchBodyReader.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.verify;
11
12 import com.google.common.collect.ImmutableList;
13 import java.io.IOException;
14 import java.io.InputStream;
15 import java.net.URISyntaxException;
16 import java.util.ArrayList;
17 import java.util.List;
18 import java.util.Locale;
19 import javax.ws.rs.Consumes;
20 import javax.ws.rs.WebApplicationException;
21 import javax.ws.rs.ext.Provider;
22 import javax.xml.parsers.ParserConfigurationException;
23 import javax.xml.stream.XMLStreamException;
24 import javax.xml.transform.dom.DOMSource;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
27 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
28 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
29 import org.opendaylight.restconf.common.patch.PatchContext;
30 import org.opendaylight.restconf.common.patch.PatchEditOperation;
31 import org.opendaylight.restconf.common.patch.PatchEntity;
32 import org.opendaylight.restconf.nb.rfc8040.MediaTypes;
33 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
34 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier;
35 import org.opendaylight.yangtools.util.xml.UntrustedXML;
36 import org.opendaylight.yangtools.yang.common.ErrorTag;
37 import org.opendaylight.yangtools.yang.common.ErrorType;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
40 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
42 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
43 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
44 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
45 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
46 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
51 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import org.w3c.dom.Document;
55 import org.w3c.dom.Element;
56 import org.w3c.dom.Node;
57 import org.w3c.dom.NodeList;
58 import org.xml.sax.SAXException;
59
60 @Provider
61 @Consumes(MediaTypes.APPLICATION_YANG_PATCH_XML)
62 public class XmlPatchBodyReader extends AbstractPatchBodyReader {
63     private static final Logger LOG = LoggerFactory.getLogger(XmlPatchBodyReader.class);
64
65     public XmlPatchBodyReader(final SchemaContextHandler schemaContextHandler,
66             final DOMMountPointService mountPointService) {
67         super(schemaContextHandler, mountPointService);
68     }
69
70     @SuppressWarnings("checkstyle:IllegalCatch")
71     @Override
72     protected PatchContext readBody(final InstanceIdentifierContext path, final InputStream entityStream)
73             throws WebApplicationException {
74         try {
75             final Document doc = UntrustedXML.newDocumentBuilder().parse(entityStream);
76             return parse(path, doc);
77         } catch (final RestconfDocumentedException e) {
78             throw e;
79         } catch (final Exception e) {
80             LOG.debug("Error parsing xml input", e);
81
82             throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
83                     ErrorTag.MALFORMED_MESSAGE, e);
84         }
85     }
86
87     private static PatchContext parse(final InstanceIdentifierContext pathContext, final Document doc)
88             throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
89         final List<PatchEntity> resultCollection = new ArrayList<>();
90         final String patchId = doc.getElementsByTagName("patch-id").item(0).getFirstChild().getNodeValue();
91         final NodeList editNodes = doc.getElementsByTagName("edit");
92
93         for (int i = 0; i < editNodes.getLength(); i++) {
94             DataSchemaNode schemaNode = (DataSchemaNode) pathContext.getSchemaNode();
95             final Element element = (Element) editNodes.item(i);
96             final String operation = element.getElementsByTagName("operation").item(0).getFirstChild().getNodeValue();
97             final PatchEditOperation oper = PatchEditOperation.valueOf(operation.toUpperCase(Locale.ROOT));
98             final String editId = element.getElementsByTagName("edit-id").item(0).getFirstChild().getNodeValue();
99             final String target = element.getElementsByTagName("target").item(0).getFirstChild().getNodeValue();
100             final List<Element> values = readValueNodes(element, oper);
101             final Element firstValueElement = values != null ? values.get(0) : null;
102
103             // find complete path to target and target schema node
104             // target can be also empty (only slash)
105             YangInstanceIdentifier targetII;
106             final SchemaNode targetNode;
107             final Inference inference;
108             if (target.equals("/")) {
109                 targetII = pathContext.getInstanceIdentifier();
110                 targetNode = pathContext.getSchemaContext();
111                 inference = pathContext.inference();
112             } else {
113                 // interpret as simple context
114                 targetII = ParserIdentifier.parserPatchTarget(pathContext, target);
115
116                 // move schema node
117                 final var lookup = DataSchemaContextTree.from(pathContext.getSchemaContext())
118                     .enterPath(targetII).orElseThrow();
119
120                 schemaNode = lookup.node().getDataSchemaNode();
121                 final var stack = lookup.stack();
122                 inference = stack.toInference();
123                 if (!stack.isEmpty()) {
124                     stack.exit();
125                 }
126
127                 final EffectiveStatement<?, ?> parentStmt = stack.currentStatement();
128                 verify(parentStmt instanceof SchemaNode, "Unexpected parent %s", parentStmt);
129                 targetNode = (SchemaNode) parentStmt;
130             }
131
132             if (targetNode == null) {
133                 LOG.debug("Target node {} not found in path {} ", target, pathContext.getSchemaNode());
134                 throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL,
135                         ErrorTag.MALFORMED_MESSAGE);
136             }
137
138             if (oper.isWithValue()) {
139                 final NormalizedNode parsed;
140                 if (schemaNode instanceof  ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
141                     final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
142                     final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
143                     final XmlParserStream xmlParser = XmlParserStream.create(writer, inference);
144                     xmlParser.traverse(new DOMSource(firstValueElement));
145                     parsed = resultHolder.getResult();
146                 } else {
147                     parsed = null;
148                 }
149
150                 // for lists allow to manipulate with list items through their parent
151                 if (targetII.getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
152                     targetII = targetII.getParent();
153                 }
154
155                 resultCollection.add(new PatchEntity(editId, oper, targetII, parsed));
156             } else {
157                 resultCollection.add(new PatchEntity(editId, oper, targetII));
158             }
159         }
160
161         return new PatchContext(pathContext, ImmutableList.copyOf(resultCollection), patchId);
162     }
163
164     /**
165      * Read value nodes.
166      *
167      * @param element Element of current edit operation
168      * @param operation Name of current operation
169      * @return List of value elements
170      */
171     private static List<Element> readValueNodes(final @NonNull Element element,
172             final @NonNull PatchEditOperation operation) {
173         final Node valueNode = element.getElementsByTagName("value").item(0);
174
175         if (operation.isWithValue() && valueNode == null) {
176             throw new RestconfDocumentedException("Error parsing input",
177                     ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
178         }
179
180         if (!operation.isWithValue() && valueNode != null) {
181             throw new RestconfDocumentedException("Error parsing input",
182                     ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
183         }
184
185         if (valueNode == null) {
186             return null;
187         }
188
189         final List<Element> result = new ArrayList<>();
190         final NodeList childNodes = valueNode.getChildNodes();
191         for (int i = 0; i < childNodes.getLength(); i++) {
192             if (childNodes.item(i) instanceof Element) {
193                 result.add((Element) childNodes.item(i));
194             }
195         }
196
197         return result;
198     }
199 }