Cleanup: Remove passing around of DataPersistenceProvider
[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.base.Optional;
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.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.ContainerSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
39 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
42 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45 import org.w3c.dom.Document;
46 import org.w3c.dom.Element;
47
48 @Provider
49 @Consumes({ Draft02.MediaTypes.DATA + RestconfService.XML, Draft02.MediaTypes.OPERATION + RestconfService.XML,
50     MediaType.APPLICATION_XML, MediaType.TEXT_XML })
51 public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsProvider implements MessageBodyReader<NormalizedNodeContext> {
52
53     private final static Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
54     private static final DocumentBuilderFactory BUILDERFACTORY;
55
56     static {
57         final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
58         try {
59             factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
60             factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
61             factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
62             factory.setXIncludeAware(false);
63             factory.setExpandEntityReferences(false);
64         } catch (final ParserConfigurationException e) {
65             throw new ExceptionInInitializerError(e);
66         }
67         factory.setNamespaceAware(true);
68         factory.setCoalescing(true);
69         factory.setIgnoringElementContentWhitespace(true);
70         factory.setIgnoringComments(true);
71         BUILDERFACTORY = factory;
72     }
73
74     @Override
75     public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
76             final MediaType mediaType) {
77         return true;
78     }
79
80     @Override
81     public NormalizedNodeContext readFrom(final Class<NormalizedNodeContext> type, final Type genericType,
82             final Annotation[] annotations, final MediaType mediaType,
83             final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException,
84             WebApplicationException {
85         try {
86             final Optional<InstanceIdentifierContext> path = getIdentifierWithSchema();
87
88             if (entityStream.available() < 1) {
89                 // represent empty nopayload input
90                 return new NormalizedNodeContext(path.get(), null);
91             }
92
93             final DocumentBuilder dBuilder;
94             try {
95                 dBuilder = BUILDERFACTORY.newDocumentBuilder();
96             } catch (final ParserConfigurationException e) {
97                 throw new RuntimeException("Failed to parse XML document", e);
98             }
99             final Document doc = dBuilder.parse(entityStream);
100
101             final NormalizedNode<?, ?> result = parse(path.get(),doc);
102             return new NormalizedNodeContext(path.get(),result);
103         } catch (final Exception e) {
104             LOG.debug("Error parsing xml input", e);
105
106             throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
107                     ErrorTag.MALFORMED_MESSAGE);
108         }
109     }
110
111     private static NormalizedNode<?,?> parse(final InstanceIdentifierContext<?> pathContext,final Document doc) {
112
113         final List<Element> elements = Collections.singletonList(doc.getDocumentElement());
114         final SchemaNode schemaNodeContext = pathContext.getSchemaNode();
115         DataSchemaNode schemaNode = null;
116         if (schemaNodeContext instanceof RpcDefinition) {
117             schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
118         } else if (schemaNodeContext instanceof DataSchemaNode) {
119             schemaNode = (DataSchemaNode) schemaNodeContext;
120         } else {
121             throw new IllegalStateException("Unknow SchemaNode");
122         }
123
124         final String docRootElm = doc.getDocumentElement().getLocalName();
125         final String schemaNodeName = pathContext.getSchemaNode().getQName().getLocalName();
126
127         if (!schemaNodeName.equalsIgnoreCase(docRootElm)) {
128             final Collection<DataSchemaNode> children = ((DataNodeContainer) schemaNode).getChildNodes();
129             for (final DataSchemaNode child : children) {
130                 if (child.getQName().getLocalName().equalsIgnoreCase(docRootElm)) {
131                     schemaNode = child;
132                     break;
133                 }
134             }
135         }
136
137         // FIXME the factory instance should be cached if the schema context is the same
138         final DomToNormalizedNodeParserFactory parserFactory =
139                 DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, pathContext.getSchemaContext());
140
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         } // FIXME : add another DataSchemaNode extensions e.g. LeafSchemaNode
147         return null;
148     }
149 }
150

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.