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