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.nb.rfc8040.jersey.providers;
10 import static com.google.common.base.Preconditions.checkState;
12 import com.google.common.collect.Iterables;
13 import java.io.IOException;
14 import java.io.InputStream;
15 import java.net.URISyntaxException;
16 import java.util.ArrayDeque;
17 import java.util.ArrayList;
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.mdsal.dom.api.DOMMountPointService;
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.nb.rfc8040.MediaTypes;
33 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
34 import org.opendaylight.yangtools.util.xml.UntrustedXML;
35 import org.opendaylight.yangtools.yang.common.ErrorType;
36 import org.opendaylight.yangtools.yang.common.QName;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
38 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
41 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
42 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
43 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
44 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
45 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
47 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
50 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
51 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
55 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
56 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59 import org.w3c.dom.Document;
60 import org.xml.sax.SAXException;
63 @Consumes({ MediaTypes.APPLICATION_YANG_DATA_XML, MediaType.APPLICATION_XML, MediaType.TEXT_XML })
64 public class XmlNormalizedNodeBodyReader extends AbstractNormalizedNodeBodyReader {
65 private static final Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
67 public XmlNormalizedNodeBodyReader(final SchemaContextHandler schemaContextHandler,
68 final DOMMountPointService mountPointService) {
69 super(schemaContextHandler, mountPointService);
72 @SuppressWarnings("checkstyle:IllegalCatch")
74 protected NormalizedNodeContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
75 throws WebApplicationException {
77 final Document doc = UntrustedXML.newDocumentBuilder().parse(entityStream);
78 return parse(path,doc);
79 } catch (final RestconfDocumentedException e) {
81 } catch (final Exception e) {
82 LOG.debug("Error parsing xml input", e);
83 RestconfDocumentedException.throwIfYangError(e);
84 throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
85 ErrorTag.MALFORMED_MESSAGE, e);
89 private NormalizedNodeContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc)
90 throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
91 final SchemaNode schemaNodeContext = pathContext.getSchemaNode();
92 DataSchemaNode schemaNode;
93 final boolean isOperation;
94 if (schemaNodeContext instanceof OperationDefinition) {
95 schemaNode = ((OperationDefinition) schemaNodeContext).getInput();
97 } else if (schemaNodeContext instanceof DataSchemaNode) {
98 schemaNode = (DataSchemaNode) schemaNodeContext;
101 throw new IllegalStateException("Unknown SchemaNode " + schemaNodeContext);
104 final String docRootElm = doc.getDocumentElement().getLocalName();
105 final String docRootNamespace = doc.getDocumentElement().getNamespaceURI();
106 final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
108 if (isPost() && !isOperation) {
109 final Deque<Object> foundSchemaNodes = findPathToSchemaNodeByName(schemaNode, docRootElm, docRootNamespace);
110 if (foundSchemaNodes.isEmpty()) {
111 throw new IllegalStateException(String.format("Child \"%s\" was not found in parent schema node \"%s\"",
112 docRootElm, schemaNode.getQName()));
114 while (!foundSchemaNodes.isEmpty()) {
115 final Object child = foundSchemaNodes.pop();
116 if (child instanceof AugmentationSchemaNode) {
117 final AugmentationSchemaNode augmentSchemaNode = (AugmentationSchemaNode) child;
118 iiToDataList.add(DataSchemaContextNode.augmentationIdentifierFrom(augmentSchemaNode));
119 } else if (child instanceof DataSchemaNode) {
120 schemaNode = (DataSchemaNode) child;
121 iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(schemaNode.getQName()));
125 } else if (!isOperation) {
126 final QName scQName = schemaNode.getQName();
127 checkState(docRootElm.equals(scQName.getLocalName())
128 && docRootNamespace.equals(scQName.getNamespace().toString()),
129 "Not correct message root element \"%s\", should be \"%s\"", docRootElm, scQName);
132 NormalizedNode parsed;
133 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
134 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
136 if (schemaNode instanceof ContainerLike || schemaNode instanceof ListSchemaNode
137 || schemaNode instanceof LeafSchemaNode) {
138 final XmlParserStream xmlParser = XmlParserStream.create(writer, SchemaInferenceStack.ofInstantiatedPath(
139 pathContext.getSchemaContext(), schemaNode.getPath()).toInference());
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.body().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 for (final DataSchemaNode child : ((DataNodeContainer) schemaNode).getChildNodes()) {
175 if (child instanceof ChoiceSchemaNode) {
176 choiceSchemaNodes.add((ChoiceSchemaNode) child);
177 } else if (child.getQName().getLocalName().equalsIgnoreCase(elementName)
178 && child.getQName().getNamespace().toString().equalsIgnoreCase(namespace)) {
179 // add child to result
183 if (child.isAugmenting()) {
184 final AugmentationSchemaNode augment = findCorrespondingAugment(schemaNode, child);
185 if (augment != null) {
186 result.push(augment);
195 for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) {
196 for (final CaseSchemaNode caseNode : choiceNode.getCases()) {
197 final Deque<Object> resultFromRecursion = findPathToSchemaNodeByName(caseNode, elementName, namespace);
198 if (!resultFromRecursion.isEmpty()) {
199 resultFromRecursion.push(choiceNode);
200 if (choiceNode.isAugmenting()) {
201 final AugmentationSchemaNode augment = findCorrespondingAugment(schemaNode, choiceNode);
202 if (augment != null) {
203 resultFromRecursion.push(augment);
206 return resultFromRecursion;
213 private static AugmentationSchemaNode findCorrespondingAugment(final DataSchemaNode parent,
214 final DataSchemaNode child) {
215 if (parent instanceof AugmentationTarget && !(parent instanceof ChoiceSchemaNode)) {
216 for (AugmentationSchemaNode augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
217 if (augmentation.dataChildByName(child.getQName()) != null) {