Bump upstreams for Silicon
[netconf.git] / restconf / restconf-nb-bierman02 / src / main / java / org / opendaylight / netconf / sal / rest / impl / XmlNormalizedNodeBodyReader.java
1 /*
2  * Copyright (c) 2014 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.netconf.sal.rest.impl;
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.lang.annotation.Annotation;
15 import java.lang.reflect.Type;
16 import java.net.URISyntaxException;
17 import java.util.ArrayDeque;
18 import java.util.ArrayList;
19 import java.util.Deque;
20 import java.util.List;
21 import java.util.Optional;
22 import javax.ws.rs.Consumes;
23 import javax.ws.rs.WebApplicationException;
24 import javax.ws.rs.core.MediaType;
25 import javax.ws.rs.core.MultivaluedMap;
26 import javax.ws.rs.ext.MessageBodyReader;
27 import javax.ws.rs.ext.Provider;
28 import javax.xml.parsers.ParserConfigurationException;
29 import javax.xml.stream.XMLStreamException;
30 import javax.xml.transform.dom.DOMSource;
31 import org.opendaylight.netconf.sal.rest.api.Draft02;
32 import org.opendaylight.netconf.sal.rest.api.RestconfService;
33 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
34 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
35 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
36 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
37 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
38 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
39 import org.opendaylight.restconf.common.util.RestUtil;
40 import org.opendaylight.yangtools.util.xml.UntrustedXML;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
44 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
46 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
47 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
48 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
49 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
50 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
52 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
55 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
56 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
60 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63 import org.w3c.dom.Document;
64 import org.xml.sax.SAXException;
65
66 @Provider
67 @Consumes({ Draft02.MediaTypes.DATA + RestconfService.XML, Draft02.MediaTypes.OPERATION + RestconfService.XML,
68         MediaType.APPLICATION_XML, MediaType.TEXT_XML })
69 public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsProvider
70         implements MessageBodyReader<NormalizedNodeContext> {
71
72     private static final Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
73
74     public XmlNormalizedNodeBodyReader(final ControllerContext controllerContext) {
75         super(controllerContext);
76     }
77
78     @Override
79     public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
80             final MediaType mediaType) {
81         return true;
82     }
83
84     @SuppressWarnings("checkstyle:IllegalCatch")
85     @Override
86     public NormalizedNodeContext readFrom(final Class<NormalizedNodeContext> type, final Type genericType,
87             final Annotation[] annotations, final MediaType mediaType,
88             final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws
89         WebApplicationException {
90         try {
91             return readFrom(entityStream);
92         } catch (final RestconfDocumentedException e) {
93             throw e;
94         } catch (final Exception e) {
95             LOG.debug("Error parsing xml input", e);
96
97             throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
98                     ErrorTag.MALFORMED_MESSAGE, e);
99         }
100     }
101
102     private NormalizedNodeContext readFrom(final InputStream entityStream) throws IOException, SAXException,
103             XMLStreamException, ParserConfigurationException, URISyntaxException {
104         final InstanceIdentifierContext<?> path = getInstanceIdentifierContext();
105         final Optional<InputStream> nonEmptyInputStreamOptional = RestUtil.isInputStreamEmpty(entityStream);
106         if (!nonEmptyInputStreamOptional.isPresent()) {
107             // represent empty nopayload input
108             return new NormalizedNodeContext(path, null);
109         }
110
111         final Document doc = UntrustedXML.newDocumentBuilder().parse(nonEmptyInputStreamOptional.get());
112         return parse(path, doc);
113     }
114
115     private NormalizedNodeContext parse(final InstanceIdentifierContext<?> pathContext,final Document doc)
116             throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
117         final SchemaNode schemaNodeContext = pathContext.getSchemaNode();
118         DataSchemaNode schemaNode;
119         boolean isRpc = false;
120         if (schemaNodeContext instanceof RpcDefinition) {
121             schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
122             isRpc = true;
123         } else if (schemaNodeContext instanceof DataSchemaNode) {
124             schemaNode = (DataSchemaNode) schemaNodeContext;
125         } else {
126             throw new IllegalStateException("Unknown SchemaNode");
127         }
128
129         final String docRootElm = doc.getDocumentElement().getLocalName();
130         final String docRootNamespace = doc.getDocumentElement().getNamespaceURI();
131         final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
132
133         if (isPost() && !isRpc) {
134             final Deque<Object> foundSchemaNodes = findPathToSchemaNodeByName(schemaNode, docRootElm, docRootNamespace);
135             if (foundSchemaNodes.isEmpty()) {
136                 throw new IllegalStateException(String.format("Child \"%s\" was not found in parent schema node \"%s\"",
137                         docRootElm, schemaNode.getQName()));
138             }
139             while (!foundSchemaNodes.isEmpty()) {
140                 final Object child = foundSchemaNodes.pop();
141                 if (child instanceof AugmentationSchemaNode) {
142                     final AugmentationSchemaNode augmentSchemaNode = (AugmentationSchemaNode) child;
143                     iiToDataList.add(DataSchemaContextNode.augmentationIdentifierFrom(augmentSchemaNode));
144                 } else if (child instanceof DataSchemaNode) {
145                     schemaNode = (DataSchemaNode) child;
146                     iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(schemaNode.getQName()));
147                 }
148             }
149         // PUT
150         } else if (!isRpc) {
151             final QName scQName = schemaNode.getQName();
152             Preconditions.checkState(
153                     docRootElm.equals(scQName.getLocalName())
154                             && docRootNamespace.equals(scQName.getNamespace().toASCIIString()),
155                     String.format("Not correct message root element \"%s\", should be \"%s\"",
156                             docRootElm, scQName));
157         }
158
159         NormalizedNode<?, ?> parsed;
160         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
161         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
162
163         if (schemaNode instanceof ContainerLike || schemaNode instanceof ListSchemaNode
164                 || schemaNode instanceof LeafSchemaNode) {
165             final XmlParserStream xmlParser = XmlParserStream.create(writer, pathContext.getSchemaContext(),
166                     schemaNode);
167             xmlParser.traverse(new DOMSource(doc.getDocumentElement()));
168             parsed = resultHolder.getResult();
169
170             // When parsing an XML source with a list root node
171             // the new XML parser always returns a MapNode with one MapEntryNode inside.
172             // However, the old XML parser returned a MapEntryNode directly in this place.
173             // Therefore we now have to extract the MapEntryNode from the parsed MapNode.
174             if (parsed instanceof MapNode) {
175                 final MapNode mapNode = (MapNode) parsed;
176                 // extracting the MapEntryNode
177                 parsed = mapNode.getValue().iterator().next();
178             }
179
180             if (schemaNode instanceof  ListSchemaNode && isPost()) {
181                 iiToDataList.add(parsed.getIdentifier());
182             }
183         } else {
184             LOG.warn("Unknown schema node extension {} was not parsed", schemaNode.getClass());
185             parsed = null;
186         }
187
188         final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
189                 pathContext.getInstanceIdentifier().getPathArguments(), iiToDataList));
190
191         final InstanceIdentifierContext<? extends SchemaNode> outIIContext = new InstanceIdentifierContext<>(
192                 fullIIToData, pathContext.getSchemaNode(), pathContext.getMountPoint(), pathContext.getSchemaContext());
193
194         return new NormalizedNodeContext(outIIContext, parsed);
195     }
196
197     private static Deque<Object> findPathToSchemaNodeByName(final DataSchemaNode schemaNode, final String elementName,
198                                                             final String namespace) {
199         final Deque<Object> result = new ArrayDeque<>();
200         final ArrayList<ChoiceSchemaNode> choiceSchemaNodes = new ArrayList<>();
201         for (final DataSchemaNode child : ((DataNodeContainer) schemaNode).getChildNodes()) {
202             if (child instanceof ChoiceSchemaNode) {
203                 choiceSchemaNodes.add((ChoiceSchemaNode) child);
204             } else if (child.getQName().getLocalName().equalsIgnoreCase(elementName)
205                     && child.getQName().getNamespace().toString().equalsIgnoreCase(namespace)) {
206                 // add child to result
207                 result.push(child);
208
209                 // find augmentation
210                 if (child.isAugmenting()) {
211                     final AugmentationSchemaNode augment = findCorrespondingAugment(schemaNode, child);
212                     if (augment != null) {
213                         result.push(augment);
214                     }
215                 }
216
217                 // return result
218                 return result;
219             }
220         }
221
222         for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) {
223             for (final CaseSchemaNode caseNode : choiceNode.getCases()) {
224                 final Deque<Object> resultFromRecursion = findPathToSchemaNodeByName(caseNode, elementName, namespace);
225                 if (!resultFromRecursion.isEmpty()) {
226                     resultFromRecursion.push(choiceNode);
227                     if (choiceNode.isAugmenting()) {
228                         final AugmentationSchemaNode augment = findCorrespondingAugment(schemaNode, choiceNode);
229                         if (augment != null) {
230                             resultFromRecursion.push(augment);
231                         }
232                     }
233                     return resultFromRecursion;
234                 }
235             }
236         }
237         return result;
238     }
239
240     private static AugmentationSchemaNode findCorrespondingAugment(final DataSchemaNode parent,
241                                                                final DataSchemaNode child) {
242         if (parent instanceof AugmentationTarget && !(parent instanceof ChoiceSchemaNode)) {
243             for (final AugmentationSchemaNode augmentation :
244                     ((AugmentationTarget) parent).getAvailableAugmentations()) {
245                 final DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
246                 if (childInAugmentation != null) {
247                     return augmentation;
248                 }
249             }
250         }
251         return null;
252     }
253 }
254