Delete netconf
[controller.git] / opendaylight / md-sal / sal-rest-connector / src / main / java / org / opendaylight / controller / 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.controller.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.controller.sal.rest.api.Draft02;
31 import org.opendaylight.controller.sal.rest.api.RestconfService;
32 import org.opendaylight.controller.sal.restconf.impl.InstanceIdentifierContext;
33 import org.opendaylight.controller.sal.restconf.impl.NormalizedNodeContext;
34 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
35 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
36 import org.opendaylight.controller.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
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     private static final DocumentBuilderFactory BUILDERFACTORY;
64
65     static {
66         final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
67         try {
68             factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
69             factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
70             factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
71             factory.setXIncludeAware(false);
72             factory.setExpandEntityReferences(false);
73         } catch (final ParserConfigurationException e) {
74             throw new ExceptionInInitializerError(e);
75         }
76         factory.setNamespaceAware(true);
77         factory.setCoalescing(true);
78         factory.setIgnoringElementContentWhitespace(true);
79         factory.setIgnoringComments(true);
80         BUILDERFACTORY = factory;
81     }
82
83     @Override
84     public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
85             final MediaType mediaType) {
86         return true;
87     }
88
89     @Override
90     public NormalizedNodeContext readFrom(final Class<NormalizedNodeContext> type, final Type genericType,
91             final Annotation[] annotations, final MediaType mediaType,
92             final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException,
93             WebApplicationException {
94         try {
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 DocumentBuilder dBuilder;
103             try {
104                 dBuilder = BUILDERFACTORY.newDocumentBuilder();
105             } catch (final ParserConfigurationException e) {
106                 throw new RuntimeException("Failed to parse XML document", e);
107             }
108             final Document doc = dBuilder.parse(entityStream);
109
110             return parse(path,doc);
111         } catch (final RestconfDocumentedException e){
112             throw e;
113         } catch (final Exception e) {
114             LOG.debug("Error parsing xml input", e);
115
116             throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
117                     ErrorTag.MALFORMED_MESSAGE);
118         }
119     }
120
121     private NormalizedNodeContext parse(final InstanceIdentifierContext<?> pathContext,final Document doc) {
122
123         final List<Element> elements = Collections.singletonList(doc.getDocumentElement());
124         final SchemaNode schemaNodeContext = pathContext.getSchemaNode();
125         DataSchemaNode schemaNode;
126         boolean isRpc = false;
127         if (schemaNodeContext instanceof RpcDefinition) {
128             schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
129             isRpc = true;
130         } else if (schemaNodeContext instanceof DataSchemaNode) {
131             schemaNode = (DataSchemaNode) schemaNodeContext;
132         } else {
133             throw new IllegalStateException("Unknow SchemaNode");
134         }
135
136         final String docRootElm = doc.getDocumentElement().getLocalName();
137         final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
138         InstanceIdentifierContext<? extends SchemaNode> outIIContext;
139
140
141         // FIXME the factory instance should be cached if the schema context is the same
142         final DomToNormalizedNodeParserFactory parserFactory =
143                 DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, pathContext.getSchemaContext());
144
145         if (isPost() && !isRpc) {
146             final Deque<Object> foundSchemaNodes = findPathToSchemaNodeByName(schemaNode, docRootElm);
147             if (foundSchemaNodes.isEmpty()) {
148                 throw new IllegalStateException(String.format("Child \"%s\" was not found in parent schema node \"%s\"",
149                         docRootElm, schemaNode.getQName()));
150             }
151             while (!foundSchemaNodes.isEmpty()) {
152                 final Object child = foundSchemaNodes.pop();
153                 if (child instanceof AugmentationSchema) {
154                     final AugmentationSchema augmentSchemaNode = (AugmentationSchema) child;
155                     iiToDataList.add(SchemaUtils.getNodeIdentifierForAugmentation(augmentSchemaNode));
156                 } else if (child instanceof DataSchemaNode) {
157                     schemaNode = (DataSchemaNode) child;
158                     iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(schemaNode.getQName()));
159                 }
160             }
161         }
162
163         NormalizedNode<?, ?> parsed = null;
164
165         if(schemaNode instanceof ContainerSchemaNode) {
166             parsed = parserFactory.getContainerNodeParser().parse(Collections.singletonList(doc.getDocumentElement()), (ContainerSchemaNode) schemaNode);
167         } else if(schemaNode instanceof ListSchemaNode) {
168             final ListSchemaNode casted = (ListSchemaNode) schemaNode;
169             parsed = parserFactory.getMapEntryNodeParser().parse(elements, casted);
170             if (isPost()) {
171                 iiToDataList.add(parsed.getIdentifier());
172             }
173         }
174         // FIXME : add another DataSchemaNode extensions e.g. LeafSchemaNode
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 Deque<Object> result = new ArrayDeque<>();
187         final ArrayList<ChoiceSchemaNode> choiceSchemaNodes = new ArrayList<>();
188         final Collection<DataSchemaNode> children = ((DataNodeContainer) schemaNode).getChildNodes();
189         for (final DataSchemaNode child : children) {
190             if (child instanceof ChoiceSchemaNode) {
191                 choiceSchemaNodes.add((ChoiceSchemaNode) child);
192             } else if (child.getQName().getLocalName().equalsIgnoreCase(elementName)) {
193                 result.push(child);
194                 if (child.isAugmenting()) {
195                     final AugmentationSchema augment = findCorrespondingAugment(schemaNode, child);
196                     if (augment != null) {
197                         result.push(augment);
198                     }
199                 }
200                 return result;
201             }
202         }
203
204         for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) {
205             for (final ChoiceCaseNode caseNode : choiceNode.getCases()) {
206                 final Deque<Object> resultFromRecursion = findPathToSchemaNodeByName(caseNode, elementName);
207                 if (!resultFromRecursion.isEmpty()) {
208                     resultFromRecursion.push(choiceNode);
209                     if (choiceNode.isAugmenting()) {
210                         final AugmentationSchema augment = findCorrespondingAugment(schemaNode, choiceNode);
211                         if (augment != null) {
212                             resultFromRecursion.push(augment);
213                         }
214                     }
215                     return resultFromRecursion;
216                 }
217             }
218         }
219         return result;
220     }
221
222     private static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent, final DataSchemaNode child) {
223         if (parent instanceof AugmentationTarget && !(parent instanceof ChoiceSchemaNode)) {
224             for (final AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
225                 final DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
226                 if (childInAugmentation != null) {
227                     return augmentation;
228                 }
229             }
230         }
231         return null;
232     }
233 }
234