1345b37e309e917d248c3207978a3aeca6a2fffc
[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 /**
61  * Reader of XML to NormalizedNode.
62  *
63  * @deprecated move to splitted module restconf-nb-rfc8040
64  */
65 @Deprecated
66 @Provider
67 @Consumes({ Rfc8040.MediaTypes.DATA + RestconfConstants.XML, MediaType.APPLICATION_XML, MediaType.TEXT_XML })
68 public class XmlNormalizedNodeBodyReader extends AbstractNormalizedNodeBodyReader {
69     private static final Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
70
71     @SuppressWarnings("checkstyle:IllegalCatch")
72     @Override
73     protected NormalizedNodeContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
74             throws IOException, WebApplicationException {
75         try {
76             final Document doc = UntrustedXML.newDocumentBuilder().parse(entityStream);
77             return parse(path,doc);
78         } catch (final RestconfDocumentedException e) {
79             throw e;
80         } catch (final Exception e) {
81             LOG.debug("Error parsing xml input", e);
82
83             throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
84                     ErrorTag.MALFORMED_MESSAGE, e);
85         }
86     }
87
88     private NormalizedNodeContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc)
89             throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
90         final SchemaNode schemaNodeContext = pathContext.getSchemaNode();
91         DataSchemaNode schemaNode;
92         boolean isRpc = false;
93         if (schemaNodeContext instanceof RpcDefinition) {
94             schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
95             isRpc = true;
96         } else if (schemaNodeContext instanceof DataSchemaNode) {
97             schemaNode = (DataSchemaNode) schemaNodeContext;
98         } else {
99             throw new IllegalStateException("Unknown SchemaNode");
100         }
101
102         final String docRootElm = doc.getDocumentElement().getLocalName();
103         final String docRootNamespace = doc.getDocumentElement().getNamespaceURI();
104         final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
105
106         if (isPost() && !isRpc) {
107             final Deque<Object> foundSchemaNodes = findPathToSchemaNodeByName(schemaNode, docRootElm, docRootNamespace);
108             if (foundSchemaNodes.isEmpty()) {
109                 throw new IllegalStateException(String.format("Child \"%s\" was not found in parent schema node \"%s\"",
110                         docRootElm, schemaNode.getQName()));
111             }
112             while (!foundSchemaNodes.isEmpty()) {
113                 final Object child = foundSchemaNodes.pop();
114                 if (child instanceof AugmentationSchema) {
115                     final AugmentationSchema augmentSchemaNode = (AugmentationSchema) child;
116                     iiToDataList.add(SchemaUtils.getNodeIdentifierForAugmentation(augmentSchemaNode));
117                 } else if (child instanceof DataSchemaNode) {
118                     schemaNode = (DataSchemaNode) child;
119                     iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(schemaNode.getQName()));
120                 }
121             }
122         // PUT
123         } else if (!isRpc) {
124             final QName scQName = schemaNode.getQName();
125             Preconditions.checkState(
126                     docRootElm.equals(scQName.getLocalName())
127                             && docRootNamespace.equals(scQName.getNamespace().toASCIIString()),
128                     String.format("Not correct message root element \"%s\", should be \"%s\"",
129                             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 ContainerSchemaNode || schemaNode instanceof ListSchemaNode
137                 || schemaNode instanceof LeafSchemaNode) {
138             final XmlParserStream xmlParser = XmlParserStream.create(writer, pathContext.getSchemaContext(),
139                     schemaNode);
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.getValue().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         final Collection<DataSchemaNode> children = ((DataNodeContainer) schemaNode).getChildNodes();
175         for (final DataSchemaNode child : children) {
176             if (child instanceof ChoiceSchemaNode) {
177                 choiceSchemaNodes.add((ChoiceSchemaNode) child);
178             } else if (child.getQName().getLocalName().equalsIgnoreCase(elementName)
179                     && child.getQName().getNamespace().toString().equalsIgnoreCase(namespace)) {
180                 // add child to result
181                 result.push(child);
182
183                 // find augmentation
184                 if (child.isAugmenting()) {
185                     final AugmentationSchema augment = findCorrespondingAugment(schemaNode, child);
186                     if (augment != null) {
187                         result.push(augment);
188                     }
189                 }
190
191                 // return result
192                 return result;
193             }
194         }
195
196         for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) {
197             for (final ChoiceCaseNode caseNode : choiceNode.getCases()) {
198                 final Deque<Object> resultFromRecursion = findPathToSchemaNodeByName(caseNode, elementName, namespace);
199                 if (!resultFromRecursion.isEmpty()) {
200                     resultFromRecursion.push(choiceNode);
201                     if (choiceNode.isAugmenting()) {
202                         final AugmentationSchema augment = findCorrespondingAugment(schemaNode, choiceNode);
203                         if (augment != null) {
204                             resultFromRecursion.push(augment);
205                         }
206                     }
207                     return resultFromRecursion;
208                 }
209             }
210         }
211         return result;
212     }
213
214     private static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent,
215                                                                final DataSchemaNode child) {
216         if (parent instanceof AugmentationTarget && !(parent instanceof ChoiceSchemaNode)) {
217             for (final AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
218                 final DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
219                 if (childInAugmentation != null) {
220                     return augmentation;
221                 }
222             }
223         }
224         return null;
225     }
226 }
227