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