Don't loose cause when reporting parsing errors.
[netconf.git] / restconf / sal-rest-connector / src / main / java / org / opendaylight / restconf / 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.jersey.providers;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.collect.Iterables;
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.util.ArrayDeque;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.Collections;
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 org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
25 import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext;
26 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
27 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
28 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
29 import org.opendaylight.restconf.Rfc8040;
30 import org.opendaylight.restconf.utils.RestconfConstants;
31 import org.opendaylight.yangtools.util.xml.UntrustedXML;
32 import org.opendaylight.yangtools.yang.common.QName;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
34 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
35 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
36 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
37 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
38 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
39 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
40 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
41 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
44 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
48 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51 import org.w3c.dom.Document;
52 import org.w3c.dom.Element;
53
54 @Provider
55 @Consumes({ Rfc8040.MediaTypes.DATA + RestconfConstants.XML, MediaType.APPLICATION_XML, MediaType.TEXT_XML })
56 public class XmlNormalizedNodeBodyReader extends AbstractNormalizedNodeBodyReader {
57     private static final Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
58
59     @SuppressWarnings("checkstyle:IllegalCatch")
60     @Override
61     protected NormalizedNodeContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
62             throws IOException, WebApplicationException {
63         try {
64             final Document doc = UntrustedXML.newDocumentBuilder().parse(entityStream);
65             return parse(path,doc);
66         } catch (final RestconfDocumentedException e) {
67             throw e;
68         } catch (final Exception e) {
69             LOG.debug("Error parsing xml input", e);
70
71             throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
72                     ErrorTag.MALFORMED_MESSAGE, e);
73         }
74     }
75
76     private NormalizedNodeContext parse(final InstanceIdentifierContext<?> pathContext,final Document doc) {
77
78         final List<Element> elements = Collections.singletonList(doc.getDocumentElement());
79         final SchemaNode schemaNodeContext = pathContext.getSchemaNode();
80         DataSchemaNode schemaNode;
81         boolean isRpc = false;
82         if (schemaNodeContext instanceof RpcDefinition) {
83             schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
84             isRpc = true;
85         } else if (schemaNodeContext instanceof DataSchemaNode) {
86             schemaNode = (DataSchemaNode) schemaNodeContext;
87         } else {
88             throw new IllegalStateException("Unknown SchemaNode");
89         }
90
91         final String docRootElm = doc.getDocumentElement().getLocalName();
92         final String docRootNamespace = doc.getDocumentElement().getNamespaceURI();
93         final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
94         InstanceIdentifierContext<? extends SchemaNode> outIIContext;
95
96         final DomToNormalizedNodeParserFactory parserFactory =
97                 DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER,
98                     pathContext.getSchemaContext());
99
100         if (isPost() && !isRpc) {
101             final Deque<Object> foundSchemaNodes = findPathToSchemaNodeByName(schemaNode, docRootElm, docRootNamespace);
102             if (foundSchemaNodes.isEmpty()) {
103                 throw new IllegalStateException(String.format("Child \"%s\" was not found in parent schema node \"%s\"",
104                         docRootElm, schemaNode.getQName()));
105             }
106             while (!foundSchemaNodes.isEmpty()) {
107                 final Object child = foundSchemaNodes.pop();
108                 if (child instanceof AugmentationSchema) {
109                     final AugmentationSchema augmentSchemaNode = (AugmentationSchema) child;
110                     iiToDataList.add(SchemaUtils.getNodeIdentifierForAugmentation(augmentSchemaNode));
111                 } else if (child instanceof DataSchemaNode) {
112                     schemaNode = (DataSchemaNode) child;
113                     iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(schemaNode.getQName()));
114                 }
115             }
116         // PUT
117         } else if (!isRpc) {
118             final QName scQName = schemaNode.getQName();
119             Preconditions.checkState(
120                     docRootElm.equals(scQName.getLocalName())
121                             && docRootNamespace.equals(scQName.getNamespace().toASCIIString()),
122                     String.format("Not correct message root element \"%s\", should be \"%s\"",
123                             docRootElm, scQName));
124         }
125
126         final NormalizedNode<?, ?> parsed;
127         if (schemaNode instanceof ContainerSchemaNode) {
128             parsed = parserFactory.getContainerNodeParser().parse(
129                     Collections.singletonList(doc.getDocumentElement()), (ContainerSchemaNode) schemaNode);
130         } else if (schemaNode instanceof ListSchemaNode) {
131             parsed = parserFactory.getMapEntryNodeParser().parse(elements, (ListSchemaNode) schemaNode);
132             if (isPost()) {
133                 iiToDataList.add(parsed.getIdentifier());
134             }
135         } else if (schemaNode instanceof LeafSchemaNode) {
136             parsed = parserFactory.getLeafNodeParser().parse(elements, (LeafSchemaNode) schemaNode);
137         } else {
138             LOG.warn("Unknown schema node extension {} was not parsed", schemaNode.getClass());
139             parsed = null;
140         }
141
142         final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
143                 pathContext.getInstanceIdentifier().getPathArguments(), iiToDataList));
144
145         outIIContext = new InstanceIdentifierContext<>(fullIIToData, pathContext.getSchemaNode(),
146                 pathContext.getMountPoint(),
147                 pathContext.getSchemaContext());
148
149         return new NormalizedNodeContext(outIIContext, parsed);
150     }
151
152     private static Deque<Object> findPathToSchemaNodeByName(final DataSchemaNode schemaNode, final String elementName,
153                                                             final String namespace) {
154         final Deque<Object> result = new ArrayDeque<>();
155         final ArrayList<ChoiceSchemaNode> choiceSchemaNodes = new ArrayList<>();
156         final Collection<DataSchemaNode> children = ((DataNodeContainer) schemaNode).getChildNodes();
157         for (final DataSchemaNode child : children) {
158             if (child instanceof ChoiceSchemaNode) {
159                 choiceSchemaNodes.add((ChoiceSchemaNode) child);
160             } else if (child.getQName().getLocalName().equalsIgnoreCase(elementName)
161                     && child.getQName().getNamespace().toString().equalsIgnoreCase(namespace)) {
162                 // add child to result
163                 result.push(child);
164
165                 // find augmentation
166                 if (child.isAugmenting()) {
167                     final AugmentationSchema augment = findCorrespondingAugment(schemaNode, child);
168                     if (augment != null) {
169                         result.push(augment);
170                     }
171                 }
172
173                 // return result
174                 return result;
175             }
176         }
177
178         for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) {
179             for (final ChoiceCaseNode caseNode : choiceNode.getCases()) {
180                 final Deque<Object> resultFromRecursion = findPathToSchemaNodeByName(caseNode, elementName, namespace);
181                 if (!resultFromRecursion.isEmpty()) {
182                     resultFromRecursion.push(choiceNode);
183                     if (choiceNode.isAugmenting()) {
184                         final AugmentationSchema augment = findCorrespondingAugment(schemaNode, choiceNode);
185                         if (augment != null) {
186                             resultFromRecursion.push(augment);
187                         }
188                     }
189                     return resultFromRecursion;
190                 }
191             }
192         }
193         return result;
194     }
195
196     private static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent,
197                                                                final DataSchemaNode child) {
198         if (parent instanceof AugmentationTarget && !(parent instanceof ChoiceSchemaNode)) {
199             for (final AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
200                 final DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
201                 if (childInAugmentation != null) {
202                     return augmentation;
203                 }
204             }
205         }
206         return null;
207     }
208 }
209