Update RESTCONF error mapping
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / jersey / providers / XmlNormalizedNodeBodyReader.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;
9
10 import static com.google.common.base.Preconditions.checkState;
11
12 import com.google.common.collect.Iterables;
13 import java.io.IOException;
14 import java.io.InputStream;
15 import java.net.URISyntaxException;
16 import java.util.ArrayDeque;
17 import java.util.ArrayList;
18 import java.util.Deque;
19 import java.util.List;
20 import javax.ws.rs.Consumes;
21 import javax.ws.rs.WebApplicationException;
22 import javax.ws.rs.core.MediaType;
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.opendaylight.mdsal.dom.api.DOMMountPointService;
28 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
29 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
30 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
31 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
32 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
33 import org.opendaylight.restconf.nb.rfc8040.MediaTypes;
34 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
35 import org.opendaylight.restconf.nb.rfc8040.jersey.providers.spi.AbstractNormalizedNodeBodyReader;
36 import org.opendaylight.yangtools.util.xml.UntrustedXML;
37 import org.opendaylight.yangtools.yang.common.QName;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
39 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
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.DataSchemaContextNode;
46 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
48 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
51 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
52 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
56 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
57 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
60 import org.w3c.dom.Document;
61 import org.xml.sax.SAXException;
62
63 @Provider
64 @Consumes({ MediaTypes.APPLICATION_YANG_DATA_XML, MediaType.APPLICATION_XML, MediaType.TEXT_XML })
65 public class XmlNormalizedNodeBodyReader extends AbstractNormalizedNodeBodyReader {
66     private static final Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
67
68     public XmlNormalizedNodeBodyReader(final SchemaContextHandler schemaContextHandler,
69             final DOMMountPointService mountPointService) {
70         super(schemaContextHandler, mountPointService);
71     }
72
73     @SuppressWarnings("checkstyle:IllegalCatch")
74     @Override
75     protected NormalizedNodeContext 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             RestconfDocumentedException.throwIfYangError(e);
85             throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
86                     ErrorTag.MALFORMED_MESSAGE, e);
87         }
88     }
89
90     private NormalizedNodeContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc)
91             throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
92         final SchemaNode schemaNodeContext = pathContext.getSchemaNode();
93         DataSchemaNode schemaNode;
94         final boolean isOperation;
95         if (schemaNodeContext instanceof OperationDefinition) {
96             schemaNode = ((OperationDefinition) schemaNodeContext).getInput();
97             isOperation = true;
98         } else if (schemaNodeContext instanceof DataSchemaNode) {
99             schemaNode = (DataSchemaNode) schemaNodeContext;
100             isOperation = false;
101         } else {
102             throw new IllegalStateException("Unknown SchemaNode " + schemaNodeContext);
103         }
104
105         final String docRootElm = doc.getDocumentElement().getLocalName();
106         final String docRootNamespace = doc.getDocumentElement().getNamespaceURI();
107         final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
108
109         if (isPost() && !isOperation) {
110             final Deque<Object> foundSchemaNodes = findPathToSchemaNodeByName(schemaNode, docRootElm, docRootNamespace);
111             if (foundSchemaNodes.isEmpty()) {
112                 throw new IllegalStateException(String.format("Child \"%s\" was not found in parent schema node \"%s\"",
113                         docRootElm, schemaNode.getQName()));
114             }
115             while (!foundSchemaNodes.isEmpty()) {
116                 final Object child = foundSchemaNodes.pop();
117                 if (child instanceof AugmentationSchemaNode) {
118                     final AugmentationSchemaNode augmentSchemaNode = (AugmentationSchemaNode) child;
119                     iiToDataList.add(DataSchemaContextNode.augmentationIdentifierFrom(augmentSchemaNode));
120                 } else if (child instanceof DataSchemaNode) {
121                     schemaNode = (DataSchemaNode) child;
122                     iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(schemaNode.getQName()));
123                 }
124             }
125         // PUT
126         } else if (!isOperation) {
127             final QName scQName = schemaNode.getQName();
128             checkState(docRootElm.equals(scQName.getLocalName())
129                 && docRootNamespace.equals(scQName.getNamespace().toString()),
130                 "Not correct message root element \"%s\", should be \"%s\"", docRootElm, scQName);
131         }
132
133         NormalizedNode parsed;
134         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
135         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
136
137         if (schemaNode instanceof ContainerLike || schemaNode instanceof ListSchemaNode
138                 || schemaNode instanceof LeafSchemaNode) {
139             final XmlParserStream xmlParser = XmlParserStream.create(writer, SchemaInferenceStack.ofInstantiatedPath(
140                 pathContext.getSchemaContext(), schemaNode.getPath()).toInference());
141             xmlParser.traverse(new DOMSource(doc.getDocumentElement()));
142             parsed = resultHolder.getResult();
143
144             // When parsing an XML source with a list root node
145             // the new XML parser always returns a MapNode with one MapEntryNode inside.
146             // However, the old XML parser returned a MapEntryNode directly in this place.
147             // Therefore we now have to extract the MapEntryNode from the parsed MapNode.
148             if (parsed instanceof MapNode) {
149                 final MapNode mapNode = (MapNode) parsed;
150                 // extracting the MapEntryNode
151                 parsed = mapNode.body().iterator().next();
152             }
153
154             if (schemaNode instanceof  ListSchemaNode && isPost()) {
155                 iiToDataList.add(parsed.getIdentifier());
156             }
157         } else {
158             LOG.warn("Unknown schema node extension {} was not parsed", schemaNode.getClass());
159             parsed = null;
160         }
161
162         final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
163                 pathContext.getInstanceIdentifier().getPathArguments(), iiToDataList));
164
165         final InstanceIdentifierContext<? extends SchemaNode> outIIContext = new InstanceIdentifierContext<>(
166                 fullIIToData, pathContext.getSchemaNode(), pathContext.getMountPoint(), pathContext.getSchemaContext());
167
168         return new NormalizedNodeContext(outIIContext, parsed);
169     }
170
171     private static Deque<Object> findPathToSchemaNodeByName(final DataSchemaNode schemaNode, final String elementName,
172                                                             final String namespace) {
173         final Deque<Object> result = new ArrayDeque<>();
174         final ArrayList<ChoiceSchemaNode> choiceSchemaNodes = new ArrayList<>();
175         for (final DataSchemaNode child : ((DataNodeContainer) schemaNode).getChildNodes()) {
176             if (child instanceof ChoiceSchemaNode) {
177                 choiceSchemaNodes.add((ChoiceSchemaNode) child);
178             } else if (child.getQName().getLocalName().equalsIgnoreCase(elementName)
179                     && child.getQName().getNamespace().toString().equalsIgnoreCase(namespace)) {
180                 // add child to result
181                 result.push(child);
182
183                 // find augmentation
184                 if (child.isAugmenting()) {
185                     final AugmentationSchemaNode augment = findCorrespondingAugment(schemaNode, child);
186                     if (augment != null) {
187                         result.push(augment);
188                     }
189                 }
190
191                 // return result
192                 return result;
193             }
194         }
195
196         for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) {
197             for (final CaseSchemaNode caseNode : choiceNode.getCases()) {
198                 final Deque<Object> resultFromRecursion = findPathToSchemaNodeByName(caseNode, elementName, namespace);
199                 if (!resultFromRecursion.isEmpty()) {
200                     resultFromRecursion.push(choiceNode);
201                     if (choiceNode.isAugmenting()) {
202                         final AugmentationSchemaNode augment = findCorrespondingAugment(schemaNode, choiceNode);
203                         if (augment != null) {
204                             resultFromRecursion.push(augment);
205                         }
206                     }
207                     return resultFromRecursion;
208                 }
209             }
210         }
211         return result;
212     }
213
214     private static AugmentationSchemaNode findCorrespondingAugment(final DataSchemaNode parent,
215                                                                final DataSchemaNode child) {
216         if (parent instanceof AugmentationTarget && !(parent instanceof ChoiceSchemaNode)) {
217             for (AugmentationSchemaNode augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
218                 if (augmentation.dataChildByName(child.getQName()) != null) {
219                     return augmentation;
220                 }
221             }
222         }
223         return null;
224     }
225 }
226