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