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