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.restconf.Rfc8040;
28 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
29 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
30 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
31 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
32 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
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 * Reader of XML to NormalizedNode.
63 * @deprecated move to splitted module restconf-nb-rfc8040
67 @Consumes({ Rfc8040.MediaTypes.DATA + RestconfConstants.XML, MediaType.APPLICATION_XML, MediaType.TEXT_XML })
68 public class XmlNormalizedNodeBodyReader extends AbstractNormalizedNodeBodyReader {
69 private static final Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
71 @SuppressWarnings("checkstyle:IllegalCatch")
73 protected NormalizedNodeContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
74 throws IOException, WebApplicationException {
76 final Document doc = UntrustedXML.newDocumentBuilder().parse(entityStream);
77 return parse(path,doc);
78 } catch (final RestconfDocumentedException e) {
80 } catch (final Exception e) {
81 LOG.debug("Error parsing xml input", e);
83 throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
84 ErrorTag.MALFORMED_MESSAGE, e);
88 private NormalizedNodeContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc)
89 throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
90 final SchemaNode schemaNodeContext = pathContext.getSchemaNode();
91 DataSchemaNode schemaNode;
92 boolean isRpc = false;
93 if (schemaNodeContext instanceof RpcDefinition) {
94 schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
96 } else if (schemaNodeContext instanceof DataSchemaNode) {
97 schemaNode = (DataSchemaNode) schemaNodeContext;
99 throw new IllegalStateException("Unknown SchemaNode");
102 final String docRootElm = doc.getDocumentElement().getLocalName();
103 final String docRootNamespace = doc.getDocumentElement().getNamespaceURI();
104 final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
106 if (isPost() && !isRpc) {
107 final Deque<Object> foundSchemaNodes = findPathToSchemaNodeByName(schemaNode, docRootElm, docRootNamespace);
108 if (foundSchemaNodes.isEmpty()) {
109 throw new IllegalStateException(String.format("Child \"%s\" was not found in parent schema node \"%s\"",
110 docRootElm, schemaNode.getQName()));
112 while (!foundSchemaNodes.isEmpty()) {
113 final Object child = foundSchemaNodes.pop();
114 if (child instanceof AugmentationSchema) {
115 final AugmentationSchema augmentSchemaNode = (AugmentationSchema) child;
116 iiToDataList.add(SchemaUtils.getNodeIdentifierForAugmentation(augmentSchemaNode));
117 } else if (child instanceof DataSchemaNode) {
118 schemaNode = (DataSchemaNode) child;
119 iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(schemaNode.getQName()));
124 final QName scQName = schemaNode.getQName();
125 Preconditions.checkState(
126 docRootElm.equals(scQName.getLocalName())
127 && docRootNamespace.equals(scQName.getNamespace().toASCIIString()),
128 String.format("Not correct message root element \"%s\", should be \"%s\"",
129 docRootElm, scQName));
132 NormalizedNode<?, ?> parsed;
133 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
134 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
136 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode
137 || schemaNode instanceof LeafSchemaNode) {
138 final XmlParserStream xmlParser = XmlParserStream.create(writer, pathContext.getSchemaContext(),
140 xmlParser.traverse(new DOMSource(doc.getDocumentElement()));
141 parsed = resultHolder.getResult();
143 // When parsing an XML source with a list root node
144 // the new XML parser always returns a MapNode with one MapEntryNode inside.
145 // However, the old XML parser returned a MapEntryNode directly in this place.
146 // Therefore we now have to extract the MapEntryNode from the parsed MapNode.
147 if (parsed instanceof MapNode) {
148 final MapNode mapNode = (MapNode) parsed;
149 // extracting the MapEntryNode
150 parsed = mapNode.getValue().iterator().next();
153 if (schemaNode instanceof ListSchemaNode && isPost()) {
154 iiToDataList.add(parsed.getIdentifier());
157 LOG.warn("Unknown schema node extension {} was not parsed", schemaNode.getClass());
161 final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
162 pathContext.getInstanceIdentifier().getPathArguments(), iiToDataList));
164 final InstanceIdentifierContext<? extends SchemaNode> outIIContext = new InstanceIdentifierContext<>(
165 fullIIToData, pathContext.getSchemaNode(), pathContext.getMountPoint(), pathContext.getSchemaContext());
167 return new NormalizedNodeContext(outIIContext, parsed);
170 private static Deque<Object> findPathToSchemaNodeByName(final DataSchemaNode schemaNode, final String elementName,
171 final String namespace) {
172 final Deque<Object> result = new ArrayDeque<>();
173 final ArrayList<ChoiceSchemaNode> choiceSchemaNodes = new ArrayList<>();
174 final Collection<DataSchemaNode> children = ((DataNodeContainer) schemaNode).getChildNodes();
175 for (final DataSchemaNode child : children) {
176 if (child instanceof ChoiceSchemaNode) {
177 choiceSchemaNodes.add((ChoiceSchemaNode) child);
178 } else if (child.getQName().getLocalName().equalsIgnoreCase(elementName)
179 && child.getQName().getNamespace().toString().equalsIgnoreCase(namespace)) {
180 // add child to result
184 if (child.isAugmenting()) {
185 final AugmentationSchema augment = findCorrespondingAugment(schemaNode, child);
186 if (augment != null) {
187 result.push(augment);
196 for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) {
197 for (final ChoiceCaseNode caseNode : choiceNode.getCases()) {
198 final Deque<Object> resultFromRecursion = findPathToSchemaNodeByName(caseNode, elementName, namespace);
199 if (!resultFromRecursion.isEmpty()) {
200 resultFromRecursion.push(choiceNode);
201 if (choiceNode.isAugmenting()) {
202 final AugmentationSchema augment = findCorrespondingAugment(schemaNode, choiceNode);
203 if (augment != null) {
204 resultFromRecursion.push(augment);
207 return resultFromRecursion;
214 private static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent,
215 final DataSchemaNode child) {
216 if (parent instanceof AugmentationTarget && !(parent instanceof ChoiceSchemaNode)) {
217 for (final AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
218 final DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
219 if (childInAugmentation != null) {