Change fields in ShardStats to non-volatile
[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             final DocumentBuilder dBuilder;
89             try {
90                 dBuilder = BUILDERFACTORY.newDocumentBuilder();
91             } catch (final ParserConfigurationException e) {
92                 throw new RuntimeException("Failed to parse XML document", e);
93             }
94             final Document doc = dBuilder.parse(entityStream);
95
96             final NormalizedNode<?, ?> result = parse(path.get(),doc);
97             return new NormalizedNodeContext(path.get(),result);
98         } catch (final Exception e) {
99             LOG.debug("Error parsing json input", e);
100
101             throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
102                     ErrorTag.MALFORMED_MESSAGE);
103         }
104     }
105
106     private static NormalizedNode<?,?> parse(final InstanceIdentifierContext<?> pathContext,final Document doc) {
107
108         final List<Element> elements = Collections.singletonList(doc.getDocumentElement());
109         final SchemaNode schemaNodeContext = pathContext.getSchemaNode();
110         DataSchemaNode schemaNode = null;
111         if (schemaNodeContext instanceof RpcDefinition) {
112             schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
113         } else if (schemaNodeContext instanceof DataSchemaNode) {
114             schemaNode = (DataSchemaNode) schemaNodeContext;
115         } else {
116             throw new IllegalStateException("Unknow SchemaNode");
117         }
118
119         final String docRootElm = doc.getDocumentElement().getLocalName();
120         final String schemaNodeName = pathContext.getSchemaNode().getQName().getLocalName();
121
122         // TODO : do we want to really follow netconf-restconf specification ?
123         if (!schemaNodeName.equalsIgnoreCase(docRootElm)) {
124             final Collection<DataSchemaNode> children = ((DataNodeContainer) schemaNode).getChildNodes();
125             for (final DataSchemaNode child : children) {
126                 if (child.getQName().getLocalName().equalsIgnoreCase(docRootElm)) {
127                     schemaNode = child;
128                     break;
129                 }
130             }
131         }
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(schemaNode instanceof ContainerSchemaNode) {
138             return parserFactory.getContainerNodeParser().parse(Collections.singletonList(doc.getDocumentElement()), (ContainerSchemaNode) schemaNode);
139         } else if(schemaNode instanceof ListSchemaNode) {
140             final ListSchemaNode casted = (ListSchemaNode) schemaNode;
141             return parserFactory.getMapEntryNodeParser().parse(elements, casted);
142         }
143         return null;
144     }
145 }
146