2 * Copyright (c) 2016 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.restconf.jersey.providers;
10 import com.google.common.base.Preconditions;
11 import com.google.common.collect.Iterables;
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.net.URISyntaxException;
15 import java.util.ArrayDeque;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Deque;
19 import java.util.List;
20 import javax.ws.rs.Consumes;
21 import javax.ws.rs.WebApplicationException;
22 import javax.ws.rs.core.MediaType;
23 import javax.ws.rs.ext.Provider;
24 import javax.xml.parsers.ParserConfigurationException;
25 import javax.xml.stream.XMLStreamException;
26 import javax.xml.transform.dom.DOMSource;
27 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
28 import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext;
29 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
30 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
31 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
32 import org.opendaylight.restconf.Rfc8040;
33 import org.opendaylight.restconf.utils.RestconfConstants;
34 import org.opendaylight.yangtools.util.xml.UntrustedXML;
35 import org.opendaylight.yangtools.yang.common.QName;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
37 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
40 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
41 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
42 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
43 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
44 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
45 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
46 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
47 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
50 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
54 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57 import org.w3c.dom.Document;
58 import org.xml.sax.SAXException;
61 @Consumes({ Rfc8040.MediaTypes.DATA + RestconfConstants.XML, MediaType.APPLICATION_XML, MediaType.TEXT_XML })
62 public class XmlNormalizedNodeBodyReader extends AbstractNormalizedNodeBodyReader {
63 private static final Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
65 @SuppressWarnings("checkstyle:IllegalCatch")
67 protected NormalizedNodeContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
68 throws IOException, WebApplicationException {
70 final Document doc = UntrustedXML.newDocumentBuilder().parse(entityStream);
71 return parse(path,doc);
72 } catch (final RestconfDocumentedException e) {
74 } catch (final Exception e) {
75 LOG.debug("Error parsing xml input", e);
77 throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
78 ErrorTag.MALFORMED_MESSAGE, e);
82 private NormalizedNodeContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc)
83 throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
84 final SchemaNode schemaNodeContext = pathContext.getSchemaNode();
85 DataSchemaNode schemaNode;
86 boolean isRpc = false;
87 if (schemaNodeContext instanceof RpcDefinition) {
88 schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
90 } else if (schemaNodeContext instanceof DataSchemaNode) {
91 schemaNode = (DataSchemaNode) schemaNodeContext;
93 throw new IllegalStateException("Unknown SchemaNode");
96 final String docRootElm = doc.getDocumentElement().getLocalName();
97 final String docRootNamespace = doc.getDocumentElement().getNamespaceURI();
98 final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
100 if (isPost() && !isRpc) {
101 final Deque<Object> foundSchemaNodes = findPathToSchemaNodeByName(schemaNode, docRootElm, docRootNamespace);
102 if (foundSchemaNodes.isEmpty()) {
103 throw new IllegalStateException(String.format("Child \"%s\" was not found in parent schema node \"%s\"",
104 docRootElm, schemaNode.getQName()));
106 while (!foundSchemaNodes.isEmpty()) {
107 final Object child = foundSchemaNodes.pop();
108 if (child instanceof AugmentationSchema) {
109 final AugmentationSchema augmentSchemaNode = (AugmentationSchema) child;
110 iiToDataList.add(SchemaUtils.getNodeIdentifierForAugmentation(augmentSchemaNode));
111 } else if (child instanceof DataSchemaNode) {
112 schemaNode = (DataSchemaNode) child;
113 iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(schemaNode.getQName()));
118 final QName scQName = schemaNode.getQName();
119 Preconditions.checkState(
120 docRootElm.equals(scQName.getLocalName())
121 && docRootNamespace.equals(scQName.getNamespace().toASCIIString()),
122 String.format("Not correct message root element \"%s\", should be \"%s\"",
123 docRootElm, scQName));
126 NormalizedNode<?, ?> parsed;
127 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
128 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
130 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode
131 || schemaNode instanceof LeafSchemaNode) {
132 final XmlParserStream xmlParser = XmlParserStream.create(writer, pathContext.getSchemaContext(),
134 xmlParser.traverse(new DOMSource(doc.getDocumentElement()));
135 parsed = resultHolder.getResult();
137 // When parsing an XML source with a list root node
138 // the new XML parser always returns a MapNode with one MapEntryNode inside.
139 // However, the old XML parser returned a MapEntryNode directly in this place.
140 // Therefore we now have to extract the MapEntryNode from the parsed MapNode.
141 if (parsed instanceof MapNode) {
142 final MapNode mapNode = (MapNode) parsed;
143 // extracting the MapEntryNode
144 parsed = mapNode.getValue().iterator().next();
147 if (schemaNode instanceof ListSchemaNode && isPost()) {
148 iiToDataList.add(parsed.getIdentifier());
151 LOG.warn("Unknown schema node extension {} was not parsed", schemaNode.getClass());
155 final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
156 pathContext.getInstanceIdentifier().getPathArguments(), iiToDataList));
158 final InstanceIdentifierContext<? extends SchemaNode> outIIContext = new InstanceIdentifierContext<>(
159 fullIIToData, pathContext.getSchemaNode(), pathContext.getMountPoint(), pathContext.getSchemaContext());
161 return new NormalizedNodeContext(outIIContext, parsed);
164 private static Deque<Object> findPathToSchemaNodeByName(final DataSchemaNode schemaNode, final String elementName,
165 final String namespace) {
166 final Deque<Object> result = new ArrayDeque<>();
167 final ArrayList<ChoiceSchemaNode> choiceSchemaNodes = new ArrayList<>();
168 final Collection<DataSchemaNode> children = ((DataNodeContainer) schemaNode).getChildNodes();
169 for (final DataSchemaNode child : children) {
170 if (child instanceof ChoiceSchemaNode) {
171 choiceSchemaNodes.add((ChoiceSchemaNode) child);
172 } else if (child.getQName().getLocalName().equalsIgnoreCase(elementName)
173 && child.getQName().getNamespace().toString().equalsIgnoreCase(namespace)) {
174 // add child to result
178 if (child.isAugmenting()) {
179 final AugmentationSchema augment = findCorrespondingAugment(schemaNode, child);
180 if (augment != null) {
181 result.push(augment);
190 for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) {
191 for (final ChoiceCaseNode caseNode : choiceNode.getCases()) {
192 final Deque<Object> resultFromRecursion = findPathToSchemaNodeByName(caseNode, elementName, namespace);
193 if (!resultFromRecursion.isEmpty()) {
194 resultFromRecursion.push(choiceNode);
195 if (choiceNode.isAugmenting()) {
196 final AugmentationSchema augment = findCorrespondingAugment(schemaNode, choiceNode);
197 if (augment != null) {
198 resultFromRecursion.push(augment);
201 return resultFromRecursion;
208 private static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent,
209 final DataSchemaNode child) {
210 if (parent instanceof AugmentationTarget && !(parent instanceof ChoiceSchemaNode)) {
211 for (final AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
212 final DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
213 if (childInAugmentation != null) {