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