8c6fa6b8198c5286ace3413c35e2b7ea1997a87c
[netconf.git] / restconf / sal-rest-connector / src / main / java / org / opendaylight / restconf / jersey / providers / XmlNormalizedNodeBodyReader.java
1 /*
2  * Copyright (c) 2016 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.restconf.jersey.providers;
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.core.Request;
26 import javax.ws.rs.core.UriInfo;
27 import javax.ws.rs.ext.MessageBodyReader;
28 import javax.ws.rs.ext.Provider;
29 import javax.xml.parsers.DocumentBuilder;
30 import javax.xml.parsers.DocumentBuilderFactory;
31 import javax.xml.parsers.ParserConfigurationException;
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.Draft18;
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({ Draft18.MediaTypes.DATA + RestconfConstants.XML, 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             final InstanceIdentifierContext<?> path = getInstanceIdentifierContext();
97
98             if (entityStream.available() < 1) {
99                 // represent empty nopayload input
100                 return new NormalizedNodeContext(path, null);
101             }
102
103             final DocumentBuilder dBuilder;
104             try {
105                 dBuilder = BUILDERFACTORY.newDocumentBuilder();
106             } catch (final ParserConfigurationException e) {
107                 throw new RuntimeException("Failed to parse XML document", e);
108             }
109             final Document doc = dBuilder.parse(entityStream);
110
111             return parse(path,doc);
112         } catch (final RestconfDocumentedException e){
113             throw e;
114         } catch (final Exception e) {
115             LOG.debug("Error parsing xml input", e);
116
117             throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
118                     ErrorTag.MALFORMED_MESSAGE);
119         }
120     }
121
122     private NormalizedNodeContext parse(final InstanceIdentifierContext<?> pathContext,final Document doc) {
123
124         final List<Element> elements = Collections.singletonList(doc.getDocumentElement());
125         final SchemaNode schemaNodeContext = pathContext.getSchemaNode();
126         DataSchemaNode schemaNode;
127         boolean isRpc = false;
128         if (schemaNodeContext instanceof RpcDefinition) {
129             schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
130             isRpc = true;
131         } else if (schemaNodeContext instanceof DataSchemaNode) {
132             schemaNode = (DataSchemaNode) schemaNodeContext;
133         } else {
134             throw new IllegalStateException("Unknown SchemaNode");
135         }
136
137         final String docRootElm = doc.getDocumentElement().getLocalName();
138         final String docRootNamespace = doc.getDocumentElement().getNamespaceURI();
139         final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
140         InstanceIdentifierContext<? extends SchemaNode> outIIContext;
141
142
143         final DomToNormalizedNodeParserFactory parserFactory =
144                 DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, pathContext.getSchemaContext());
145
146         if (isPost() && !isRpc) {
147             final Deque<Object> foundSchemaNodes = findPathToSchemaNodeByName(schemaNode, docRootElm, docRootNamespace);
148             if (foundSchemaNodes.isEmpty()) {
149                 throw new IllegalStateException(String.format("Child \"%s\" was not found in parent schema node \"%s\"",
150                         docRootElm, schemaNode.getQName()));
151             }
152             while (!foundSchemaNodes.isEmpty()) {
153                 final Object child = foundSchemaNodes.pop();
154                 if (child instanceof AugmentationSchema) {
155                     final AugmentationSchema augmentSchemaNode = (AugmentationSchema) child;
156                     iiToDataList.add(SchemaUtils.getNodeIdentifierForAugmentation(augmentSchemaNode));
157                 } else if (child instanceof DataSchemaNode) {
158                     schemaNode = (DataSchemaNode) child;
159                     iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(schemaNode.getQName()));
160                 }
161             }
162         }
163
164         NormalizedNode<?, ?> parsed = null;
165
166         if (schemaNode instanceof ContainerSchemaNode) {
167             parsed = parserFactory.getContainerNodeParser().parse(Collections.singletonList(doc.getDocumentElement()), (ContainerSchemaNode) schemaNode);
168         } else if(schemaNode instanceof ListSchemaNode) {
169             final ListSchemaNode casted = (ListSchemaNode) schemaNode;
170             parsed = parserFactory.getMapEntryNodeParser().parse(elements, casted);
171             if (isPost()) {
172                 iiToDataList.add(parsed.getIdentifier());
173             }
174         }
175
176         final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
177                 pathContext.getInstanceIdentifier().getPathArguments(), iiToDataList));
178
179         outIIContext = new InstanceIdentifierContext<>(fullIIToData, pathContext.getSchemaNode(), pathContext.getMountPoint(),
180                 pathContext.getSchemaContext());
181
182         return new NormalizedNodeContext(outIIContext, parsed);
183     }
184
185     private static Deque<Object> findPathToSchemaNodeByName(final DataSchemaNode schemaNode, final String elementName,
186                                                             final String namespace) {
187         final Deque<Object> result = new ArrayDeque<>();
188         final ArrayList<ChoiceSchemaNode> choiceSchemaNodes = new ArrayList<>();
189         final Collection<DataSchemaNode> children = ((DataNodeContainer) schemaNode).getChildNodes();
190         for (final DataSchemaNode child : children) {
191             if (child instanceof ChoiceSchemaNode) {
192                 choiceSchemaNodes.add((ChoiceSchemaNode) child);
193             } else if (child.getQName().getLocalName().equalsIgnoreCase(elementName)
194                     && child.getQName().getNamespace().toString().equalsIgnoreCase(namespace)) {
195                 // add child to result
196                 result.push(child);
197
198                 // find augmentation
199                 if (child.isAugmenting()) {
200                     final AugmentationSchema augment = findCorrespondingAugment(schemaNode, child);
201                     if (augment != null) {
202                         result.push(augment);
203                     }
204                 }
205
206                 // return result
207                 return result;
208             }
209         }
210
211         for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) {
212             for (final ChoiceCaseNode caseNode : choiceNode.getCases()) {
213                 final Deque<Object> resultFromRecursion = findPathToSchemaNodeByName(caseNode, elementName, namespace);
214                 if (!resultFromRecursion.isEmpty()) {
215                     resultFromRecursion.push(choiceNode);
216                     if (choiceNode.isAugmenting()) {
217                         final AugmentationSchema augment = findCorrespondingAugment(schemaNode, choiceNode);
218                         if (augment != null) {
219                             resultFromRecursion.push(augment);
220                         }
221                     }
222                     return resultFromRecursion;
223                 }
224             }
225         }
226         return result;
227     }
228
229     private static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent, final DataSchemaNode child) {
230         if ((parent instanceof AugmentationTarget) && !(parent instanceof ChoiceSchemaNode)) {
231             for (final AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
232                 final DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
233                 if (childInAugmentation != null) {
234                     return augmentation;
235                 }
236             }
237         }
238         return null;
239     }
240
241     public void injectParams(final UriInfo uriInfo, final Request request) {
242         setRequest(request);
243         setUriInfo(uriInfo);
244     }
245 }
246