Fix close() in provider
[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.restconf.Draft16;
38 import org.opendaylight.restconf.utils.RestconfConstants;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
40 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
41 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
42 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
43 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
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.ListSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
53 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56 import org.w3c.dom.Document;
57 import org.w3c.dom.Element;
58
59 @Provider
60 @Consumes({ Draft02.MediaTypes.DATA + RestconfService.XML, Draft02.MediaTypes.OPERATION + RestconfService.XML,
61         Draft16.MediaTypes.DATA + RestconfConstants.XML_ORIG, MediaType.APPLICATION_XML, MediaType.TEXT_XML })
62 public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsProvider implements MessageBodyReader<NormalizedNodeContext> {
63
64     private final static Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
65     private static final DocumentBuilderFactory BUILDERFACTORY;
66
67     static {
68         final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
69         try {
70             factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
71             factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
72             factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
73             factory.setXIncludeAware(false);
74             factory.setExpandEntityReferences(false);
75         } catch (final ParserConfigurationException e) {
76             throw new ExceptionInInitializerError(e);
77         }
78         factory.setNamespaceAware(true);
79         factory.setCoalescing(true);
80         factory.setIgnoringElementContentWhitespace(true);
81         factory.setIgnoringComments(true);
82         BUILDERFACTORY = factory;
83     }
84
85     @Override
86     public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
87             final MediaType mediaType) {
88         return true;
89     }
90
91     @Override
92     public NormalizedNodeContext readFrom(final Class<NormalizedNodeContext> type, final Type genericType,
93             final Annotation[] annotations, final MediaType mediaType,
94             final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException,
95             WebApplicationException {
96         try {
97             final InstanceIdentifierContext<?> path = getInstanceIdentifierContext();
98
99             if (entityStream.available() < 1) {
100                 // represent empty nopayload input
101                 return new NormalizedNodeContext(path, null);
102             }
103
104             final DocumentBuilder dBuilder;
105             try {
106                 dBuilder = BUILDERFACTORY.newDocumentBuilder();
107             } catch (final ParserConfigurationException e) {
108                 throw new RuntimeException("Failed to parse XML document", e);
109             }
110             final Document doc = dBuilder.parse(entityStream);
111
112             return parse(path,doc);
113         } catch (final RestconfDocumentedException e){
114             throw e;
115         } catch (final Exception e) {
116             LOG.debug("Error parsing xml input", e);
117
118             throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
119                     ErrorTag.MALFORMED_MESSAGE);
120         }
121     }
122
123     private NormalizedNodeContext parse(final InstanceIdentifierContext<?> pathContext,final Document doc) {
124
125         final List<Element> elements = Collections.singletonList(doc.getDocumentElement());
126         final SchemaNode schemaNodeContext = pathContext.getSchemaNode();
127         DataSchemaNode schemaNode;
128         boolean isRpc = false;
129         if (schemaNodeContext instanceof RpcDefinition) {
130             schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
131             isRpc = true;
132         } else if (schemaNodeContext instanceof DataSchemaNode) {
133             schemaNode = (DataSchemaNode) schemaNodeContext;
134         } else {
135             throw new IllegalStateException("Unknown SchemaNode");
136         }
137
138         final String docRootElm = doc.getDocumentElement().getLocalName();
139         final String docRootNamespace = doc.getDocumentElement().getNamespaceURI();
140         final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
141         InstanceIdentifierContext<? extends SchemaNode> outIIContext;
142
143
144         // FIXME the factory instance should be cached if the schema context is the same
145         final DomToNormalizedNodeParserFactory parserFactory =
146                 DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, pathContext.getSchemaContext());
147
148         if (isPost() && !isRpc) {
149             final Deque<Object> foundSchemaNodes = findPathToSchemaNodeByName(schemaNode, docRootElm, docRootNamespace);
150             if (foundSchemaNodes.isEmpty()) {
151                 throw new IllegalStateException(String.format("Child \"%s\" was not found in parent schema node \"%s\"",
152                         docRootElm, schemaNode.getQName()));
153             }
154             while (!foundSchemaNodes.isEmpty()) {
155                 final Object child = foundSchemaNodes.pop();
156                 if (child instanceof AugmentationSchema) {
157                     final AugmentationSchema augmentSchemaNode = (AugmentationSchema) child;
158                     iiToDataList.add(SchemaUtils.getNodeIdentifierForAugmentation(augmentSchemaNode));
159                 } else if (child instanceof DataSchemaNode) {
160                     schemaNode = (DataSchemaNode) child;
161                     iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(schemaNode.getQName()));
162                 }
163             }
164         }
165
166         NormalizedNode<?, ?> parsed = null;
167
168         if (schemaNode instanceof ContainerSchemaNode) {
169             parsed = parserFactory.getContainerNodeParser().parse(Collections.singletonList(doc.getDocumentElement()), (ContainerSchemaNode) schemaNode);
170         } else if(schemaNode instanceof ListSchemaNode) {
171             final ListSchemaNode casted = (ListSchemaNode) schemaNode;
172             parsed = parserFactory.getMapEntryNodeParser().parse(elements, casted);
173             if (isPost()) {
174                 iiToDataList.add(parsed.getIdentifier());
175             }
176         }
177         // FIXME : add another DataSchemaNode extensions e.g. LeafSchemaNode
178
179         final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
180                 pathContext.getInstanceIdentifier().getPathArguments(), iiToDataList));
181
182         outIIContext = new InstanceIdentifierContext<>(fullIIToData, pathContext.getSchemaNode(), pathContext.getMountPoint(),
183                 pathContext.getSchemaContext());
184
185         return new NormalizedNodeContext(outIIContext, parsed);
186     }
187
188     private static Deque<Object> findPathToSchemaNodeByName(final DataSchemaNode schemaNode, final String elementName,
189                                                             final String namespace) {
190         final Deque<Object> result = new ArrayDeque<>();
191         final ArrayList<ChoiceSchemaNode> choiceSchemaNodes = new ArrayList<>();
192         final Collection<DataSchemaNode> children = ((DataNodeContainer) schemaNode).getChildNodes();
193         for (final DataSchemaNode child : children) {
194             if (child instanceof ChoiceSchemaNode) {
195                 choiceSchemaNodes.add((ChoiceSchemaNode) child);
196             } else if (child.getQName().getLocalName().equalsIgnoreCase(elementName)
197                     && child.getQName().getNamespace().toString().equalsIgnoreCase(namespace)) {
198                 // add child to result
199                 result.push(child);
200
201                 // find augmentation
202                 if (child.isAugmenting()) {
203                     final AugmentationSchema augment = findCorrespondingAugment(schemaNode, child);
204                     if (augment != null) {
205                         result.push(augment);
206                     }
207                 }
208
209                 // return result
210                 return result;
211             }
212         }
213
214         for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) {
215             for (final ChoiceCaseNode caseNode : choiceNode.getCases()) {
216                 final Deque<Object> resultFromRecursion = findPathToSchemaNodeByName(caseNode, elementName, namespace);
217                 if (!resultFromRecursion.isEmpty()) {
218                     resultFromRecursion.push(choiceNode);
219                     if (choiceNode.isAugmenting()) {
220                         final AugmentationSchema augment = findCorrespondingAugment(schemaNode, choiceNode);
221                         if (augment != null) {
222                             resultFromRecursion.push(augment);
223                         }
224                     }
225                     return resultFromRecursion;
226                 }
227             }
228         }
229         return result;
230     }
231
232     private static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent, final DataSchemaNode child) {
233         if ((parent instanceof AugmentationTarget) && !(parent instanceof ChoiceSchemaNode)) {
234             for (final AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
235                 final DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
236                 if (childInAugmentation != null) {
237                     return augmentation;
238                 }
239             }
240         }
241         return null;
242     }
243 }
244