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