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