Create transaction on the backend datastore only when neccessary
[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.ChoiceCaseNode;
38 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
41 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
44 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.w3c.dom.Document;
48 import org.w3c.dom.Element;
49
50 @Provider
51 @Consumes({ Draft02.MediaTypes.DATA + RestconfService.XML, Draft02.MediaTypes.OPERATION + RestconfService.XML,
52     MediaType.APPLICATION_XML, MediaType.TEXT_XML })
53 public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsProvider implements MessageBodyReader<NormalizedNodeContext> {
54
55     private final static Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
56     private static final DocumentBuilderFactory BUILDERFACTORY;
57
58     static {
59         final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
60         try {
61             factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
62             factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
63             factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
64             factory.setXIncludeAware(false);
65             factory.setExpandEntityReferences(false);
66         } catch (final ParserConfigurationException e) {
67             throw new ExceptionInInitializerError(e);
68         }
69         factory.setNamespaceAware(true);
70         factory.setCoalescing(true);
71         factory.setIgnoringElementContentWhitespace(true);
72         factory.setIgnoringComments(true);
73         BUILDERFACTORY = factory;
74     }
75
76     @Override
77     public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
78             final MediaType mediaType) {
79         return true;
80     }
81
82     @Override
83     public NormalizedNodeContext readFrom(final Class<NormalizedNodeContext> type, final Type genericType,
84             final Annotation[] annotations, final MediaType mediaType,
85             final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException,
86             WebApplicationException {
87         try {
88             final InstanceIdentifierContext<?> path = getInstanceIdentifierContext();
89
90             if (entityStream.available() < 1) {
91                 // represent empty nopayload input
92                 return new NormalizedNodeContext(path, null);
93             }
94
95             final DocumentBuilder dBuilder;
96             try {
97                 dBuilder = BUILDERFACTORY.newDocumentBuilder();
98             } catch (final ParserConfigurationException e) {
99                 throw new RuntimeException("Failed to parse XML document", e);
100             }
101             final Document doc = dBuilder.parse(entityStream);
102
103             final NormalizedNode<?, ?> result = parse(path,doc);
104             return new NormalizedNodeContext(path,result);
105         } catch (final Exception e) {
106             LOG.debug("Error parsing xml input", e);
107
108             throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
109                     ErrorTag.MALFORMED_MESSAGE);
110         }
111     }
112
113     private static NormalizedNode<?,?> parse(final InstanceIdentifierContext<?> pathContext,final Document doc) {
114
115         final List<Element> elements = Collections.singletonList(doc.getDocumentElement());
116         final SchemaNode schemaNodeContext = pathContext.getSchemaNode();
117         DataSchemaNode schemaNode;
118         if (schemaNodeContext instanceof RpcDefinition) {
119             schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
120         } else if (schemaNodeContext instanceof DataSchemaNode) {
121             schemaNode = (DataSchemaNode) schemaNodeContext;
122         } else {
123             throw new IllegalStateException("Unknow SchemaNode");
124         }
125
126         final String docRootElm = doc.getDocumentElement().getLocalName();
127         final String schemaNodeName = pathContext.getSchemaNode().getQName().getLocalName();
128
129         if (!schemaNodeName.equalsIgnoreCase(docRootElm)) {
130             final DataSchemaNode foundSchemaNode = findSchemaNodeOrParentChoiceByName(schemaNode, docRootElm);
131             if (foundSchemaNode != null) {
132                 schemaNode = foundSchemaNode;
133             }
134         }
135
136         // FIXME the factory instance should be cached if the schema context is the same
137         final DomToNormalizedNodeParserFactory parserFactory =
138                 DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, pathContext.getSchemaContext());
139
140         NormalizedNode<?, ?> parsed = null;
141         if(schemaNode instanceof ContainerSchemaNode) {
142             return parserFactory.getContainerNodeParser().parse(Collections.singletonList(doc.getDocumentElement()), (ContainerSchemaNode) schemaNode);
143         } else if(schemaNode instanceof ListSchemaNode) {
144             final ListSchemaNode casted = (ListSchemaNode) schemaNode;
145             return parserFactory.getMapEntryNodeParser().parse(elements, casted);
146         } else if (schemaNode instanceof ChoiceSchemaNode) {
147             final ChoiceSchemaNode casted = (ChoiceSchemaNode) schemaNode;
148             return parserFactory.getChoiceNodeParser().parse(elements, casted);
149         }
150
151         // FIXME : add another DataSchemaNode extensions e.g. LeafSchemaNode
152
153         return parsed;
154     }
155
156     private static DataSchemaNode findSchemaNodeOrParentChoiceByName(DataSchemaNode schemaNode, String elementName) {
157         final ArrayList<ChoiceSchemaNode> choiceSchemaNodes = new ArrayList<>();
158         final Collection<DataSchemaNode> children = ((DataNodeContainer) schemaNode).getChildNodes();
159         for (final DataSchemaNode child : children) {
160             if (child instanceof ChoiceSchemaNode) {
161                 choiceSchemaNodes.add((ChoiceSchemaNode) child);
162             } else if (child.getQName().getLocalName().equalsIgnoreCase(elementName)) {
163                 return child;
164             }
165         }
166
167         for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) {
168             for (final ChoiceCaseNode caseNode : choiceNode.getCases()) {
169                 final DataSchemaNode resultFromRecursion = findSchemaNodeOrParentChoiceByName(caseNode, elementName);
170                 if (resultFromRecursion != null) {
171                     // this returns top choice node in which child element is found
172                     return choiceNode;
173                 }
174             }
175         }
176         return null;
177     }
178 }
179