Bug 8988 - Check for empty payload properly
[netconf.git] / restconf / restconf-nb-bierman02 / src / main / java / org / opendaylight / netconf / sal / rest / impl / XmlNormalizedNodeBodyReader.java
1 /*
2  * Copyright (c) 2014 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.netconf.sal.rest.impl;
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.lang.annotation.Annotation;
15 import java.lang.reflect.Type;
16 import java.net.URISyntaxException;
17 import java.util.ArrayDeque;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.Deque;
21 import java.util.List;
22 import java.util.Optional;
23 import javax.ws.rs.Consumes;
24 import javax.ws.rs.WebApplicationException;
25 import javax.ws.rs.core.MediaType;
26 import javax.ws.rs.core.MultivaluedMap;
27 import javax.ws.rs.ext.MessageBodyReader;
28 import javax.ws.rs.ext.Provider;
29 import javax.xml.parsers.ParserConfigurationException;
30 import javax.xml.stream.XMLStreamException;
31 import javax.xml.transform.dom.DOMSource;
32 import org.opendaylight.netconf.sal.rest.api.Draft02;
33 import org.opendaylight.netconf.sal.rest.api.RestconfService;
34 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
35 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
36 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
37 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
38 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
39 import org.opendaylight.restconf.common.util.RestUtil;
40 import org.opendaylight.yangtools.util.xml.UntrustedXML;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
44 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
46 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
47 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
48 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
49 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
50 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
51 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
52 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
53 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
56 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
60 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63 import org.w3c.dom.Document;
64 import org.xml.sax.SAXException;
65
66 @Provider
67 @Consumes({ Draft02.MediaTypes.DATA + RestconfService.XML, Draft02.MediaTypes.OPERATION + RestconfService.XML,
68         MediaType.APPLICATION_XML, MediaType.TEXT_XML })
69 public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsProvider
70         implements MessageBodyReader<NormalizedNodeContext> {
71
72     private static final Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
73
74     @Override
75     public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
76             final MediaType mediaType) {
77         return true;
78     }
79
80     @SuppressWarnings("checkstyle:IllegalCatch")
81     @Override
82     public NormalizedNodeContext readFrom(final Class<NormalizedNodeContext> type, final Type genericType,
83             final Annotation[] annotations, final MediaType mediaType,
84             final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException,
85             WebApplicationException {
86         try {
87             return readFrom(entityStream);
88         } catch (final RestconfDocumentedException e) {
89             throw e;
90         } catch (final Exception e) {
91             LOG.debug("Error parsing xml input", e);
92
93             throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
94                     ErrorTag.MALFORMED_MESSAGE, e);
95         }
96     }
97
98     private NormalizedNodeContext readFrom(final InputStream entityStream) throws IOException, SAXException,
99             XMLStreamException, ParserConfigurationException, URISyntaxException {
100         final InstanceIdentifierContext<?> path = getInstanceIdentifierContext();
101         final Optional<InputStream> nonEmptyInputStreamOptional = RestUtil.isInputStreamEmpty(entityStream);
102         if (!nonEmptyInputStreamOptional.isPresent()) {
103             // represent empty nopayload input
104             return new NormalizedNodeContext(path, null);
105         }
106
107         final Document doc = UntrustedXML.newDocumentBuilder().parse(nonEmptyInputStreamOptional.get());
108         return parse(path, doc);
109     }
110
111     private NormalizedNodeContext parse(final InstanceIdentifierContext<?> pathContext,final Document doc)
112             throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
113         final SchemaNode schemaNodeContext = pathContext.getSchemaNode();
114         DataSchemaNode schemaNode;
115         boolean isRpc = false;
116         if (schemaNodeContext instanceof RpcDefinition) {
117             schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
118             isRpc = true;
119         } else if (schemaNodeContext instanceof DataSchemaNode) {
120             schemaNode = (DataSchemaNode) schemaNodeContext;
121         } else {
122             throw new IllegalStateException("Unknown SchemaNode");
123         }
124
125         final String docRootElm = doc.getDocumentElement().getLocalName();
126         final String docRootNamespace = doc.getDocumentElement().getNamespaceURI();
127         final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
128
129         if (isPost() && !isRpc) {
130             final Deque<Object> foundSchemaNodes = findPathToSchemaNodeByName(schemaNode, docRootElm, docRootNamespace);
131             if (foundSchemaNodes.isEmpty()) {
132                 throw new IllegalStateException(String.format("Child \"%s\" was not found in parent schema node \"%s\"",
133                         docRootElm, schemaNode.getQName()));
134             }
135             while (!foundSchemaNodes.isEmpty()) {
136                 final Object child = foundSchemaNodes.pop();
137                 if (child instanceof AugmentationSchema) {
138                     final AugmentationSchema augmentSchemaNode = (AugmentationSchema) child;
139                     iiToDataList.add(SchemaUtils.getNodeIdentifierForAugmentation(augmentSchemaNode));
140                 } else if (child instanceof DataSchemaNode) {
141                     schemaNode = (DataSchemaNode) child;
142                     iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(schemaNode.getQName()));
143                 }
144             }
145         // PUT
146         } else if (!isRpc) {
147             final QName scQName = schemaNode.getQName();
148             Preconditions.checkState(
149                     docRootElm.equals(scQName.getLocalName())
150                             && docRootNamespace.equals(scQName.getNamespace().toASCIIString()),
151                     String.format("Not correct message root element \"%s\", should be \"%s\"",
152                             docRootElm, scQName));
153         }
154
155         NormalizedNode<?, ?> parsed;
156         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
157         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
158
159         if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode
160                 || schemaNode instanceof LeafSchemaNode) {
161             final XmlParserStream xmlParser = XmlParserStream.create(writer, pathContext.getSchemaContext(),
162                     schemaNode);
163             xmlParser.traverse(new DOMSource(doc.getDocumentElement()));
164             parsed = resultHolder.getResult();
165
166             // When parsing an XML source with a list root node
167             // the new XML parser always returns a MapNode with one MapEntryNode inside.
168             // However, the old XML parser returned a MapEntryNode directly in this place.
169             // Therefore we now have to extract the MapEntryNode from the parsed MapNode.
170             if (parsed instanceof MapNode) {
171                 final MapNode mapNode = (MapNode) parsed;
172                 // extracting the MapEntryNode
173                 parsed = mapNode.getValue().iterator().next();
174             }
175
176             if (schemaNode instanceof  ListSchemaNode && isPost()) {
177                 iiToDataList.add(parsed.getIdentifier());
178             }
179         } else {
180             LOG.warn("Unknown schema node extension {} was not parsed", schemaNode.getClass());
181             parsed = null;
182         }
183
184         final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
185                 pathContext.getInstanceIdentifier().getPathArguments(), iiToDataList));
186
187         final InstanceIdentifierContext<? extends SchemaNode> outIIContext = new InstanceIdentifierContext<>(
188                 fullIIToData, pathContext.getSchemaNode(), pathContext.getMountPoint(), pathContext.getSchemaContext());
189
190         return new NormalizedNodeContext(outIIContext, parsed);
191     }
192
193     private static Deque<Object> findPathToSchemaNodeByName(final DataSchemaNode schemaNode, final String elementName,
194                                                             final String namespace) {
195         final Deque<Object> result = new ArrayDeque<>();
196         final ArrayList<ChoiceSchemaNode> choiceSchemaNodes = new ArrayList<>();
197         final Collection<DataSchemaNode> children = ((DataNodeContainer) schemaNode).getChildNodes();
198         for (final DataSchemaNode child : children) {
199             if (child instanceof ChoiceSchemaNode) {
200                 choiceSchemaNodes.add((ChoiceSchemaNode) child);
201             } else if (child.getQName().getLocalName().equalsIgnoreCase(elementName)
202                     && child.getQName().getNamespace().toString().equalsIgnoreCase(namespace)) {
203                 // add child to result
204                 result.push(child);
205
206                 // find augmentation
207                 if (child.isAugmenting()) {
208                     final AugmentationSchema augment = findCorrespondingAugment(schemaNode, child);
209                     if (augment != null) {
210                         result.push(augment);
211                     }
212                 }
213
214                 // return result
215                 return result;
216             }
217         }
218
219         for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) {
220             for (final ChoiceCaseNode caseNode : choiceNode.getCases()) {
221                 final Deque<Object> resultFromRecursion = findPathToSchemaNodeByName(caseNode, elementName, namespace);
222                 if (!resultFromRecursion.isEmpty()) {
223                     resultFromRecursion.push(choiceNode);
224                     if (choiceNode.isAugmenting()) {
225                         final AugmentationSchema augment = findCorrespondingAugment(schemaNode, choiceNode);
226                         if (augment != null) {
227                             resultFromRecursion.push(augment);
228                         }
229                     }
230                     return resultFromRecursion;
231                 }
232             }
233         }
234         return result;
235     }
236
237     private static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent,
238                                                                final DataSchemaNode child) {
239         if ((parent instanceof AugmentationTarget) && !(parent instanceof ChoiceSchemaNode)) {
240             for (final AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
241                 final DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
242                 if (childInAugmentation != null) {
243                     return augmentation;
244                 }
245             }
246         }
247         return null;
248     }
249 }
250