2 * Copyright (c) 2014 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.netconf.sal.rest.impl;
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.lang.annotation.Annotation;
15 import java.lang.reflect.Type;
16 import java.util.ArrayDeque;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.Collections;
20 import java.util.Deque;
21 import java.util.List;
22 import javax.ws.rs.Consumes;
23 import javax.ws.rs.WebApplicationException;
24 import javax.ws.rs.core.MediaType;
25 import javax.ws.rs.core.MultivaluedMap;
26 import javax.ws.rs.ext.MessageBodyReader;
27 import javax.ws.rs.ext.Provider;
28 import org.opendaylight.netconf.sal.rest.api.Draft02;
29 import org.opendaylight.netconf.sal.rest.api.RestconfService;
30 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
31 import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext;
32 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
33 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
34 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
35 import org.opendaylight.restconf.utils.RestconfConstants;
36 import org.opendaylight.yangtools.util.xml.UntrustedXML;
37 import org.opendaylight.yangtools.yang.common.QName;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
39 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
40 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
41 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
42 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
43 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
44 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
45 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
46 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
49 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
53 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56 import org.w3c.dom.Document;
57 import org.w3c.dom.Element;
58 import org.xml.sax.SAXException;
61 @Consumes({ Draft02.MediaTypes.DATA + RestconfService.XML, Draft02.MediaTypes.OPERATION + RestconfService.XML,
62 MediaType.APPLICATION_XML, MediaType.TEXT_XML })
63 public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsProvider
64 implements MessageBodyReader<NormalizedNodeContext> {
66 private static final Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
69 public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
70 final MediaType mediaType) {
74 @SuppressWarnings("checkstyle:IllegalCatch")
76 public NormalizedNodeContext readFrom(final Class<NormalizedNodeContext> type, final Type genericType,
77 final Annotation[] annotations, final MediaType mediaType,
78 final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException,
79 WebApplicationException {
81 if (getUriInfo().getAbsolutePath().getPath().contains(RestconfConstants.DRAFT_PATTERN)) {
82 final org.opendaylight.restconf.jersey.providers.XmlNormalizedNodeBodyReader xmlReaderNewRest =
83 new org.opendaylight.restconf.jersey.providers.XmlNormalizedNodeBodyReader();
84 xmlReaderNewRest.injectParams(getUriInfo(), getRequest());
85 return xmlReaderNewRest.readFrom(type, genericType, annotations, mediaType, httpHeaders, entityStream);
87 return readFrom(entityStream);
89 } catch (final RestconfDocumentedException e) {
91 } catch (final Exception e) {
92 LOG.debug("Error parsing xml input", e);
94 throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
95 ErrorTag.MALFORMED_MESSAGE);
99 private NormalizedNodeContext readFrom(final InputStream entityStream) throws IOException, SAXException {
100 final InstanceIdentifierContext<?> path = getInstanceIdentifierContext();
102 if (entityStream.available() < 1) {
103 // represent empty nopayload input
104 return new NormalizedNodeContext(path, null);
107 final Document doc = UntrustedXML.newDocumentBuilder().parse(entityStream);
108 return parse(path, doc);
111 private NormalizedNodeContext parse(final InstanceIdentifierContext<?> pathContext,final Document doc) {
113 final List<Element> elements = Collections.singletonList(doc.getDocumentElement());
114 final SchemaNode schemaNodeContext = pathContext.getSchemaNode();
115 DataSchemaNode schemaNode;
116 boolean isRpc = false;
117 if (schemaNodeContext instanceof RpcDefinition) {
118 schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
120 } else if (schemaNodeContext instanceof DataSchemaNode) {
121 schemaNode = (DataSchemaNode) schemaNodeContext;
123 throw new IllegalStateException("Unknown SchemaNode");
126 final String docRootElm = doc.getDocumentElement().getLocalName();
127 final String docRootNamespace = doc.getDocumentElement().getNamespaceURI();
128 final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
129 InstanceIdentifierContext<? extends SchemaNode> outIIContext;
131 // FIXME the factory instance should be cached if the schema context is the same
132 final DomToNormalizedNodeParserFactory parserFactory = DomToNormalizedNodeParserFactory
133 .getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, pathContext.getSchemaContext());
135 if (isPost() && !isRpc) {
136 final Deque<Object> foundSchemaNodes = findPathToSchemaNodeByName(schemaNode, docRootElm, docRootNamespace);
137 if (foundSchemaNodes.isEmpty()) {
138 throw new IllegalStateException(String.format("Child \"%s\" was not found in parent schema node \"%s\"",
139 docRootElm, schemaNode.getQName()));
141 while (!foundSchemaNodes.isEmpty()) {
142 final Object child = foundSchemaNodes.pop();
143 if (child instanceof AugmentationSchema) {
144 final AugmentationSchema augmentSchemaNode = (AugmentationSchema) child;
145 iiToDataList.add(SchemaUtils.getNodeIdentifierForAugmentation(augmentSchemaNode));
146 } else if (child instanceof DataSchemaNode) {
147 schemaNode = (DataSchemaNode) child;
148 iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(schemaNode.getQName()));
153 final QName scQName = schemaNode.getQName();
154 Preconditions.checkState(
155 docRootElm.equals(scQName.getLocalName())
156 && docRootNamespace.equals(scQName.getNamespace().toASCIIString()),
157 String.format("Not correct message root element \"%s\", should be \"%s\"",
158 docRootElm, scQName));
161 final NormalizedNode<?, ?> parsed;
162 if (schemaNode instanceof ContainerSchemaNode) {
163 parsed = parserFactory.getContainerNodeParser().parse(
164 Collections.singletonList(doc.getDocumentElement()), (ContainerSchemaNode) schemaNode);
165 } else if (schemaNode instanceof ListSchemaNode) {
166 parsed = parserFactory.getMapEntryNodeParser().parse(elements, (ListSchemaNode) schemaNode);
168 iiToDataList.add(parsed.getIdentifier());
170 } else if (schemaNode instanceof LeafSchemaNode) {
171 parsed = parserFactory.getLeafNodeParser().parse(elements, (LeafSchemaNode) schemaNode);
173 LOG.warn("Unknown schema node extension {} was not parsed", schemaNode.getClass());
177 final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
178 pathContext.getInstanceIdentifier().getPathArguments(), iiToDataList));
180 outIIContext = new InstanceIdentifierContext<>(fullIIToData, pathContext.getSchemaNode(),
181 pathContext.getMountPoint(),
182 pathContext.getSchemaContext());
184 return new NormalizedNodeContext(outIIContext, parsed);
187 private static Deque<Object> findPathToSchemaNodeByName(final DataSchemaNode schemaNode, final String elementName,
188 final String namespace) {
189 final Deque<Object> result = new ArrayDeque<>();
190 final ArrayList<ChoiceSchemaNode> choiceSchemaNodes = new ArrayList<>();
191 final Collection<DataSchemaNode> children = ((DataNodeContainer) schemaNode).getChildNodes();
192 for (final DataSchemaNode child : children) {
193 if (child instanceof ChoiceSchemaNode) {
194 choiceSchemaNodes.add((ChoiceSchemaNode) child);
195 } else if (child.getQName().getLocalName().equalsIgnoreCase(elementName)
196 && child.getQName().getNamespace().toString().equalsIgnoreCase(namespace)) {
197 // add child to result
201 if (child.isAugmenting()) {
202 final AugmentationSchema augment = findCorrespondingAugment(schemaNode, child);
203 if (augment != null) {
204 result.push(augment);
213 for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) {
214 for (final ChoiceCaseNode caseNode : choiceNode.getCases()) {
215 final Deque<Object> resultFromRecursion = findPathToSchemaNodeByName(caseNode, elementName, namespace);
216 if (!resultFromRecursion.isEmpty()) {
217 resultFromRecursion.push(choiceNode);
218 if (choiceNode.isAugmenting()) {
219 final AugmentationSchema augment = findCorrespondingAugment(schemaNode, choiceNode);
220 if (augment != null) {
221 resultFromRecursion.push(augment);
224 return resultFromRecursion;
231 private static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent,
232 final DataSchemaNode child) {
233 if ((parent instanceof AugmentationTarget) && !(parent instanceof ChoiceSchemaNode)) {
234 for (final AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
235 final DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
236 if (childInAugmentation != null) {