2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.netconf.sal.rest.impl;
10 import com.google.common.collect.Iterables;
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.ArrayDeque;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.Deque;
20 import java.util.List;
21 import javax.ws.rs.Consumes;
22 import javax.ws.rs.WebApplicationException;
23 import javax.ws.rs.core.MediaType;
24 import javax.ws.rs.core.MultivaluedMap;
25 import javax.ws.rs.ext.MessageBodyReader;
26 import javax.ws.rs.ext.Provider;
27 import javax.xml.parsers.DocumentBuilder;
28 import javax.xml.parsers.DocumentBuilderFactory;
29 import javax.xml.parsers.ParserConfigurationException;
30 import org.opendaylight.netconf.sal.rest.api.Draft02;
31 import org.opendaylight.netconf.sal.rest.api.RestconfService;
32 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
33 import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext;
34 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
35 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
36 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
37 import org.opendaylight.restconf.utils.RestconfConstants;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
39 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
40 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
41 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
42 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
43 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
44 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
45 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
46 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
49 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
52 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.w3c.dom.Document;
56 import org.w3c.dom.Element;
57 import org.xml.sax.SAXException;
60 @Consumes({ Draft02.MediaTypes.DATA + RestconfService.XML, Draft02.MediaTypes.OPERATION + RestconfService.XML,
61 MediaType.APPLICATION_XML, MediaType.TEXT_XML })
62 public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsProvider implements MessageBodyReader<NormalizedNodeContext> {
64 private final static Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
65 private static final DocumentBuilderFactory BUILDERFACTORY;
68 final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
70 factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
71 factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
72 factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
73 factory.setXIncludeAware(false);
74 factory.setExpandEntityReferences(false);
75 } catch (final ParserConfigurationException e) {
76 throw new ExceptionInInitializerError(e);
78 factory.setNamespaceAware(true);
79 factory.setCoalescing(true);
80 factory.setIgnoringElementContentWhitespace(true);
81 factory.setIgnoringComments(true);
82 BUILDERFACTORY = factory;
86 public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
87 final MediaType mediaType) {
92 public NormalizedNodeContext readFrom(final Class<NormalizedNodeContext> type, final Type genericType,
93 final Annotation[] annotations, final MediaType mediaType,
94 final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException,
95 WebApplicationException {
97 if (getUriInfo().getAbsolutePath().getPath().contains(RestconfConstants.DRAFT_PATTERN)) {
98 final org.opendaylight.restconf.jersey.providers.XmlNormalizedNodeBodyReader xmlReaderNewRest =
99 new org.opendaylight.restconf.jersey.providers.XmlNormalizedNodeBodyReader();
100 xmlReaderNewRest.injectParams(getUriInfo(), getRequest());
101 return xmlReaderNewRest.readFrom(type, genericType, annotations, mediaType, httpHeaders, entityStream);
103 return readFrom(entityStream);
105 } catch (final RestconfDocumentedException e){
107 } catch (final Exception e) {
108 LOG.debug("Error parsing xml input", e);
110 throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
111 ErrorTag.MALFORMED_MESSAGE);
115 private NormalizedNodeContext readFrom(final InputStream entityStream) throws IOException, SAXException {
116 final InstanceIdentifierContext<?> path = getInstanceIdentifierContext();
118 if (entityStream.available() < 1) {
119 // represent empty nopayload input
120 return new NormalizedNodeContext(path, null);
123 final DocumentBuilder dBuilder;
125 dBuilder = BUILDERFACTORY.newDocumentBuilder();
126 } catch (final ParserConfigurationException e) {
127 throw new RuntimeException("Failed to parse XML document", e);
129 final Document doc = dBuilder.parse(entityStream);
131 return parse(path,doc);
134 private NormalizedNodeContext parse(final InstanceIdentifierContext<?> pathContext,final Document doc) {
136 final List<Element> elements = Collections.singletonList(doc.getDocumentElement());
137 final SchemaNode schemaNodeContext = pathContext.getSchemaNode();
138 DataSchemaNode schemaNode;
139 boolean isRpc = false;
140 if (schemaNodeContext instanceof RpcDefinition) {
141 schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
143 } else if (schemaNodeContext instanceof DataSchemaNode) {
144 schemaNode = (DataSchemaNode) schemaNodeContext;
146 throw new IllegalStateException("Unknown SchemaNode");
149 final String docRootElm = doc.getDocumentElement().getLocalName();
150 final String docRootNamespace = doc.getDocumentElement().getNamespaceURI();
151 final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
152 InstanceIdentifierContext<? extends SchemaNode> outIIContext;
155 // FIXME the factory instance should be cached if the schema context is the same
156 final DomToNormalizedNodeParserFactory parserFactory =
157 DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, pathContext.getSchemaContext());
159 if (isPost() && !isRpc) {
160 final Deque<Object> foundSchemaNodes = findPathToSchemaNodeByName(schemaNode, docRootElm, docRootNamespace);
161 if (foundSchemaNodes.isEmpty()) {
162 throw new IllegalStateException(String.format("Child \"%s\" was not found in parent schema node \"%s\"",
163 docRootElm, schemaNode.getQName()));
165 while (!foundSchemaNodes.isEmpty()) {
166 final Object child = foundSchemaNodes.pop();
167 if (child instanceof AugmentationSchema) {
168 final AugmentationSchema augmentSchemaNode = (AugmentationSchema) child;
169 iiToDataList.add(SchemaUtils.getNodeIdentifierForAugmentation(augmentSchemaNode));
170 } else if (child instanceof DataSchemaNode) {
171 schemaNode = (DataSchemaNode) child;
172 iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(schemaNode.getQName()));
177 NormalizedNode<?, ?> parsed = null;
179 if (schemaNode instanceof ContainerSchemaNode) {
180 parsed = parserFactory.getContainerNodeParser().parse(Collections.singletonList(doc.getDocumentElement()), (ContainerSchemaNode) schemaNode);
181 } else if(schemaNode instanceof ListSchemaNode) {
182 final ListSchemaNode casted = (ListSchemaNode) schemaNode;
183 parsed = parserFactory.getMapEntryNodeParser().parse(elements, casted);
185 iiToDataList.add(parsed.getIdentifier());
188 // FIXME : add another DataSchemaNode extensions e.g. LeafSchemaNode
190 final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
191 pathContext.getInstanceIdentifier().getPathArguments(), iiToDataList));
193 outIIContext = new InstanceIdentifierContext<>(fullIIToData, pathContext.getSchemaNode(), pathContext.getMountPoint(),
194 pathContext.getSchemaContext());
196 return new NormalizedNodeContext(outIIContext, parsed);
199 private static Deque<Object> findPathToSchemaNodeByName(final DataSchemaNode schemaNode, final String elementName,
200 final String namespace) {
201 final Deque<Object> result = new ArrayDeque<>();
202 final ArrayList<ChoiceSchemaNode> choiceSchemaNodes = new ArrayList<>();
203 final Collection<DataSchemaNode> children = ((DataNodeContainer) schemaNode).getChildNodes();
204 for (final DataSchemaNode child : children) {
205 if (child instanceof ChoiceSchemaNode) {
206 choiceSchemaNodes.add((ChoiceSchemaNode) child);
207 } else if (child.getQName().getLocalName().equalsIgnoreCase(elementName)
208 && child.getQName().getNamespace().toString().equalsIgnoreCase(namespace)) {
209 // add child to result
213 if (child.isAugmenting()) {
214 final AugmentationSchema augment = findCorrespondingAugment(schemaNode, child);
215 if (augment != null) {
216 result.push(augment);
225 for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) {
226 for (final ChoiceCaseNode caseNode : choiceNode.getCases()) {
227 final Deque<Object> resultFromRecursion = findPathToSchemaNodeByName(caseNode, elementName, namespace);
228 if (!resultFromRecursion.isEmpty()) {
229 resultFromRecursion.push(choiceNode);
230 if (choiceNode.isAugmenting()) {
231 final AugmentationSchema augment = findCorrespondingAugment(schemaNode, choiceNode);
232 if (augment != null) {
233 resultFromRecursion.push(augment);
236 return resultFromRecursion;
243 private static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent, final DataSchemaNode child) {
244 if ((parent instanceof AugmentationTarget) && !(parent instanceof ChoiceSchemaNode)) {
245 for (final AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
246 final DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
247 if (childInAugmentation != null) {