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