Merge "BUG 3045 : Use non-strict parsing in hello message."
[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 Exception e) {
108             LOG.debug("Error parsing xml input", e);
109
110             throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
111                     ErrorTag.MALFORMED_MESSAGE);
112         }
113     }
114
115     private static NormalizedNode<?,?> parse(final InstanceIdentifierContext<?> pathContext,final Document doc) {
116
117         final List<Element> elements = Collections.singletonList(doc.getDocumentElement());
118         final SchemaNode schemaNodeContext = pathContext.getSchemaNode();
119         DataSchemaNode schemaNode;
120         if (schemaNodeContext instanceof RpcDefinition) {
121             schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
122         } else if (schemaNodeContext instanceof DataSchemaNode) {
123             schemaNode = (DataSchemaNode) schemaNodeContext;
124         } else {
125             throw new IllegalStateException("Unknow SchemaNode");
126         }
127
128         final String docRootElm = doc.getDocumentElement().getLocalName();
129         final String schemaNodeName = pathContext.getSchemaNode().getQName().getLocalName();
130
131         // FIXME the factory instance should be cached if the schema context is the same
132         final DomToNormalizedNodeParserFactory parserFactory =
133                 DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, pathContext.getSchemaContext());
134
135         if (!schemaNodeName.equalsIgnoreCase(docRootElm)) {
136             final DataSchemaNode foundSchemaNode = findSchemaNodeOrParentChoiceByName(schemaNode, docRootElm);
137             if (foundSchemaNode != null) {
138                 if (schemaNode instanceof AugmentationTarget) {
139                     final AugmentationSchema augmentSchemaNode = findCorrespondingAugment(schemaNode, foundSchemaNode);
140                     if (augmentSchemaNode != null) {
141                         return parserFactory.getAugmentationNodeParser().parse(elements, augmentSchemaNode);
142                     }
143                 }
144                 schemaNode = foundSchemaNode;
145             }
146         }
147
148         NormalizedNode<?, ?> parsed = null;
149
150         if(schemaNode instanceof ContainerSchemaNode) {
151             return parserFactory.getContainerNodeParser().parse(Collections.singletonList(doc.getDocumentElement()), (ContainerSchemaNode) schemaNode);
152         } else if(schemaNode instanceof ListSchemaNode) {
153             final ListSchemaNode casted = (ListSchemaNode) schemaNode;
154             return parserFactory.getMapEntryNodeParser().parse(elements, casted);
155         } else if (schemaNode instanceof ChoiceSchemaNode) {
156             final ChoiceSchemaNode casted = (ChoiceSchemaNode) schemaNode;
157             return parserFactory.getChoiceNodeParser().parse(elements, casted);
158         }
159         // FIXME : add another DataSchemaNode extensions e.g. LeafSchemaNode
160
161         return parsed;
162     }
163
164     private static DataSchemaNode findSchemaNodeOrParentChoiceByName(DataSchemaNode schemaNode, String elementName) {
165         final ArrayList<ChoiceSchemaNode> choiceSchemaNodes = new ArrayList<>();
166         final Collection<DataSchemaNode> children = ((DataNodeContainer) schemaNode).getChildNodes();
167         for (final DataSchemaNode child : children) {
168             if (child instanceof ChoiceSchemaNode) {
169                 choiceSchemaNodes.add((ChoiceSchemaNode) child);
170             } else if (child.getQName().getLocalName().equalsIgnoreCase(elementName)) {
171                 return child;
172             }
173         }
174
175         for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) {
176             for (final ChoiceCaseNode caseNode : choiceNode.getCases()) {
177                 final DataSchemaNode resultFromRecursion = findSchemaNodeOrParentChoiceByName(caseNode, elementName);
178                 if (resultFromRecursion != null) {
179                     // this returns top choice node in which child element is found
180                     return choiceNode;
181                 }
182             }
183         }
184         return null;
185     }
186
187     private static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent, final DataSchemaNode child) {
188         if (parent instanceof AugmentationTarget && !((parent instanceof ChoiceCaseNode) || (parent instanceof ChoiceSchemaNode))) {
189             for (AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
190                 DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
191                 if (childInAugmentation != null) {
192                     return augmentation;
193                 }
194             }
195         }
196         return null;
197     }
198 }
199