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 != MediaType.WILDCARD_TYPE).findFirst().orElse(MediaType.APPLICATION_JSON_TYPE);
105 LOG.debug("Using MediaType: {}", mediaType);
107 final List<RestconfError> errors = exception.getErrors();
108 if (errors.isEmpty()) {
109 // We don't actually want to send any content but, if we don't set any content here,
110 // the tomcat front-end will send back an html error report. To prevent that, set a
111 // single space char in the entity.
113 return Response.status(exception.getStatus()).type(MediaType.TEXT_PLAIN_TYPE).entity(" ").build();
116 final int status = errors.iterator().next().getErrorTag().getStatusCode();
118 final DataNodeContainer errorsSchemaNode =
119 (DataNodeContainer) controllerContext.getRestconfModuleErrorsSchemaNode();
121 if (errorsSchemaNode == null) {
122 return Response.status(status).type(MediaType.TEXT_PLAIN_TYPE).entity(exception.getMessage()).build();
125 Preconditions.checkState(errorsSchemaNode instanceof ContainerSchemaNode,
126 "Found Errors SchemaNode isn't ContainerNode");
127 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> errContBuild =
128 Builders.containerBuilder((ContainerSchemaNode) errorsSchemaNode);
130 final List<DataSchemaNode> schemaList = ControllerContext.findInstanceDataChildrenByName(errorsSchemaNode,
131 Draft02.RestConfModule.ERROR_LIST_SCHEMA_NODE);
132 final DataSchemaNode errListSchemaNode = Iterables.getFirst(schemaList, null);
133 Preconditions.checkState(
134 errListSchemaNode instanceof ListSchemaNode, "Found Error SchemaNode isn't ListSchemaNode");
135 final CollectionNodeBuilder<MapEntryNode, MapNode> listErorsBuilder = Builders
136 .mapBuilder((ListSchemaNode) errListSchemaNode);
139 for (final RestconfError error : errors) {
140 listErorsBuilder.withChild(toErrorEntryNode(error, errListSchemaNode));
142 errContBuild.withChild(listErorsBuilder.build());
144 final NormalizedNodeContext errContext = new NormalizedNodeContext(new InstanceIdentifierContext<>(null,
145 (DataSchemaNode) errorsSchemaNode, null, controllerContext.getGlobalSchema()), errContBuild.build());
148 if (mediaType.getSubtype().endsWith("json")) {
149 responseBody = toJsonResponseBody(errContext, errorsSchemaNode);
151 responseBody = toXMLResponseBody(errContext, errorsSchemaNode);
154 return Response.status(status).type(mediaType).entity(responseBody).build();
157 private static MapEntryNode toErrorEntryNode(final RestconfError error, final DataSchemaNode errListSchemaNode) {
158 Preconditions.checkArgument(errListSchemaNode instanceof ListSchemaNode,
159 "errListSchemaNode has to be of type ListSchemaNode");
160 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) errListSchemaNode;
161 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> errNodeValues = Builders
162 .mapEntryBuilder(listStreamSchemaNode);
164 List<DataSchemaNode> lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName(
165 listStreamSchemaNode, "error-type");
166 final DataSchemaNode errTypSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
167 Preconditions.checkState(errTypSchemaNode instanceof LeafSchemaNode);
168 errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errTypSchemaNode)
169 .withValue(error.getErrorType().getErrorTypeTag()).build());
171 lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName(
172 listStreamSchemaNode, "error-tag");
173 final DataSchemaNode errTagSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
174 Preconditions.checkState(errTagSchemaNode instanceof LeafSchemaNode);
175 errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errTagSchemaNode)
176 .withValue(error.getErrorTag().getTagValue()).build());
178 if (error.getErrorAppTag() != null) {
179 lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName(
180 listStreamSchemaNode, "error-app-tag");
181 final DataSchemaNode errAppTagSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
182 Preconditions.checkState(errAppTagSchemaNode instanceof LeafSchemaNode);
183 errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errAppTagSchemaNode)
184 .withValue(error.getErrorAppTag()).build());
187 lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName(
188 listStreamSchemaNode, "error-message");
189 final DataSchemaNode errMsgSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
190 Preconditions.checkState(errMsgSchemaNode instanceof LeafSchemaNode);
191 errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errMsgSchemaNode)
192 .withValue(error.getErrorMessage()).build());
194 if (error.getErrorInfo() != null) {
195 // Oddly, error-info is defined as an empty container in the restconf yang. Apparently the
196 // intention is for implementors to define their own data content so we'll just treat it as a leaf
198 errNodeValues.withChild(ImmutableNodes.leafNode(Draft02.RestConfModule.ERROR_INFO_QNAME,
199 error.getErrorInfo()));
202 // TODO : find how could we add possible "error-path"
204 return errNodeValues.build();
207 private static Object toJsonResponseBody(final NormalizedNodeContext errorsNode,
208 final DataNodeContainer errorsSchemaNode) {
209 final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
210 NormalizedNode<?, ?> data = errorsNode.getData();
211 final InstanceIdentifierContext<?> context = errorsNode.getInstanceIdentifierContext();
212 final DataSchemaNode schema = (DataSchemaNode) context.getSchemaNode();
214 SchemaPath path = context.getSchemaNode().getPath();
215 final OutputStreamWriter outputWriter = new OutputStreamWriter(outStream, StandardCharsets.UTF_8);
217 throw new RestconfDocumentedException(Response.Status.NOT_FOUND);
220 boolean isDataRoot = false;
221 URI initialNs = null;
222 if (SchemaPath.ROOT.equals(path)) {
225 path = path.getParent();
226 // FIXME: Add proper handling of reading root.
228 if (!schema.isAugmenting() && !(schema instanceof SchemaContext)) {
229 initialNs = schema.getQName().getNamespace();
232 final JsonWriter jsonWriter = JsonWriterFactory.createJsonWriter(outputWriter);
233 final NormalizedNodeStreamWriter jsonStreamWriter = JSONNormalizedNodeStreamWriter.createExclusiveWriter(
234 JSONCodecFactory.getShared(context.getSchemaContext()), path, initialNs, jsonWriter);
236 // We create a delegating writer to special-case error-info as error-info is defined as an empty
237 // container in the restconf yang schema but we create a leaf node so we can output it. The delegate
238 // stream writer validates the node type against the schema and thus will expect a LeafSchemaNode but
239 // the schema has a ContainerSchemaNode so, to avoid an error, we override the leafNode behavior
241 final NormalizedNodeStreamWriter streamWriter = new ForwardingNormalizedNodeStreamWriter() {
243 protected NormalizedNodeStreamWriter delegate() {
244 return jsonStreamWriter;
248 public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
249 if (name.getNodeType().equals(Draft02.RestConfModule.ERROR_INFO_QNAME)) {
250 jsonWriter.name(Draft02.RestConfModule.ERROR_INFO_QNAME.getLocalName());
251 jsonWriter.value(value.toString());
253 super.leafNode(name, value);
258 final NormalizedNodeWriter nnWriter = NormalizedNodeWriter.forStreamWriter(streamWriter);
261 writeDataRoot(outputWriter,nnWriter,(ContainerNode) data);
263 if (data instanceof MapEntryNode) {
264 data = ImmutableNodes.mapNodeBuilder(data.getNodeType()).withChild((MapEntryNode) data).build();
266 nnWriter.write(data);
269 outputWriter.flush();
270 } catch (final IOException e) {
271 LOG.warn("Error writing error response body", e);
275 return outStream.toString(StandardCharsets.UTF_8.name());
276 } catch (UnsupportedEncodingException e) {
278 return "Failure encoding error response: " + e;
282 private static Object toXMLResponseBody(final NormalizedNodeContext errorsNode,
283 final DataNodeContainer errorsSchemaNode) {
284 final InstanceIdentifierContext<?> pathContext = errorsNode.getInstanceIdentifierContext();
285 final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
287 final XMLStreamWriter xmlWriter;
289 xmlWriter = XML_FACTORY.createXMLStreamWriter(outStream, StandardCharsets.UTF_8.name());
290 } catch (final XMLStreamException e) {
291 throw new IllegalStateException(e);
292 } catch (final FactoryConfigurationError e) {
293 throw new IllegalStateException(e);
295 NormalizedNode<?, ?> data = errorsNode.getData();
296 SchemaPath schemaPath = pathContext.getSchemaNode().getPath();
298 boolean isDataRoot = false;
299 if (SchemaPath.ROOT.equals(schemaPath)) {
302 schemaPath = schemaPath.getParent();
305 final NormalizedNodeStreamWriter xmlStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter,
306 pathContext.getSchemaContext(), schemaPath);
308 // We create a delegating writer to special-case error-info as error-info is defined as an empty
309 // container in the restconf yang schema but we create a leaf node so we can output it. The delegate
310 // stream writer validates the node type against the schema and thus will expect a LeafSchemaNode but
311 // the schema has a ContainerSchemaNode so, to avoid an error, we override the leafNode behavior
313 final NormalizedNodeStreamWriter streamWriter = new ForwardingNormalizedNodeStreamWriter() {
315 protected NormalizedNodeStreamWriter delegate() {
316 return xmlStreamWriter;
320 public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
321 if (name.getNodeType().equals(Draft02.RestConfModule.ERROR_INFO_QNAME)) {
322 String ns = Draft02.RestConfModule.ERROR_INFO_QNAME.getNamespace().toString();
324 xmlWriter.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX,
325 Draft02.RestConfModule.ERROR_INFO_QNAME.getLocalName(), ns);
326 xmlWriter.writeCharacters(value.toString());
327 xmlWriter.writeEndElement();
328 } catch (XMLStreamException e) {
329 throw new IOException("Error writing error-info", e);
332 super.leafNode(name, value);
337 final NormalizedNodeWriter nnWriter = NormalizedNodeWriter.forStreamWriter(streamWriter);
340 writeRootElement(xmlWriter, nnWriter, (ContainerNode) data);
342 if (data instanceof MapEntryNode) {
343 // Restconf allows returning one list item. We need to wrap it
344 // in map node in order to serialize it properly
345 data = ImmutableNodes.mapNodeBuilder(data.getNodeType()).addChild((MapEntryNode) data).build();
347 nnWriter.write(data);
350 } catch (final IOException e) {
351 LOG.warn("Error writing error response body.", e);
355 return outStream.toString(StandardCharsets.UTF_8.name());
356 } catch (UnsupportedEncodingException e) {
358 return "Failure encoding error response: " + e;
362 private static void writeRootElement(final XMLStreamWriter xmlWriter, final NormalizedNodeWriter nnWriter,
363 final ContainerNode data)
366 final QName name = SchemaContext.NAME;
367 xmlWriter.writeStartElement(name.getNamespace().toString(), name.getLocalName());
368 for (final DataContainerChild<? extends PathArgument, ?> child : data.getValue()) {
369 nnWriter.write(child);
372 xmlWriter.writeEndElement();
374 } catch (final XMLStreamException e) {
375 Throwables.propagate(e);
379 private static void writeDataRoot(final OutputStreamWriter outputWriter, final NormalizedNodeWriter nnWriter,
380 final ContainerNode data) throws IOException {
381 final Iterator<DataContainerChild<? extends PathArgument, ?>> iterator = data.getValue().iterator();
382 while (iterator.hasNext()) {
383 final DataContainerChild<? extends PathArgument, ?> child = iterator.next();
384 nnWriter.write(child);