Merge "BUG 3066 : Optimistic lock failed, on NetconfStateUpdate"
[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 java.io.IOException;
11 import java.io.InputStream;
12 import java.lang.annotation.Annotation;
13 import java.lang.reflect.Type;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.Collections;
17 import java.util.List;
18 import javax.ws.rs.Consumes;
19 import javax.ws.rs.WebApplicationException;
20 import javax.ws.rs.core.MediaType;
21 import javax.ws.rs.core.MultivaluedMap;
22 import javax.ws.rs.ext.MessageBodyReader;
23 import javax.ws.rs.ext.Provider;
24 import javax.xml.parsers.DocumentBuilder;
25 import javax.xml.parsers.DocumentBuilderFactory;
26 import javax.xml.parsers.ParserConfigurationException;
27 import org.opendaylight.controller.sal.rest.api.Draft02;
28 import org.opendaylight.controller.sal.rest.api.RestconfService;
29 import org.opendaylight.controller.sal.restconf.impl.InstanceIdentifierContext;
30 import org.opendaylight.controller.sal.restconf.impl.NormalizedNodeContext;
31 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
32 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
33 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
34 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
35 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
36 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
37 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
38 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
39 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
40 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
43 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
46 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.w3c.dom.Document;
50 import org.w3c.dom.Element;
51
52 @Provider
53 @Consumes({ Draft02.MediaTypes.DATA + RestconfService.XML, Draft02.MediaTypes.OPERATION + RestconfService.XML,
54     MediaType.APPLICATION_XML, MediaType.TEXT_XML })
55 public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsProvider implements MessageBodyReader<NormalizedNodeContext> {
56
57     private final static Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
58     private static final DocumentBuilderFactory BUILDERFACTORY;
59
60     static {
61         final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
62         try {
63             factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
64             factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
65             factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
66             factory.setXIncludeAware(false);
67             factory.setExpandEntityReferences(false);
68         } catch (final ParserConfigurationException e) {
69             throw new ExceptionInInitializerError(e);
70         }
71         factory.setNamespaceAware(true);
72         factory.setCoalescing(true);
73         factory.setIgnoringElementContentWhitespace(true);
74         factory.setIgnoringComments(true);
75         BUILDERFACTORY = factory;
76     }
77
78     @Override
79     public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
80             final MediaType mediaType) {
81         return true;
82     }
83
84     @Override
85     public NormalizedNodeContext readFrom(final Class<NormalizedNodeContext> type, final Type genericType,
86             final Annotation[] annotations, final MediaType mediaType,
87             final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException,
88             WebApplicationException {
89         try {
90             final InstanceIdentifierContext<?> path = getInstanceIdentifierContext();
91
92             if (entityStream.available() < 1) {
93                 // represent empty nopayload input
94                 return new NormalizedNodeContext(path, null);
95             }
96
97             final DocumentBuilder dBuilder;
98             try {
99                 dBuilder = BUILDERFACTORY.newDocumentBuilder();
100             } catch (final ParserConfigurationException e) {
101                 throw new RuntimeException("Failed to parse XML document", e);
102             }
103             final Document doc = dBuilder.parse(entityStream);
104
105             final NormalizedNode<?, ?> result = parse(path,doc);
106             return new NormalizedNodeContext(path,result);
107         } catch (final RestconfDocumentedException e){
108             throw e;
109         } catch (final Exception e) {
110             LOG.debug("Error parsing xml input", e);
111
112             throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
113                     ErrorTag.MALFORMED_MESSAGE);
114         }
115     }
116
117     private static NormalizedNode<?,?> parse(final InstanceIdentifierContext<?> pathContext,final Document doc) {
118
119         final List<Element> elements = Collections.singletonList(doc.getDocumentElement());
120         final SchemaNode schemaNodeContext = pathContext.getSchemaNode();
121         DataSchemaNode schemaNode;
122         if (schemaNodeContext instanceof RpcDefinition) {
123             schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
124         } else if (schemaNodeContext instanceof DataSchemaNode) {
125             schemaNode = (DataSchemaNode) schemaNodeContext;
126         } else {
127             throw new IllegalStateException("Unknow SchemaNode");
128         }
129
130         final String docRootElm = doc.getDocumentElement().getLocalName();
131         final String schemaNodeName = pathContext.getSchemaNode().getQName().getLocalName();
132
133         // FIXME the factory instance should be cached if the schema context is the same
134         final DomToNormalizedNodeParserFactory parserFactory =
135                 DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, pathContext.getSchemaContext());
136
137         if (!schemaNodeName.equalsIgnoreCase(docRootElm)) {
138             final DataSchemaNode foundSchemaNode = findSchemaNodeOrParentChoiceByName(schemaNode, docRootElm);
139             if (foundSchemaNode != null) {
140                 if (schemaNode instanceof AugmentationTarget) {
141                     final AugmentationSchema augmentSchemaNode = findCorrespondingAugment(schemaNode, foundSchemaNode);
142                     if (augmentSchemaNode != null) {
143                         return parserFactory.getAugmentationNodeParser().parse(elements, augmentSchemaNode);
144                     }
145                 }
146                 schemaNode = foundSchemaNode;
147             }
148         }
149
150         NormalizedNode<?, ?> parsed = null;
151
152         if(schemaNode instanceof ContainerSchemaNode) {
153             return parserFactory.getContainerNodeParser().parse(Collections.singletonList(doc.getDocumentElement()), (ContainerSchemaNode) schemaNode);
154         } else if(schemaNode instanceof ListSchemaNode) {
155             final ListSchemaNode casted = (ListSchemaNode) schemaNode;
156             return parserFactory.getMapEntryNodeParser().parse(elements, casted);
157         } else if (schemaNode instanceof ChoiceSchemaNode) {
158             final ChoiceSchemaNode casted = (ChoiceSchemaNode) schemaNode;
159             return parserFactory.getChoiceNodeParser().parse(elements, casted);
160         }
161         // FIXME : add another DataSchemaNode extensions e.g. LeafSchemaNode
162
163         return parsed;
164     }
165
166     private static DataSchemaNode findSchemaNodeOrParentChoiceByName(DataSchemaNode schemaNode, String elementName) {
167         final ArrayList<ChoiceSchemaNode> choiceSchemaNodes = new ArrayList<>();
168         final Collection<DataSchemaNode> children = ((DataNodeContainer) schemaNode).getChildNodes();
169         for (final DataSchemaNode child : children) {
170             if (child instanceof ChoiceSchemaNode) {
171                 choiceSchemaNodes.add((ChoiceSchemaNode) child);
172             } else if (child.getQName().getLocalName().equalsIgnoreCase(elementName)) {
173                 return child;
174             }
175         }
176
177         for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) {
178             for (final ChoiceCaseNode caseNode : choiceNode.getCases()) {
179                 final DataSchemaNode resultFromRecursion = findSchemaNodeOrParentChoiceByName(caseNode, elementName);
180                 if (resultFromRecursion != null) {
181                     // this returns top choice node in which child element is found
182                     return choiceNode;
183                 }
184             }
185         }
186         return null;
187     }
188
189     private static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent, final DataSchemaNode child) {
190         if (parent instanceof AugmentationTarget && !((parent instanceof ChoiceCaseNode) || (parent instanceof ChoiceSchemaNode))) {
191             for (AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
192                 DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
193                 if (childInAugmentation != null) {
194                     return augmentation;
195                 }
196             }
197         }
198         return null;
199     }
200 }
201