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.jersey.providers;
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.core.Request;
26 import javax.ws.rs.core.UriInfo;
27 import javax.ws.rs.ext.MessageBodyReader;
28 import javax.ws.rs.ext.Provider;
29 import javax.xml.parsers.DocumentBuilder;
30 import javax.xml.parsers.DocumentBuilderFactory;
31 import javax.xml.parsers.ParserConfigurationException;
32 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
33 import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext;
34 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
35 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
36 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
37 import org.opendaylight.restconf.Draft17;
38 import org.opendaylight.restconf.utils.RestconfConstants;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
40 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
41 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
42 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
43 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
44 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
45 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
46 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
47 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
50 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
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;
60 @Consumes({ Draft17.MediaTypes.DATA + RestconfConstants.XML, MediaType.APPLICATION_XML, MediaType.TEXT_XML })
61 public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsProvider implements MessageBodyReader<NormalizedNodeContext> {
63 private final static Logger LOG = LoggerFactory.getLogger(XmlNormalizedNodeBodyReader.class);
64 private static final DocumentBuilderFactory BUILDERFACTORY;
67 final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
69 factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
70 factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
71 factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
72 factory.setXIncludeAware(false);
73 factory.setExpandEntityReferences(false);
74 } catch (final ParserConfigurationException e) {
75 throw new ExceptionInInitializerError(e);
77 factory.setNamespaceAware(true);
78 factory.setCoalescing(true);
79 factory.setIgnoringElementContentWhitespace(true);
80 factory.setIgnoringComments(true);
81 BUILDERFACTORY = factory;
85 public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
86 final MediaType mediaType) {
91 public NormalizedNodeContext readFrom(final Class<NormalizedNodeContext> type, final Type genericType,
92 final Annotation[] annotations, final MediaType mediaType,
93 final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException,
94 WebApplicationException {
96 final InstanceIdentifierContext<?> path = getInstanceIdentifierContext();
98 if (entityStream.available() < 1) {
99 // represent empty nopayload input
100 return new NormalizedNodeContext(path, null);
103 final DocumentBuilder dBuilder;
105 dBuilder = BUILDERFACTORY.newDocumentBuilder();
106 } catch (final ParserConfigurationException e) {
107 throw new RuntimeException("Failed to parse XML document", e);
109 final Document doc = dBuilder.parse(entityStream);
111 return parse(path,doc);
112 } catch (final RestconfDocumentedException e){
114 } catch (final Exception e) {
115 LOG.debug("Error parsing xml input", e);
117 throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
118 ErrorTag.MALFORMED_MESSAGE);
122 private NormalizedNodeContext parse(final InstanceIdentifierContext<?> pathContext,final Document doc) {
124 final List<Element> elements = Collections.singletonList(doc.getDocumentElement());
125 final SchemaNode schemaNodeContext = pathContext.getSchemaNode();
126 DataSchemaNode schemaNode;
127 boolean isRpc = false;
128 if (schemaNodeContext instanceof RpcDefinition) {
129 schemaNode = ((RpcDefinition) schemaNodeContext).getInput();
131 } else if (schemaNodeContext instanceof DataSchemaNode) {
132 schemaNode = (DataSchemaNode) schemaNodeContext;
134 throw new IllegalStateException("Unknown SchemaNode");
137 final String docRootElm = doc.getDocumentElement().getLocalName();
138 final String docRootNamespace = doc.getDocumentElement().getNamespaceURI();
139 final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
140 InstanceIdentifierContext<? extends SchemaNode> outIIContext;
143 final DomToNormalizedNodeParserFactory parserFactory =
144 DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, pathContext.getSchemaContext());
146 if (isPost() && !isRpc) {
147 final Deque<Object> foundSchemaNodes = findPathToSchemaNodeByName(schemaNode, docRootElm, docRootNamespace);
148 if (foundSchemaNodes.isEmpty()) {
149 throw new IllegalStateException(String.format("Child \"%s\" was not found in parent schema node \"%s\"",
150 docRootElm, schemaNode.getQName()));
152 while (!foundSchemaNodes.isEmpty()) {
153 final Object child = foundSchemaNodes.pop();
154 if (child instanceof AugmentationSchema) {
155 final AugmentationSchema augmentSchemaNode = (AugmentationSchema) child;
156 iiToDataList.add(SchemaUtils.getNodeIdentifierForAugmentation(augmentSchemaNode));
157 } else if (child instanceof DataSchemaNode) {
158 schemaNode = (DataSchemaNode) child;
159 iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(schemaNode.getQName()));
164 NormalizedNode<?, ?> parsed = null;
166 if (schemaNode instanceof ContainerSchemaNode) {
167 parsed = parserFactory.getContainerNodeParser().parse(Collections.singletonList(doc.getDocumentElement()), (ContainerSchemaNode) schemaNode);
168 } else if(schemaNode instanceof ListSchemaNode) {
169 final ListSchemaNode casted = (ListSchemaNode) schemaNode;
170 parsed = parserFactory.getMapEntryNodeParser().parse(elements, casted);
172 iiToDataList.add(parsed.getIdentifier());
176 final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(
177 pathContext.getInstanceIdentifier().getPathArguments(), iiToDataList));
179 outIIContext = new InstanceIdentifierContext<>(fullIIToData, pathContext.getSchemaNode(), pathContext.getMountPoint(),
180 pathContext.getSchemaContext());
182 return new NormalizedNodeContext(outIIContext, parsed);
185 private static Deque<Object> findPathToSchemaNodeByName(final DataSchemaNode schemaNode, final String elementName,
186 final String namespace) {
187 final Deque<Object> result = new ArrayDeque<>();
188 final ArrayList<ChoiceSchemaNode> choiceSchemaNodes = new ArrayList<>();
189 final Collection<DataSchemaNode> children = ((DataNodeContainer) schemaNode).getChildNodes();
190 for (final DataSchemaNode child : children) {
191 if (child instanceof ChoiceSchemaNode) {
192 choiceSchemaNodes.add((ChoiceSchemaNode) child);
193 } else if (child.getQName().getLocalName().equalsIgnoreCase(elementName)
194 && child.getQName().getNamespace().toString().equalsIgnoreCase(namespace)) {
195 // add child to result
199 if (child.isAugmenting()) {
200 final AugmentationSchema augment = findCorrespondingAugment(schemaNode, child);
201 if (augment != null) {
202 result.push(augment);
211 for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) {
212 for (final ChoiceCaseNode caseNode : choiceNode.getCases()) {
213 final Deque<Object> resultFromRecursion = findPathToSchemaNodeByName(caseNode, elementName, namespace);
214 if (!resultFromRecursion.isEmpty()) {
215 resultFromRecursion.push(choiceNode);
216 if (choiceNode.isAugmenting()) {
217 final AugmentationSchema augment = findCorrespondingAugment(schemaNode, choiceNode);
218 if (augment != null) {
219 resultFromRecursion.push(augment);
222 return resultFromRecursion;
229 private static AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent, final DataSchemaNode child) {
230 if ((parent instanceof AugmentationTarget) && !(parent instanceof ChoiceSchemaNode)) {
231 for (final AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
232 final DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
233 if (childInAugmentation != null) {
241 public void injectParams(final UriInfo uriInfo, final Request request) {