37baa231e71fb96c753e03983d9e22189dedc510
[netconf.git] / restconf / sal-rest-connector / 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.collect.Iterables;
11 import java.io.IOException;
12 import java.io.InputStream;
13 import java.lang.annotation.Annotation;
14 import java.lang.reflect.Type;
15 import java.util.ArrayDeque;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.Deque;
20 import java.util.List;
21 import javax.ws.rs.Consumes;
22 import javax.ws.rs.WebApplicationException;
23 import javax.ws.rs.core.MediaType;
24 import javax.ws.rs.core.MultivaluedMap;
25 import javax.ws.rs.ext.MessageBodyReader;
26 import javax.ws.rs.ext.Provider;
27 import javax.xml.parsers.DocumentBuilder;
28 import javax.xml.parsers.DocumentBuilderFactory;
29 import javax.xml.parsers.ParserConfigurationException;
30 import org.opendaylight.netconf.sal.rest.api.Draft02;
31 import org.opendaylight.netconf.sal.rest.api.RestconfService;
32 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
33 import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext;
34 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
35 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
36 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
38 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
39 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
40 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
41 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
42 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
43 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
44 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
45 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
48 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
51 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import org.w3c.dom.Document;
55 import org.w3c.dom.Element;
56 import org.xml.sax.SAXException;
57
58 @Provider
59 @Consumes({ Draft02.MediaTypes.DATA + RestconfService.XML, Draft02.MediaTypes.OPERATION + RestconfService.XML,
60         MediaType.APPLICATION_XML, MediaType.TEXT_XML })
61 public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsProvider implements MessageBodyReader<NormalizedNodeContext> {
62
63     private final static Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
64     private static final DocumentBuilderFactory BUILDERFACTORY;
65
66     static {
67         final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
68         try {
69             factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
70             factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
71             factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
72             factory.setXIncludeAware(false);
73             factory.setExpandEntityReferences(false);
74         } catch (final ParserConfigurationException e) {
75             throw new ExceptionInInitializerError(e);
76         }
77         factory.setNamespaceAware(true);
78         factory.setCoalescing(true);
79         factory.setIgnoringElementContentWhitespace(true);
80         factory.setIgnoringComments(true);
81         BUILDERFACTORY = factory;
82     }
83
84     @Override
85     public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
86             final MediaType mediaType) {
87         return true;
88     }
89
90     @Override
91     public NormalizedNodeContext readFrom(final Class<NormalizedNodeContext> type, final Type genericType,
92             final Annotation[] annotations, final MediaType mediaType,
93             final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException,
94             WebApplicationException {
95         try {
96             if (getUriInfo().getAbsolutePath().getPath().contains("restconf/16")) {
97                 final org.opendaylight.restconf.jersey.providers.XmlNormalizedNodeBodyReader xmlReaderNewRest =
98                         new org.opendaylight.restconf.jersey.providers.XmlNormalizedNodeBodyReader();
99                 xmlReaderNewRest.injectParams(getUriInfo(), getRequest());
100                 return xmlReaderNewRest.readFrom(type, genericType, annotations, mediaType, httpHeaders, entityStream);
101             } else {
102                 return readFrom(entityStream);
103             }
104         } catch (final RestconfDocumentedException e){
105             throw e;
106         } catch (final Exception e) {
107             LOG.debug("Error parsing xml input", e);
108
109             throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
110                     ErrorTag.MALFORMED_MESSAGE);
111         }
112     }
113
114     private NormalizedNodeContext readFrom(final InputStream entityStream) throws IOException, SAXException {
115         final InstanceIdentifierContext<?> path = getInstanceIdentifierContext();
116
117         if (entityStream.available() < 1) {
118             // represent empty nopayload input
119             return new NormalizedNodeContext(path, null);
120         }
121
122         final DocumentBuilder dBuilder;
123         try {
124             dBuilder = BUILDERFACTORY.newDocumentBuilder();
125         } catch (final ParserConfigurationException e) {
126             throw new RuntimeException("Failed to parse XML document", e);
127         }
128         final Document doc = dBuilder.parse(entityStream);
129
130         return parse(path,doc);
131     }
132
133     private NormalizedNodeContext parse(final InstanceIdentifierContext<?> pathContext,final Document doc) {
134
135         final List<Element> elements = Collections.singletonList(doc.getDocumentElement());
136         final SchemaNode schemaNodeContext = pathContext.getSchemaNode();
137         DataSchemaNode schemaNode;
138         boolean isRpc = false;
139         if (schemaNodeContext instanceof RpcDefinition) {
140             schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
141             isRpc = true;
142         } else if (schemaNodeContext instanceof DataSchemaNode) {
143             schemaNode = (DataSchemaNode) schemaNodeContext;
144         } else {
145             throw new IllegalStateException("Unknown SchemaNode");
146         }
147
148         final String docRootElm = doc.getDocumentElement().getLocalName();
149         final String docRootNamespace = doc.getDocumentElement().getNamespaceURI();
150         final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
151         InstanceIdentifierContext<? extends SchemaNode> outIIContext;
152
153
154         // FIXME the factory instance should be cached if the schema context is the same
155         final DomToNormalizedNodeParserFactory parserFactory =
156                 DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, pathContext.getSchemaContext());
157
158         if (isPost() && !isRpc) {
159             final Deque<Object> foundSchemaNodes = findPathToSchemaNodeByName(schemaNode, docRootElm, docRootNamespace);
160             if (foundSchemaNodes.isEmpty()) {
161                 throw new IllegalStateException(String.format("Child \"%s\" was not found in parent schema node \"%s\"",
162                         docRootElm, schemaNode.getQName()));
163             }
164             while (!foundSchemaNodes.isEmpty()) {
165                 final Object child = foundSchemaNodes.pop();
166                 if (child instanceof AugmentationSchema) {
167                     final AugmentationSchema augmentSchemaNode = (AugmentationSchema) child;
168                     iiToDataList.add(SchemaUtils.getNodeIdentifierForAugmentation(augmentSchemaNode));
169                 } else if (child instanceof DataSchemaNode) {
170                     schemaNode = (DataSchemaNode) child;
171                     iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(schemaNode.getQName()));
172                 }
173             }
174         }
175
176         NormalizedNode<?, ?> parsed = null;
177
178         if (schemaNode instanceof ContainerSchemaNode) {
179             parsed = parserFactory.getContainerNodeParser().parse(Collections.singletonList(doc.getDocumentElement()), (ContainerSchemaNode) schemaNode);
180         } else if(schemaNode instanceof ListSchemaNode) {
181             final ListSchemaNode casted = (ListSchemaNode) schemaNode;
182             parsed = parserFactory.getMapEntryNodeParser().parse(elements, casted);
183             if (isPost()) {
184                 iiToDataList.add(parsed.getIdentifier());
185             }
186         }
187         // FIXME : add another DataSchemaNode extensions e.g. LeafSchemaNode
188
189         final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
190                 pathContext.getInstanceIdentifier().getPathArguments(), iiToDataList));
191
192         outIIContext = new InstanceIdentifierContext<>(fullIIToData, pathContext.getSchemaNode(), pathContext.getMountPoint(),
193                 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 AugmentationSchema 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 ChoiceCaseNode caseNode : choiceNode.getCases()) {
226                 final Deque<Object> resultFromRecursion = findPathToSchemaNodeByName(caseNode, elementName, namespace);
227                 if (!resultFromRecursion.isEmpty()) {
228                     resultFromRecursion.push(choiceNode);
229                     if (choiceNode.isAugmenting()) {
230                         final AugmentationSchema 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 AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent, final DataSchemaNode child) {
243         if ((parent instanceof AugmentationTarget) && !(parent instanceof ChoiceSchemaNode)) {
244             for (final AugmentationSchema augmentation : ((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