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.collect.Iterables;
11 import java.io.IOException;
12 import java.io.InputStream;
13 import java.lang.annotation.Annotation;
14 import java.lang.reflect.Type;
15 import java.util.ArrayDeque;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.Deque;
20 import java.util.List;
21 import javax.ws.rs.Consumes;
22 import javax.ws.rs.WebApplicationException;
23 import javax.ws.rs.core.MediaType;
24 import javax.ws.rs.core.MultivaluedMap;
25 import javax.ws.rs.ext.MessageBodyReader;
26 import javax.ws.rs.ext.Provider;
27 import org.opendaylight.netconf.sal.rest.api.Draft02;
28 import org.opendaylight.netconf.sal.rest.api.RestconfService;
29 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
30 import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext;
31 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
32 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
33 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
34 import org.opendaylight.restconf.utils.RestconfConstants;
35 import org.opendaylight.yangtools.util.xml.UntrustedXML;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
37 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
38 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
39 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
40 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
41 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
42 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
43 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
44 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
47 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
50 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.w3c.dom.Document;
54 import org.w3c.dom.Element;
55 import org.xml.sax.SAXException;
58 @Consumes({ Draft02.MediaTypes.DATA + RestconfService.XML, Draft02.MediaTypes.OPERATION + RestconfService.XML,
59 MediaType.APPLICATION_XML, MediaType.TEXT_XML })
60 public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsProvider
61 implements MessageBodyReader<NormalizedNodeContext> {
63 private static final Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
66 public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
67 final MediaType mediaType) {
71 @SuppressWarnings("checkstyle:IllegalCatch")
73 public NormalizedNodeContext readFrom(final Class<NormalizedNodeContext> type, final Type genericType,
74 final Annotation[] annotations, final MediaType mediaType,
75 final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException,
76 WebApplicationException {
78 if (getUriInfo().getAbsolutePath().getPath().contains(RestconfConstants.DRAFT_PATTERN)) {
79 final org.opendaylight.restconf.jersey.providers.XmlNormalizedNodeBodyReader xmlReaderNewRest =
80 new org.opendaylight.restconf.jersey.providers.XmlNormalizedNodeBodyReader();
81 xmlReaderNewRest.injectParams(getUriInfo(), getRequest());
82 return xmlReaderNewRest.readFrom(type, genericType, annotations, mediaType, httpHeaders, entityStream);
84 return readFrom(entityStream);
86 } catch (final RestconfDocumentedException e) {
88 } catch (final Exception e) {
89 LOG.debug("Error parsing xml input", e);
91 throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
92 ErrorTag.MALFORMED_MESSAGE);
96 private NormalizedNodeContext readFrom(final InputStream entityStream) throws IOException, SAXException {
97 final InstanceIdentifierContext<?> path = getInstanceIdentifierContext();
99 if (entityStream.available() < 1) {
100 // represent empty nopayload input
101 return new NormalizedNodeContext(path, null);
104 final Document doc = UntrustedXML.newDocumentBuilder().parse(entityStream);
105 return parse(path, doc);
108 private NormalizedNodeContext parse(final InstanceIdentifierContext<?> pathContext,final Document doc) {
110 final List<Element> elements = Collections.singletonList(doc.getDocumentElement());
111 final SchemaNode schemaNodeContext = pathContext.getSchemaNode();
112 DataSchemaNode schemaNode;
113 boolean isRpc = false;
114 if (schemaNodeContext instanceof RpcDefinition) {
115 schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
117 } else if (schemaNodeContext instanceof DataSchemaNode) {
118 schemaNode = (DataSchemaNode) schemaNodeContext;
120 throw new IllegalStateException("Unknown SchemaNode");
123 final String docRootElm = doc.getDocumentElement().getLocalName();
124 final String docRootNamespace = doc.getDocumentElement().getNamespaceURI();
125 final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
126 InstanceIdentifierContext<? extends SchemaNode> outIIContext;
128 // FIXME the factory instance should be cached if the schema context is the same
129 final DomToNormalizedNodeParserFactory parserFactory = DomToNormalizedNodeParserFactory
130 .getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, pathContext.getSchemaContext());
132 if (isPost() && !isRpc) {
133 final Deque<Object> foundSchemaNodes = findPathToSchemaNodeByName(schemaNode, docRootElm, docRootNamespace);
134 if (foundSchemaNodes.isEmpty()) {
135 throw new IllegalStateException(String.format("Child \"%s\" was not found in parent schema node \"%s\"",
136 docRootElm, schemaNode.getQName()));
138 while (!foundSchemaNodes.isEmpty()) {
139 final Object child = foundSchemaNodes.pop();
140 if (child instanceof AugmentationSchema) {
141 final AugmentationSchema augmentSchemaNode = (AugmentationSchema) child;
142 iiToDataList.add(SchemaUtils.getNodeIdentifierForAugmentation(augmentSchemaNode));
143 } else if (child instanceof DataSchemaNode) {
144 schemaNode = (DataSchemaNode) child;
145 iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(schemaNode.getQName()));
150 NormalizedNode<?, ?> parsed = null;
152 if (schemaNode instanceof ContainerSchemaNode) {
153 parsed = parserFactory.getContainerNodeParser().parse(Collections.singletonList(doc.getDocumentElement()),
154 (ContainerSchemaNode) schemaNode);
155 } else if (schemaNode instanceof ListSchemaNode) {
156 final ListSchemaNode casted = (ListSchemaNode) schemaNode;
157 parsed = parserFactory.getMapEntryNodeParser().parse(elements, casted);
159 iiToDataList.add(parsed.getIdentifier());
162 // FIXME : add another DataSchemaNode extensions e.g. LeafSchemaNode
164 final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
165 pathContext.getInstanceIdentifier().getPathArguments(), iiToDataList));
167 outIIContext = new InstanceIdentifierContext<>(fullIIToData, pathContext.getSchemaNode(),
168 pathContext.getMountPoint(),
169 pathContext.getSchemaContext());
171 return new NormalizedNodeContext(outIIContext, parsed);
174 private static Deque<Object> findPathToSchemaNodeByName(final DataSchemaNode schemaNode, final String elementName,
175 final String namespace) {
176 final Deque<Object> result = new ArrayDeque<>();
177 final ArrayList<ChoiceSchemaNode> choiceSchemaNodes = new ArrayList<>();
178 final Collection<DataSchemaNode> children = ((DataNodeContainer) schemaNode).getChildNodes();
179 for (final DataSchemaNode child : children) {
180 if (child instanceof ChoiceSchemaNode) {
181 choiceSchemaNodes.add((ChoiceSchemaNode) child);
182 } else if (child.getQName().getLocalName().equalsIgnoreCase(elementName)
183 && child.getQName().getNamespace().toString().equalsIgnoreCase(namespace)) {
184 // add child to result
188 if (child.isAugmenting()) {
189 final AugmentationSchema augment = findCorrespondingAugment(schemaNode, child);
190 if (augment != null) {
191 result.push(augment);
200 for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) {
201 for (final ChoiceCaseNode caseNode : choiceNode.getCases()) {
202 final Deque<Object> resultFromRecursion = findPathToSchemaNodeByName(caseNode, elementName, namespace);
203 if (!resultFromRecursion.isEmpty()) {
204 resultFromRecursion.push(choiceNode);
205 if (choiceNode.isAugmenting()) {
206 final AugmentationSchema augment = findCorrespondingAugment(schemaNode, choiceNode);
207 if (augment != null) {
208 resultFromRecursion.push(augment);
211 return resultFromRecursion;
218 private static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent,
219 final DataSchemaNode child) {
220 if ((parent instanceof AugmentationTarget) && !(parent instanceof ChoiceSchemaNode)) {
221 for (final AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
222 final DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
223 if (childInAugmentation != null) {