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