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