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