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