3e28d04324b21e0a88793b14fc344a27c10e58bd
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / 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.nb.rfc8040.jersey.providers;
9
10 import static com.google.common.base.Preconditions.checkState;
11
12 import com.google.common.collect.Iterables;
13 import java.io.IOException;
14 import java.io.InputStream;
15 import java.net.URISyntaxException;
16 import java.util.ArrayDeque;
17 import java.util.ArrayList;
18 import java.util.Deque;
19 import java.util.List;
20 import javax.ws.rs.Consumes;
21 import javax.ws.rs.WebApplicationException;
22 import javax.ws.rs.core.MediaType;
23 import javax.ws.rs.ext.Provider;
24 import javax.xml.parsers.ParserConfigurationException;
25 import javax.xml.stream.XMLStreamException;
26 import javax.xml.transform.dom.DOMSource;
27 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
28 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
29 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
30 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
31 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
32 import org.opendaylight.restconf.nb.rfc8040.MediaTypes;
33 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
34 import org.opendaylight.yangtools.util.xml.UntrustedXML;
35 import org.opendaylight.yangtools.yang.common.ErrorType;
36 import org.opendaylight.yangtools.yang.common.QName;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
38 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
41 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
42 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
43 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
44 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
45 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
47 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
50 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
51 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
55 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
56 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59 import org.w3c.dom.Document;
60 import org.xml.sax.SAXException;
61
62 @Provider
63 @Consumes({ MediaTypes.APPLICATION_YANG_DATA_XML, MediaType.APPLICATION_XML, MediaType.TEXT_XML })
64 public class XmlNormalizedNodeBodyReader extends AbstractNormalizedNodeBodyReader {
65     private static final Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
66
67     public XmlNormalizedNodeBodyReader(final SchemaContextHandler schemaContextHandler,
68             final DOMMountPointService mountPointService) {
69         super(schemaContextHandler, mountPointService);
70     }
71
72     @SuppressWarnings("checkstyle:IllegalCatch")
73     @Override
74     protected NormalizedNodeContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
75             throws WebApplicationException {
76         try {
77             final Document doc = UntrustedXML.newDocumentBuilder().parse(entityStream);
78             return parse(path,doc);
79         } catch (final RestconfDocumentedException e) {
80             throw e;
81         } catch (final Exception e) {
82             LOG.debug("Error parsing xml input", e);
83             RestconfDocumentedException.throwIfYangError(e);
84             throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
85                     ErrorTag.MALFORMED_MESSAGE, e);
86         }
87     }
88
89     private NormalizedNodeContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc)
90             throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
91         final SchemaNode schemaNodeContext = pathContext.getSchemaNode();
92         DataSchemaNode schemaNode;
93         final boolean isOperation;
94         if (schemaNodeContext instanceof OperationDefinition) {
95             schemaNode = ((OperationDefinition) schemaNodeContext).getInput();
96             isOperation = true;
97         } else if (schemaNodeContext instanceof DataSchemaNode) {
98             schemaNode = (DataSchemaNode) schemaNodeContext;
99             isOperation = false;
100         } else {
101             throw new IllegalStateException("Unknown SchemaNode " + schemaNodeContext);
102         }
103
104         final String docRootElm = doc.getDocumentElement().getLocalName();
105         final String docRootNamespace = doc.getDocumentElement().getNamespaceURI();
106         final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
107
108         if (isPost() && !isOperation) {
109             final Deque<Object> foundSchemaNodes = findPathToSchemaNodeByName(schemaNode, docRootElm, docRootNamespace);
110             if (foundSchemaNodes.isEmpty()) {
111                 throw new IllegalStateException(String.format("Child \"%s\" was not found in parent schema node \"%s\"",
112                         docRootElm, schemaNode.getQName()));
113             }
114             while (!foundSchemaNodes.isEmpty()) {
115                 final Object child = foundSchemaNodes.pop();
116                 if (child instanceof AugmentationSchemaNode) {
117                     final AugmentationSchemaNode augmentSchemaNode = (AugmentationSchemaNode) child;
118                     iiToDataList.add(DataSchemaContextNode.augmentationIdentifierFrom(augmentSchemaNode));
119                 } else if (child instanceof DataSchemaNode) {
120                     schemaNode = (DataSchemaNode) child;
121                     iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(schemaNode.getQName()));
122                 }
123             }
124         // PUT
125         } else if (!isOperation) {
126             final QName scQName = schemaNode.getQName();
127             checkState(docRootElm.equals(scQName.getLocalName())
128                 && docRootNamespace.equals(scQName.getNamespace().toString()),
129                 "Not correct message root element \"%s\", should be \"%s\"", docRootElm, scQName);
130         }
131
132         NormalizedNode parsed;
133         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
134         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
135
136         if (schemaNode instanceof ContainerLike || schemaNode instanceof ListSchemaNode
137                 || schemaNode instanceof LeafSchemaNode) {
138             final XmlParserStream xmlParser = XmlParserStream.create(writer, SchemaInferenceStack.ofInstantiatedPath(
139                 pathContext.getSchemaContext(), schemaNode.getPath()).toInference());
140             xmlParser.traverse(new DOMSource(doc.getDocumentElement()));
141             parsed = resultHolder.getResult();
142
143             // When parsing an XML source with a list root node
144             // the new XML parser always returns a MapNode with one MapEntryNode inside.
145             // However, the old XML parser returned a MapEntryNode directly in this place.
146             // Therefore we now have to extract the MapEntryNode from the parsed MapNode.
147             if (parsed instanceof MapNode) {
148                 final MapNode mapNode = (MapNode) parsed;
149                 // extracting the MapEntryNode
150                 parsed = mapNode.body().iterator().next();
151             }
152
153             if (schemaNode instanceof  ListSchemaNode && isPost()) {
154                 iiToDataList.add(parsed.getIdentifier());
155             }
156         } else {
157             LOG.warn("Unknown schema node extension {} was not parsed", schemaNode.getClass());
158             parsed = null;
159         }
160
161         final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
162                 pathContext.getInstanceIdentifier().getPathArguments(), iiToDataList));
163
164         final InstanceIdentifierContext<? extends SchemaNode> outIIContext = new InstanceIdentifierContext<>(
165                 fullIIToData, pathContext.getSchemaNode(), pathContext.getMountPoint(), pathContext.getSchemaContext());
166
167         return new NormalizedNodeContext(outIIContext, parsed);
168     }
169
170     private static Deque<Object> findPathToSchemaNodeByName(final DataSchemaNode schemaNode, final String elementName,
171                                                             final String namespace) {
172         final Deque<Object> result = new ArrayDeque<>();
173         final ArrayList<ChoiceSchemaNode> choiceSchemaNodes = new ArrayList<>();
174         for (final DataSchemaNode child : ((DataNodeContainer) schemaNode).getChildNodes()) {
175             if (child instanceof ChoiceSchemaNode) {
176                 choiceSchemaNodes.add((ChoiceSchemaNode) child);
177             } else if (child.getQName().getLocalName().equalsIgnoreCase(elementName)
178                     && child.getQName().getNamespace().toString().equalsIgnoreCase(namespace)) {
179                 // add child to result
180                 result.push(child);
181
182                 // find augmentation
183                 if (child.isAugmenting()) {
184                     final AugmentationSchemaNode augment = findCorrespondingAugment(schemaNode, child);
185                     if (augment != null) {
186                         result.push(augment);
187                     }
188                 }
189
190                 // return result
191                 return result;
192             }
193         }
194
195         for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) {
196             for (final CaseSchemaNode caseNode : choiceNode.getCases()) {
197                 final Deque<Object> resultFromRecursion = findPathToSchemaNodeByName(caseNode, elementName, namespace);
198                 if (!resultFromRecursion.isEmpty()) {
199                     resultFromRecursion.push(choiceNode);
200                     if (choiceNode.isAugmenting()) {
201                         final AugmentationSchemaNode augment = findCorrespondingAugment(schemaNode, choiceNode);
202                         if (augment != null) {
203                             resultFromRecursion.push(augment);
204                         }
205                     }
206                     return resultFromRecursion;
207                 }
208             }
209         }
210         return result;
211     }
212
213     private static AugmentationSchemaNode findCorrespondingAugment(final DataSchemaNode parent,
214                                                                final DataSchemaNode child) {
215         if (parent instanceof AugmentationTarget && !(parent instanceof ChoiceSchemaNode)) {
216             for (AugmentationSchemaNode augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
217                 if (augmentation.dataChildByName(child.getQName()) != null) {
218                     return augmentation;
219                 }
220             }
221         }
222         return null;
223     }
224 }
225