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.Draft15;
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;
59 @Consumes({ Draft02.MediaTypes.DATA + RestconfService.XML, Draft02.MediaTypes.OPERATION + RestconfService.XML,
60 Draft15.MediaTypes.DATA, MediaType.APPLICATION_XML, MediaType.TEXT_XML })
61 public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsProvider implements MessageBodyReader<NormalizedNodeContext> {
63 private final static Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
64 private static final DocumentBuilderFactory BUILDERFACTORY;
67 final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
69 factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
70 factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
71 factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
72 factory.setXIncludeAware(false);
73 factory.setExpandEntityReferences(false);
74 } catch (final ParserConfigurationException e) {
75 throw new ExceptionInInitializerError(e);
77 factory.setNamespaceAware(true);
78 factory.setCoalescing(true);
79 factory.setIgnoringElementContentWhitespace(true);
80 factory.setIgnoringComments(true);
81 BUILDERFACTORY = factory;
85 public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
86 final MediaType mediaType) {
91 public NormalizedNodeContext readFrom(final Class<NormalizedNodeContext> type, final Type genericType,
92 final Annotation[] annotations, final MediaType mediaType,
93 final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException,
94 WebApplicationException {
96 final InstanceIdentifierContext<?> path = getInstanceIdentifierContext();
98 if (entityStream.available() < 1) {
99 // represent empty nopayload input
100 return new NormalizedNodeContext(path, null);
103 final DocumentBuilder dBuilder;
105 dBuilder = BUILDERFACTORY.newDocumentBuilder();
106 } catch (final ParserConfigurationException e) {
107 throw new RuntimeException("Failed to parse XML document", e);
109 final Document doc = dBuilder.parse(entityStream);
111 return parse(path,doc);
112 } catch (final RestconfDocumentedException e){
114 } catch (final Exception e) {
115 LOG.debug("Error parsing xml input", e);
117 throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
118 ErrorTag.MALFORMED_MESSAGE);
122 private NormalizedNodeContext parse(final InstanceIdentifierContext<?> pathContext,final Document doc) {
124 final List<Element> elements = Collections.singletonList(doc.getDocumentElement());
125 final SchemaNode schemaNodeContext = pathContext.getSchemaNode();
126 DataSchemaNode schemaNode;
127 boolean isRpc = false;
128 if (schemaNodeContext instanceof RpcDefinition) {
129 schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
131 } else if (schemaNodeContext instanceof DataSchemaNode) {
132 schemaNode = (DataSchemaNode) schemaNodeContext;
134 throw new IllegalStateException("Unknow SchemaNode");
137 final String docRootElm = doc.getDocumentElement().getLocalName();
138 final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
139 InstanceIdentifierContext<? extends SchemaNode> outIIContext;
142 // FIXME the factory instance should be cached if the schema context is the same
143 final DomToNormalizedNodeParserFactory parserFactory =
144 DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, pathContext.getSchemaContext());
146 if (isPost() && !isRpc) {
147 final Deque<Object> foundSchemaNodes = findPathToSchemaNodeByName(schemaNode, docRootElm);
148 if (foundSchemaNodes.isEmpty()) {
149 throw new IllegalStateException(String.format("Child \"%s\" was not found in parent schema node \"%s\"",
150 docRootElm, schemaNode.getQName()));
152 while (!foundSchemaNodes.isEmpty()) {
153 final Object child = foundSchemaNodes.pop();
154 if (child instanceof AugmentationSchema) {
155 final AugmentationSchema augmentSchemaNode = (AugmentationSchema) child;
156 iiToDataList.add(SchemaUtils.getNodeIdentifierForAugmentation(augmentSchemaNode));
157 } else if (child instanceof DataSchemaNode) {
158 schemaNode = (DataSchemaNode) child;
159 iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(schemaNode.getQName()));
164 NormalizedNode<?, ?> parsed = null;
166 if(schemaNode instanceof ContainerSchemaNode) {
167 parsed = parserFactory.getContainerNodeParser().parse(Collections.singletonList(doc.getDocumentElement()), (ContainerSchemaNode) schemaNode);
168 } else if(schemaNode instanceof ListSchemaNode) {
169 final ListSchemaNode casted = (ListSchemaNode) schemaNode;
170 parsed = parserFactory.getMapEntryNodeParser().parse(elements, casted);
172 iiToDataList.add(parsed.getIdentifier());
175 // FIXME : add another DataSchemaNode extensions e.g. LeafSchemaNode
177 final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
178 pathContext.getInstanceIdentifier().getPathArguments(), iiToDataList));
180 outIIContext = new InstanceIdentifierContext<>(fullIIToData, pathContext.getSchemaNode(), pathContext.getMountPoint(),
181 pathContext.getSchemaContext());
183 return new NormalizedNodeContext(outIIContext, parsed);
186 private static Deque<Object> findPathToSchemaNodeByName(final DataSchemaNode schemaNode, final String elementName) {
187 final Deque<Object> result = new ArrayDeque<>();
188 final ArrayList<ChoiceSchemaNode> choiceSchemaNodes = new ArrayList<>();
189 final Collection<DataSchemaNode> children = ((DataNodeContainer) schemaNode).getChildNodes();
190 for (final DataSchemaNode child : children) {
191 if (child instanceof ChoiceSchemaNode) {
192 choiceSchemaNodes.add((ChoiceSchemaNode) child);
193 } else if (child.getQName().getLocalName().equalsIgnoreCase(elementName)) {
195 if (child.isAugmenting()) {
196 final AugmentationSchema augment = findCorrespondingAugment(schemaNode, child);
197 if (augment != null) {
198 result.push(augment);
205 for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) {
206 for (final ChoiceCaseNode caseNode : choiceNode.getCases()) {
207 final Deque<Object> resultFromRecursion = findPathToSchemaNodeByName(caseNode, elementName);
208 if (!resultFromRecursion.isEmpty()) {
209 resultFromRecursion.push(choiceNode);
210 if (choiceNode.isAugmenting()) {
211 final AugmentationSchema augment = findCorrespondingAugment(schemaNode, choiceNode);
212 if (augment != null) {
213 resultFromRecursion.push(augment);
216 return resultFromRecursion;
223 private static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent, final DataSchemaNode child) {
224 if ((parent instanceof AugmentationTarget) && !(parent instanceof ChoiceSchemaNode)) {
225 for (final AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
226 final DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
227 if (childInAugmentation != null) {