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 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.common.context.InstanceIdentifierContext;
28 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
29 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
30 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
31 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
32 import org.opendaylight.restconf.nb.rfc8040.Rfc8040;
33 import org.opendaylight.restconf.nb.rfc8040.handlers.DOMMountPointServiceHandler;
34 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
35 import org.opendaylight.restconf.nb.rfc8040.jersey.providers.spi.AbstractNormalizedNodeBodyReader;
36 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
37 import org.opendaylight.yangtools.util.xml.UntrustedXML;
38 import org.opendaylight.yangtools.yang.common.QName;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
40 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
43 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
44 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
45 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
46 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
47 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
49 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
53 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
57 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
60 import org.w3c.dom.Document;
61 import org.xml.sax.SAXException;
64 @Consumes({ Rfc8040.MediaTypes.DATA + RestconfConstants.XML, MediaType.APPLICATION_XML, MediaType.TEXT_XML })
65 public class XmlNormalizedNodeBodyReader extends AbstractNormalizedNodeBodyReader {
66 private static final Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
68 public XmlNormalizedNodeBodyReader(SchemaContextHandler schemaContextHandler,
69 DOMMountPointServiceHandler mountPointServiceHandler) {
70 super(schemaContextHandler, mountPointServiceHandler);
73 @SuppressWarnings("checkstyle:IllegalCatch")
75 protected NormalizedNodeContext readBody(final InstanceIdentifierContext<?> path, final InputStream entityStream)
76 throws WebApplicationException {
78 final Document doc = UntrustedXML.newDocumentBuilder().parse(entityStream);
79 return parse(path,doc);
80 } catch (final RestconfDocumentedException e) {
82 } catch (final Exception e) {
83 LOG.debug("Error parsing xml input", e);
85 throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
86 ErrorTag.MALFORMED_MESSAGE, e);
90 private NormalizedNodeContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc)
91 throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
92 final SchemaNode schemaNodeContext = pathContext.getSchemaNode();
93 DataSchemaNode schemaNode;
94 boolean isRpc = false;
95 if (schemaNodeContext instanceof RpcDefinition) {
96 schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
98 } else if (schemaNodeContext instanceof DataSchemaNode) {
99 schemaNode = (DataSchemaNode) schemaNodeContext;
101 throw new IllegalStateException("Unknown SchemaNode");
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() && !isRpc) {
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(SchemaUtils.getNodeIdentifierForAugmentation(augmentSchemaNode));
119 } else if (child instanceof DataSchemaNode) {
120 schemaNode = (DataSchemaNode) child;
121 iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(schemaNode.getQName()));
126 final QName scQName = schemaNode.getQName();
127 Preconditions.checkState(
128 docRootElm.equals(scQName.getLocalName())
129 && docRootNamespace.equals(scQName.getNamespace().toASCIIString()),
130 String.format("Not correct message root element \"%s\", should be \"%s\"",
131 docRootElm, scQName));
134 NormalizedNode<?, ?> parsed;
135 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
136 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
138 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode
139 || schemaNode instanceof LeafSchemaNode) {
140 final XmlParserStream xmlParser = XmlParserStream.create(writer, pathContext.getSchemaContext(),
142 xmlParser.traverse(new DOMSource(doc.getDocumentElement()));
143 parsed = resultHolder.getResult();
145 // When parsing an XML source with a list root node
146 // the new XML parser always returns a MapNode with one MapEntryNode inside.
147 // However, the old XML parser returned a MapEntryNode directly in this place.
148 // Therefore we now have to extract the MapEntryNode from the parsed MapNode.
149 if (parsed instanceof MapNode) {
150 final MapNode mapNode = (MapNode) parsed;
151 // extracting the MapEntryNode
152 parsed = mapNode.getValue().iterator().next();
155 if (schemaNode instanceof ListSchemaNode && isPost()) {
156 iiToDataList.add(parsed.getIdentifier());
159 LOG.warn("Unknown schema node extension {} was not parsed", schemaNode.getClass());
163 final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
164 pathContext.getInstanceIdentifier().getPathArguments(), iiToDataList));
166 final InstanceIdentifierContext<? extends SchemaNode> outIIContext = new InstanceIdentifierContext<>(
167 fullIIToData, pathContext.getSchemaNode(), pathContext.getMountPoint(), pathContext.getSchemaContext());
169 return new NormalizedNodeContext(outIIContext, parsed);
172 private static Deque<Object> findPathToSchemaNodeByName(final DataSchemaNode schemaNode, final String elementName,
173 final String namespace) {
174 final Deque<Object> result = new ArrayDeque<>();
175 final ArrayList<ChoiceSchemaNode> choiceSchemaNodes = new ArrayList<>();
176 final Collection<DataSchemaNode> children = ((DataNodeContainer) schemaNode).getChildNodes();
177 for (final DataSchemaNode child : children) {
178 if (child instanceof ChoiceSchemaNode) {
179 choiceSchemaNodes.add((ChoiceSchemaNode) child);
180 } else if (child.getQName().getLocalName().equalsIgnoreCase(elementName)
181 && child.getQName().getNamespace().toString().equalsIgnoreCase(namespace)) {
182 // add child to result
186 if (child.isAugmenting()) {
187 final AugmentationSchemaNode augment = findCorrespondingAugment(schemaNode, child);
188 if (augment != null) {
189 result.push(augment);
198 for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) {
199 for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
200 final Deque<Object> resultFromRecursion = findPathToSchemaNodeByName(caseNode, elementName, namespace);
201 if (!resultFromRecursion.isEmpty()) {
202 resultFromRecursion.push(choiceNode);
203 if (choiceNode.isAugmenting()) {
204 final AugmentationSchemaNode augment = findCorrespondingAugment(schemaNode, choiceNode);
205 if (augment != null) {
206 resultFromRecursion.push(augment);
209 return resultFromRecursion;
216 private static AugmentationSchemaNode findCorrespondingAugment(final DataSchemaNode parent,
217 final DataSchemaNode child) {
218 if (parent instanceof AugmentationTarget && !(parent instanceof ChoiceSchemaNode)) {
219 for (final AugmentationSchemaNode augmentation
220 : ((AugmentationTarget) parent).getAvailableAugmentations()) {
221 final DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
222 if (childInAugmentation != null) {