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