Bug 2358: Fixed warnings in Restconf
[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.Collection;
15 import java.util.Collections;
16 import java.util.List;
17 import javax.ws.rs.Consumes;
18 import javax.ws.rs.WebApplicationException;
19 import javax.ws.rs.core.MediaType;
20 import javax.ws.rs.core.MultivaluedMap;
21 import javax.ws.rs.ext.MessageBodyReader;
22 import javax.ws.rs.ext.Provider;
23 import javax.xml.parsers.DocumentBuilder;
24 import javax.xml.parsers.DocumentBuilderFactory;
25 import javax.xml.parsers.ParserConfigurationException;
26 import org.opendaylight.controller.sal.rest.api.Draft02;
27 import org.opendaylight.controller.sal.rest.api.RestconfService;
28 import org.opendaylight.controller.sal.restconf.impl.InstanceIdentifierContext;
29 import org.opendaylight.controller.sal.restconf.impl.NormalizedNodeContext;
30 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
31 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
32 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
33 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
34 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
35 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
36 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
38 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
41 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.w3c.dom.Document;
45 import org.w3c.dom.Element;
46
47 @Provider
48 @Consumes({ Draft02.MediaTypes.DATA + RestconfService.XML, Draft02.MediaTypes.OPERATION + RestconfService.XML,
49     MediaType.APPLICATION_XML, MediaType.TEXT_XML })
50 public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsProvider implements MessageBodyReader<NormalizedNodeContext> {
51
52     private final static Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
53     private static final DocumentBuilderFactory BUILDERFACTORY;
54
55     static {
56         final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
57         try {
58             factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
59             factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
60             factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
61             factory.setXIncludeAware(false);
62             factory.setExpandEntityReferences(false);
63         } catch (final ParserConfigurationException e) {
64             throw new ExceptionInInitializerError(e);
65         }
66         factory.setNamespaceAware(true);
67         factory.setCoalescing(true);
68         factory.setIgnoringElementContentWhitespace(true);
69         factory.setIgnoringComments(true);
70         BUILDERFACTORY = factory;
71     }
72
73     @Override
74     public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
75             final MediaType mediaType) {
76         return true;
77     }
78
79     @Override
80     public NormalizedNodeContext readFrom(final Class<NormalizedNodeContext> type, final Type genericType,
81             final Annotation[] annotations, final MediaType mediaType,
82             final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException,
83             WebApplicationException {
84         try {
85             final InstanceIdentifierContext<?> path = getInstanceIdentifierContext();
86
87             if (entityStream.available() < 1) {
88                 // represent empty nopayload input
89                 return new NormalizedNodeContext(path, null);
90             }
91
92             final DocumentBuilder dBuilder;
93             try {
94                 dBuilder = BUILDERFACTORY.newDocumentBuilder();
95             } catch (final ParserConfigurationException e) {
96                 throw new RuntimeException("Failed to parse XML document", e);
97             }
98             final Document doc = dBuilder.parse(entityStream);
99
100             final NormalizedNode<?, ?> result = parse(path,doc);
101             return new NormalizedNodeContext(path,result);
102         } catch (final Exception e) {
103             LOG.debug("Error parsing xml input", e);
104
105             throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
106                     ErrorTag.MALFORMED_MESSAGE);
107         }
108     }
109
110     private static NormalizedNode<?,?> parse(final InstanceIdentifierContext<?> pathContext,final Document doc) {
111
112         final List<Element> elements = Collections.singletonList(doc.getDocumentElement());
113         final SchemaNode schemaNodeContext = pathContext.getSchemaNode();
114         DataSchemaNode schemaNode = null;
115         if (schemaNodeContext instanceof RpcDefinition) {
116             schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
117         } else if (schemaNodeContext instanceof DataSchemaNode) {
118             schemaNode = (DataSchemaNode) schemaNodeContext;
119         } else {
120             throw new IllegalStateException("Unknow SchemaNode");
121         }
122
123         final String docRootElm = doc.getDocumentElement().getLocalName();
124         final String schemaNodeName = pathContext.getSchemaNode().getQName().getLocalName();
125
126         if (!schemaNodeName.equalsIgnoreCase(docRootElm)) {
127             final Collection<DataSchemaNode> children = ((DataNodeContainer) schemaNode).getChildNodes();
128             for (final DataSchemaNode child : children) {
129                 if (child.getQName().getLocalName().equalsIgnoreCase(docRootElm)) {
130                     schemaNode = child;
131                     break;
132                 }
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         if(schemaNode instanceof ContainerSchemaNode) {
141             return parserFactory.getContainerNodeParser().parse(Collections.singletonList(doc.getDocumentElement()), (ContainerSchemaNode) schemaNode);
142         } else if(schemaNode instanceof ListSchemaNode) {
143             final ListSchemaNode casted = (ListSchemaNode) schemaNode;
144             return parserFactory.getMapEntryNodeParser().parse(elements, casted);
145         } // FIXME : add another DataSchemaNode extensions e.g. LeafSchemaNode
146         return null;
147     }
148 }
149