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