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.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.util.DataSchemaContextNode;
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.ContainerLike;
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.OperationDefinition;
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(final SchemaContextHandler schemaContextHandler,
69 final 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 final boolean isOperation;
95 if (schemaNodeContext instanceof OperationDefinition) {
96 schemaNode = ((OperationDefinition) schemaNodeContext).getInput();
98 } else if (schemaNodeContext instanceof DataSchemaNode) {
99 schemaNode = (DataSchemaNode) schemaNodeContext;
102 throw new IllegalStateException("Unknown SchemaNode " + schemaNodeContext);
105 final String docRootElm = doc.getDocumentElement().getLocalName();
106 final String docRootNamespace = doc.getDocumentElement().getNamespaceURI();
107 final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
109 if (isPost() && !isOperation) {
110 final Deque<Object> foundSchemaNodes = findPathToSchemaNodeByName(schemaNode, docRootElm, docRootNamespace);
111 if (foundSchemaNodes.isEmpty()) {
112 throw new IllegalStateException(String.format("Child \"%s\" was not found in parent schema node \"%s\"",
113 docRootElm, schemaNode.getQName()));
115 while (!foundSchemaNodes.isEmpty()) {
116 final Object child = foundSchemaNodes.pop();
117 if (child instanceof AugmentationSchemaNode) {
118 final AugmentationSchemaNode augmentSchemaNode = (AugmentationSchemaNode) child;
119 iiToDataList.add(DataSchemaContextNode.augmentationIdentifierFrom(augmentSchemaNode));
120 } else if (child instanceof DataSchemaNode) {
121 schemaNode = (DataSchemaNode) child;
122 iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(schemaNode.getQName()));
126 } else if (!isOperation) {
127 final QName scQName = schemaNode.getQName();
128 checkState(docRootElm.equals(scQName.getLocalName())
129 && docRootNamespace.equals(scQName.getNamespace().toASCIIString()),
130 "Not correct message root element \"%s\", should be \"%s\"", docRootElm, scQName);
133 NormalizedNode<?, ?> parsed;
134 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
135 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
137 if (schemaNode instanceof ContainerLike || schemaNode instanceof ListSchemaNode
138 || schemaNode instanceof LeafSchemaNode) {
139 final XmlParserStream xmlParser = XmlParserStream.create(writer, pathContext.getSchemaContext(),
141 xmlParser.traverse(new DOMSource(doc.getDocumentElement()));
142 parsed = resultHolder.getResult();
144 // When parsing an XML source with a list root node
145 // the new XML parser always returns a MapNode with one MapEntryNode inside.
146 // However, the old XML parser returned a MapEntryNode directly in this place.
147 // Therefore we now have to extract the MapEntryNode from the parsed MapNode.
148 if (parsed instanceof MapNode) {
149 final MapNode mapNode = (MapNode) parsed;
150 // extracting the MapEntryNode
151 parsed = mapNode.getValue().iterator().next();
154 if (schemaNode instanceof ListSchemaNode && isPost()) {
155 iiToDataList.add(parsed.getIdentifier());
158 LOG.warn("Unknown schema node extension {} was not parsed", schemaNode.getClass());
162 final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
163 pathContext.getInstanceIdentifier().getPathArguments(), iiToDataList));
165 final InstanceIdentifierContext<? extends SchemaNode> outIIContext = new InstanceIdentifierContext<>(
166 fullIIToData, pathContext.getSchemaNode(), pathContext.getMountPoint(), pathContext.getSchemaContext());
168 return new NormalizedNodeContext(outIIContext, parsed);
171 private static Deque<Object> findPathToSchemaNodeByName(final DataSchemaNode schemaNode, final String elementName,
172 final String namespace) {
173 final Deque<Object> result = new ArrayDeque<>();
174 final ArrayList<ChoiceSchemaNode> choiceSchemaNodes = new ArrayList<>();
175 for (final DataSchemaNode child : ((DataNodeContainer) schemaNode).getChildNodes()) {
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 AugmentationSchemaNode augment = findCorrespondingAugment(schemaNode, child);
186 if (augment != null) {
187 result.push(augment);
196 for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) {
197 for (final CaseSchemaNode 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 AugmentationSchemaNode augment = findCorrespondingAugment(schemaNode, choiceNode);
203 if (augment != null) {
204 resultFromRecursion.push(augment);
207 return resultFromRecursion;
214 private static AugmentationSchemaNode findCorrespondingAugment(final DataSchemaNode parent,
215 final DataSchemaNode child) {
216 if (parent instanceof AugmentationTarget && !(parent instanceof ChoiceSchemaNode)) {
217 for (final AugmentationSchemaNode augmentation
218 : ((AugmentationTarget) parent).getAvailableAugmentations()) {
219 final DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
220 if (childInAugmentation != null) {