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