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