2 * Copyright (c) 2014 Brocade Communications 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
9 package org.opendaylight.netconf.sal.rest.impl;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Throwables;
13 import com.google.common.collect.Iterables;
14 import com.google.gson.stream.JsonWriter;
15 import java.io.ByteArrayOutputStream;
16 import java.io.IOException;
17 import java.io.OutputStreamWriter;
18 import java.io.UnsupportedEncodingException;
20 import java.nio.charset.StandardCharsets;
21 import java.util.Iterator;
22 import java.util.List;
23 import javax.ws.rs.core.Context;
24 import javax.ws.rs.core.HttpHeaders;
25 import javax.ws.rs.core.MediaType;
26 import javax.ws.rs.core.Response;
27 import javax.ws.rs.ext.ExceptionMapper;
28 import javax.ws.rs.ext.Provider;
29 import javax.xml.XMLConstants;
30 import javax.xml.stream.FactoryConfigurationError;
31 import javax.xml.stream.XMLOutputFactory;
32 import javax.xml.stream.XMLStreamException;
33 import javax.xml.stream.XMLStreamWriter;
34 import org.opendaylight.netconf.sal.rest.api.Draft02;
35 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
36 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
37 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
38 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
39 import org.opendaylight.restconf.common.errors.RestconfError;
40 import org.opendaylight.yangtools.yang.common.QName;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
44 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
46 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.stream.ForwardingNormalizedNodeStreamWriter;
50 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
51 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
52 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactory;
53 import org.opendaylight.yangtools.yang.data.codec.gson.JSONNormalizedNodeStreamWriter;
54 import org.opendaylight.yangtools.yang.data.codec.gson.JsonWriterFactory;
55 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
56 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
57 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
58 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
59 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
60 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
62 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
66 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
71 * This class defines an ExceptionMapper that handles RestconfDocumentedExceptions thrown by resource implementations
72 * and translates appropriately to restconf error response as defined in the RESTCONF RFC draft.
74 * @author Thomas Pantelis
77 public class RestconfDocumentedExceptionMapper implements ExceptionMapper<RestconfDocumentedException> {
79 private static final Logger LOG = LoggerFactory.getLogger(RestconfDocumentedExceptionMapper.class);
81 private static final XMLOutputFactory XML_FACTORY;
84 XML_FACTORY = XMLOutputFactory.newFactory();
85 XML_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
89 private HttpHeaders headers;
91 private final ControllerContext controllerContext;
93 public RestconfDocumentedExceptionMapper(ControllerContext controllerContext) {
94 this.controllerContext = Preconditions.checkNotNull(controllerContext);
98 public Response toResponse(final RestconfDocumentedException exception) {
100 LOG.debug("In toResponse: {}", exception.getMessage());
102 final MediaType mediaType = headers.getAcceptableMediaTypes().stream()
103 .filter(type -> !type.equals(MediaType.WILDCARD_TYPE)).findFirst()
104 .orElse(MediaType.APPLICATION_JSON_TYPE);
106 LOG.debug("Using MediaType: {}", mediaType);
108 final List<RestconfError> errors = exception.getErrors();
109 if (errors.isEmpty()) {
110 // We don't actually want to send any content but, if we don't set any content here,
111 // the tomcat front-end will send back an html error report. To prevent that, set a
112 // single space char in the entity.
114 return Response.status(exception.getStatus()).type(MediaType.TEXT_PLAIN_TYPE).entity(" ").build();
117 final int status = errors.iterator().next().getErrorTag().getStatusCode();
119 final DataNodeContainer errorsSchemaNode =
120 (DataNodeContainer) controllerContext.getRestconfModuleErrorsSchemaNode();
122 if (errorsSchemaNode == null) {
123 return Response.status(status).type(MediaType.TEXT_PLAIN_TYPE).entity(exception.getMessage()).build();
126 Preconditions.checkState(errorsSchemaNode instanceof ContainerSchemaNode,
127 "Found Errors SchemaNode isn't ContainerNode");
128 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> errContBuild =
129 Builders.containerBuilder((ContainerSchemaNode) errorsSchemaNode);
131 final List<DataSchemaNode> schemaList = ControllerContext.findInstanceDataChildrenByName(errorsSchemaNode,
132 Draft02.RestConfModule.ERROR_LIST_SCHEMA_NODE);
133 final DataSchemaNode errListSchemaNode = Iterables.getFirst(schemaList, null);
134 Preconditions.checkState(
135 errListSchemaNode instanceof ListSchemaNode, "Found Error SchemaNode isn't ListSchemaNode");
136 final CollectionNodeBuilder<MapEntryNode, MapNode> listErorsBuilder = Builders
137 .mapBuilder((ListSchemaNode) errListSchemaNode);
140 for (final RestconfError error : errors) {
141 listErorsBuilder.withChild(toErrorEntryNode(error, errListSchemaNode));
143 errContBuild.withChild(listErorsBuilder.build());
145 final NormalizedNodeContext errContext = new NormalizedNodeContext(new InstanceIdentifierContext<>(null,
146 (DataSchemaNode) errorsSchemaNode, null, controllerContext.getGlobalSchema()), errContBuild.build());
149 if (mediaType.getSubtype().endsWith("json")) {
150 responseBody = toJsonResponseBody(errContext, errorsSchemaNode);
152 responseBody = toXMLResponseBody(errContext, errorsSchemaNode);
155 return Response.status(status).type(mediaType).entity(responseBody).build();
158 private static MapEntryNode toErrorEntryNode(final RestconfError error, final DataSchemaNode errListSchemaNode) {
159 Preconditions.checkArgument(errListSchemaNode instanceof ListSchemaNode,
160 "errListSchemaNode has to be of type ListSchemaNode");
161 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) errListSchemaNode;
162 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> errNodeValues = Builders
163 .mapEntryBuilder(listStreamSchemaNode);
165 List<DataSchemaNode> lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName(
166 listStreamSchemaNode, "error-type");
167 final DataSchemaNode errTypSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
168 Preconditions.checkState(errTypSchemaNode instanceof LeafSchemaNode);
169 errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errTypSchemaNode)
170 .withValue(error.getErrorType().getErrorTypeTag()).build());
172 lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName(
173 listStreamSchemaNode, "error-tag");
174 final DataSchemaNode errTagSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
175 Preconditions.checkState(errTagSchemaNode instanceof LeafSchemaNode);
176 errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errTagSchemaNode)
177 .withValue(error.getErrorTag().getTagValue()).build());
179 if (error.getErrorAppTag() != null) {
180 lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName(
181 listStreamSchemaNode, "error-app-tag");
182 final DataSchemaNode errAppTagSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
183 Preconditions.checkState(errAppTagSchemaNode instanceof LeafSchemaNode);
184 errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errAppTagSchemaNode)
185 .withValue(error.getErrorAppTag()).build());
188 lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName(
189 listStreamSchemaNode, "error-message");
190 final DataSchemaNode errMsgSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
191 Preconditions.checkState(errMsgSchemaNode instanceof LeafSchemaNode);
192 errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errMsgSchemaNode)
193 .withValue(error.getErrorMessage()).build());
195 if (error.getErrorInfo() != null) {
196 // Oddly, error-info is defined as an empty container in the restconf yang. Apparently the
197 // intention is for implementors to define their own data content so we'll just treat it as a leaf
199 errNodeValues.withChild(ImmutableNodes.leafNode(Draft02.RestConfModule.ERROR_INFO_QNAME,
200 error.getErrorInfo()));
203 // TODO : find how could we add possible "error-path"
205 return errNodeValues.build();
208 private static Object toJsonResponseBody(final NormalizedNodeContext errorsNode,
209 final DataNodeContainer errorsSchemaNode) {
210 final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
211 NormalizedNode<?, ?> data = errorsNode.getData();
212 final InstanceIdentifierContext<?> context = errorsNode.getInstanceIdentifierContext();
213 final DataSchemaNode schema = (DataSchemaNode) context.getSchemaNode();
215 SchemaPath path = context.getSchemaNode().getPath();
216 final OutputStreamWriter outputWriter = new OutputStreamWriter(outStream, StandardCharsets.UTF_8);
218 throw new RestconfDocumentedException(Response.Status.NOT_FOUND);
221 boolean isDataRoot = false;
222 URI initialNs = null;
223 if (SchemaPath.ROOT.equals(path)) {
226 path = path.getParent();
227 // FIXME: Add proper handling of reading root.
229 if (!schema.isAugmenting() && !(schema instanceof SchemaContext)) {
230 initialNs = schema.getQName().getNamespace();
233 final JsonWriter jsonWriter = JsonWriterFactory.createJsonWriter(outputWriter);
234 final NormalizedNodeStreamWriter jsonStreamWriter = JSONNormalizedNodeStreamWriter.createExclusiveWriter(
235 JSONCodecFactory.getShared(context.getSchemaContext()), path, initialNs, jsonWriter);
237 // We create a delegating writer to special-case error-info as error-info is defined as an empty
238 // container in the restconf yang schema but we create a leaf node so we can output it. The delegate
239 // stream writer validates the node type against the schema and thus will expect a LeafSchemaNode but
240 // the schema has a ContainerSchemaNode so, to avoid an error, we override the leafNode behavior
242 final NormalizedNodeStreamWriter streamWriter = new ForwardingNormalizedNodeStreamWriter() {
244 protected NormalizedNodeStreamWriter delegate() {
245 return jsonStreamWriter;
249 public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
250 if (name.getNodeType().equals(Draft02.RestConfModule.ERROR_INFO_QNAME)) {
251 jsonWriter.name(Draft02.RestConfModule.ERROR_INFO_QNAME.getLocalName());
252 jsonWriter.value(value.toString());
254 super.leafNode(name, value);
259 final NormalizedNodeWriter nnWriter = NormalizedNodeWriter.forStreamWriter(streamWriter);
262 writeDataRoot(outputWriter,nnWriter,(ContainerNode) data);
264 if (data instanceof MapEntryNode) {
265 data = ImmutableNodes.mapNodeBuilder(data.getNodeType()).withChild((MapEntryNode) data).build();
267 nnWriter.write(data);
270 outputWriter.flush();
271 } catch (final IOException e) {
272 LOG.warn("Error writing error response body", e);
276 return outStream.toString(StandardCharsets.UTF_8.name());
277 } catch (UnsupportedEncodingException e) {
279 return "Failure encoding error response: " + e;
283 private static Object toXMLResponseBody(final NormalizedNodeContext errorsNode,
284 final DataNodeContainer errorsSchemaNode) {
285 final InstanceIdentifierContext<?> pathContext = errorsNode.getInstanceIdentifierContext();
286 final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
288 final XMLStreamWriter xmlWriter;
290 xmlWriter = XML_FACTORY.createXMLStreamWriter(outStream, StandardCharsets.UTF_8.name());
291 } catch (final XMLStreamException e) {
292 throw new IllegalStateException(e);
293 } catch (final FactoryConfigurationError e) {
294 throw new IllegalStateException(e);
296 NormalizedNode<?, ?> data = errorsNode.getData();
297 SchemaPath schemaPath = pathContext.getSchemaNode().getPath();
299 boolean isDataRoot = false;
300 if (SchemaPath.ROOT.equals(schemaPath)) {
303 schemaPath = schemaPath.getParent();
306 final NormalizedNodeStreamWriter xmlStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter,
307 pathContext.getSchemaContext(), schemaPath);
309 // We create a delegating writer to special-case error-info as error-info is defined as an empty
310 // container in the restconf yang schema but we create a leaf node so we can output it. The delegate
311 // stream writer validates the node type against the schema and thus will expect a LeafSchemaNode but
312 // the schema has a ContainerSchemaNode so, to avoid an error, we override the leafNode behavior
314 final NormalizedNodeStreamWriter streamWriter = new ForwardingNormalizedNodeStreamWriter() {
316 protected NormalizedNodeStreamWriter delegate() {
317 return xmlStreamWriter;
321 public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
322 if (name.getNodeType().equals(Draft02.RestConfModule.ERROR_INFO_QNAME)) {
323 String ns = Draft02.RestConfModule.ERROR_INFO_QNAME.getNamespace().toString();
325 xmlWriter.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX,
326 Draft02.RestConfModule.ERROR_INFO_QNAME.getLocalName(), ns);
327 xmlWriter.writeCharacters(value.toString());
328 xmlWriter.writeEndElement();
329 } catch (XMLStreamException e) {
330 throw new IOException("Error writing error-info", e);
333 super.leafNode(name, value);
338 final NormalizedNodeWriter nnWriter = NormalizedNodeWriter.forStreamWriter(streamWriter);
341 writeRootElement(xmlWriter, nnWriter, (ContainerNode) data);
343 if (data instanceof MapEntryNode) {
344 // Restconf allows returning one list item. We need to wrap it
345 // in map node in order to serialize it properly
346 data = ImmutableNodes.mapNodeBuilder(data.getNodeType()).addChild((MapEntryNode) data).build();
348 nnWriter.write(data);
351 } catch (final IOException e) {
352 LOG.warn("Error writing error response body.", e);
356 return outStream.toString(StandardCharsets.UTF_8.name());
357 } catch (UnsupportedEncodingException e) {
359 return "Failure encoding error response: " + e;
363 private static void writeRootElement(final XMLStreamWriter xmlWriter, final NormalizedNodeWriter nnWriter,
364 final ContainerNode data)
367 final QName name = SchemaContext.NAME;
368 xmlWriter.writeStartElement(name.getNamespace().toString(), name.getLocalName());
369 for (final DataContainerChild<? extends PathArgument, ?> child : data.getValue()) {
370 nnWriter.write(child);
373 xmlWriter.writeEndElement();
375 } catch (final XMLStreamException e) {
376 Throwables.propagate(e);
380 private static void writeDataRoot(final OutputStreamWriter outputWriter, final NormalizedNodeWriter nnWriter,
381 final ContainerNode data) throws IOException {
382 final Iterator<DataContainerChild<? extends PathArgument, ?>> iterator = data.getValue().iterator();
383 while (iterator.hasNext()) {
384 final DataContainerChild<? extends PathArgument, ?> child = iterator.next();
385 nnWriter.write(child);