Merge "Convert rcf8040 from web.xml to programmtic web API"
[netconf.git] / restconf / restconf-nb-bierman02 / src / main / java / org / opendaylight / netconf / sal / rest / impl / RestconfDocumentedExceptionMapper.java
1 /*
2  * Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.netconf.sal.rest.impl;
10
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;
19 import java.net.URI;
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;
69
70 /**
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.
73  *
74  * @author Thomas Pantelis
75  */
76 @Provider
77 public class RestconfDocumentedExceptionMapper implements ExceptionMapper<RestconfDocumentedException> {
78
79     private static final Logger LOG = LoggerFactory.getLogger(RestconfDocumentedExceptionMapper.class);
80
81     private static final XMLOutputFactory XML_FACTORY;
82
83     static {
84         XML_FACTORY = XMLOutputFactory.newFactory();
85         XML_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
86     }
87
88     @Context
89     private HttpHeaders headers;
90
91     private final ControllerContext controllerContext;
92
93     public RestconfDocumentedExceptionMapper(ControllerContext controllerContext) {
94         this.controllerContext = Preconditions.checkNotNull(controllerContext);
95     }
96
97     @Override
98     public Response toResponse(final RestconfDocumentedException exception) {
99
100         LOG.debug("In toResponse: {}", exception.getMessage());
101
102         final List<MediaType> accepts = headers.getAcceptableMediaTypes();
103         if (accepts != null) {
104             accepts.remove(MediaType.WILDCARD_TYPE);
105         }
106
107         LOG.debug("Accept headers: {}", accepts);
108
109         final MediaType mediaType;
110         if (accepts != null && accepts.size() > 0) {
111             mediaType = accepts.get(0); // just pick the first one
112         } else {
113             // Default to the content type if there's no Accept header
114             mediaType = MediaType.APPLICATION_JSON_TYPE;
115         }
116
117         LOG.debug("Using MediaType: {}", mediaType);
118
119         final List<RestconfError> errors = exception.getErrors();
120         if (errors.isEmpty()) {
121             // We don't actually want to send any content but, if we don't set any content here,
122             // the tomcat front-end will send back an html error report. To prevent that, set a
123             // single space char in the entity.
124
125             return Response.status(exception.getStatus()).type(MediaType.TEXT_PLAIN_TYPE).entity(" ").build();
126         }
127
128         final int status = errors.iterator().next().getErrorTag().getStatusCode();
129
130         final DataNodeContainer errorsSchemaNode =
131                 (DataNodeContainer) controllerContext.getRestconfModuleErrorsSchemaNode();
132
133         if (errorsSchemaNode == null) {
134             return Response.status(status).type(MediaType.TEXT_PLAIN_TYPE).entity(exception.getMessage()).build();
135         }
136
137         Preconditions.checkState(errorsSchemaNode instanceof ContainerSchemaNode,
138                 "Found Errors SchemaNode isn't ContainerNode");
139         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> errContBuild =
140                 Builders.containerBuilder((ContainerSchemaNode) errorsSchemaNode);
141
142         final List<DataSchemaNode> schemaList = ControllerContext.findInstanceDataChildrenByName(errorsSchemaNode,
143                 Draft02.RestConfModule.ERROR_LIST_SCHEMA_NODE);
144         final DataSchemaNode errListSchemaNode = Iterables.getFirst(schemaList, null);
145         Preconditions.checkState(
146                 errListSchemaNode instanceof ListSchemaNode, "Found Error SchemaNode isn't ListSchemaNode");
147         final CollectionNodeBuilder<MapEntryNode, MapNode> listErorsBuilder = Builders
148                 .mapBuilder((ListSchemaNode) errListSchemaNode);
149
150
151         for (final RestconfError error : errors) {
152             listErorsBuilder.withChild(toErrorEntryNode(error, errListSchemaNode));
153         }
154         errContBuild.withChild(listErorsBuilder.build());
155
156         final NormalizedNodeContext errContext =  new NormalizedNodeContext(new InstanceIdentifierContext<>(null,
157                 (DataSchemaNode) errorsSchemaNode, null, controllerContext.getGlobalSchema()), errContBuild.build());
158
159         Object responseBody;
160         if (mediaType.getSubtype().endsWith("json")) {
161             responseBody = toJsonResponseBody(errContext, errorsSchemaNode);
162         } else {
163             responseBody = toXMLResponseBody(errContext, errorsSchemaNode);
164         }
165
166         return Response.status(status).type(mediaType).entity(responseBody).build();
167     }
168
169     private static MapEntryNode toErrorEntryNode(final RestconfError error, final DataSchemaNode errListSchemaNode) {
170         Preconditions.checkArgument(errListSchemaNode instanceof ListSchemaNode,
171                 "errListSchemaNode has to be of type ListSchemaNode");
172         final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) errListSchemaNode;
173         final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> errNodeValues = Builders
174                 .mapEntryBuilder(listStreamSchemaNode);
175
176         List<DataSchemaNode> lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName(
177                 listStreamSchemaNode, "error-type");
178         final DataSchemaNode errTypSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
179         Preconditions.checkState(errTypSchemaNode instanceof LeafSchemaNode);
180         errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errTypSchemaNode)
181                 .withValue(error.getErrorType().getErrorTypeTag()).build());
182
183         lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName(
184                 listStreamSchemaNode, "error-tag");
185         final DataSchemaNode errTagSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
186         Preconditions.checkState(errTagSchemaNode instanceof LeafSchemaNode);
187         errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errTagSchemaNode)
188                 .withValue(error.getErrorTag().getTagValue()).build());
189
190         if (error.getErrorAppTag() != null) {
191             lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName(
192                     listStreamSchemaNode, "error-app-tag");
193             final DataSchemaNode errAppTagSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
194             Preconditions.checkState(errAppTagSchemaNode instanceof LeafSchemaNode);
195             errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errAppTagSchemaNode)
196                     .withValue(error.getErrorAppTag()).build());
197         }
198
199         lsChildDataSchemaNode = ControllerContext.findInstanceDataChildrenByName(
200                 listStreamSchemaNode, "error-message");
201         final DataSchemaNode errMsgSchemaNode = Iterables.getFirst(lsChildDataSchemaNode, null);
202         Preconditions.checkState(errMsgSchemaNode instanceof LeafSchemaNode);
203         errNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) errMsgSchemaNode)
204                 .withValue(error.getErrorMessage()).build());
205
206         if (error.getErrorInfo() != null) {
207             // Oddly, error-info is defined as an empty container in the restconf yang. Apparently the
208             // intention is for implementors to define their own data content so we'll just treat it as a leaf
209             // with string data.
210             errNodeValues.withChild(ImmutableNodes.leafNode(Draft02.RestConfModule.ERROR_INFO_QNAME,
211                     error.getErrorInfo()));
212         }
213
214         // TODO : find how could we add possible "error-path"
215
216         return errNodeValues.build();
217     }
218
219     private static Object toJsonResponseBody(final NormalizedNodeContext errorsNode,
220                                              final DataNodeContainer errorsSchemaNode) {
221         final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
222         NormalizedNode<?, ?> data = errorsNode.getData();
223         final InstanceIdentifierContext<?> context = errorsNode.getInstanceIdentifierContext();
224         final DataSchemaNode schema = (DataSchemaNode) context.getSchemaNode();
225
226         SchemaPath path = context.getSchemaNode().getPath();
227         final OutputStreamWriter outputWriter = new OutputStreamWriter(outStream, StandardCharsets.UTF_8);
228         if (data == null) {
229             throw new RestconfDocumentedException(Response.Status.NOT_FOUND);
230         }
231
232         boolean isDataRoot = false;
233         URI initialNs = null;
234         if (SchemaPath.ROOT.equals(path)) {
235             isDataRoot = true;
236         } else {
237             path = path.getParent();
238             // FIXME: Add proper handling of reading root.
239         }
240         if (!schema.isAugmenting() && !(schema instanceof SchemaContext)) {
241             initialNs = schema.getQName().getNamespace();
242         }
243
244         final JsonWriter jsonWriter = JsonWriterFactory.createJsonWriter(outputWriter);
245         final NormalizedNodeStreamWriter jsonStreamWriter = JSONNormalizedNodeStreamWriter.createExclusiveWriter(
246                 JSONCodecFactory.getShared(context.getSchemaContext()), path, initialNs, jsonWriter);
247
248         // We create a delegating writer to special-case error-info as error-info is defined as an empty
249         // container in the restconf yang schema but we create a leaf node so we can output it. The delegate
250         // stream writer validates the node type against the schema and thus will expect a LeafSchemaNode but
251         // the schema has a ContainerSchemaNode so, to avoid an error, we override the leafNode behavior
252         // for error-info.
253         final NormalizedNodeStreamWriter streamWriter = new ForwardingNormalizedNodeStreamWriter() {
254             @Override
255             protected NormalizedNodeStreamWriter delegate() {
256                 return jsonStreamWriter;
257             }
258
259             @Override
260             public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
261                 if (name.getNodeType().equals(Draft02.RestConfModule.ERROR_INFO_QNAME)) {
262                     jsonWriter.name(Draft02.RestConfModule.ERROR_INFO_QNAME.getLocalName());
263                     jsonWriter.value(value.toString());
264                 } else {
265                     super.leafNode(name, value);
266                 }
267             }
268         };
269
270         final NormalizedNodeWriter nnWriter = NormalizedNodeWriter.forStreamWriter(streamWriter);
271         try {
272             if (isDataRoot) {
273                 writeDataRoot(outputWriter,nnWriter,(ContainerNode) data);
274             } else {
275                 if (data instanceof MapEntryNode) {
276                     data = ImmutableNodes.mapNodeBuilder(data.getNodeType()).withChild((MapEntryNode) data).build();
277                 }
278                 nnWriter.write(data);
279             }
280             nnWriter.flush();
281             outputWriter.flush();
282         } catch (final IOException e) {
283             LOG.warn("Error writing error response body", e);
284         }
285
286         try {
287             return outStream.toString(StandardCharsets.UTF_8.name());
288         } catch (UnsupportedEncodingException e) {
289             // Shouldn't happen
290             return "Failure encoding error response: " + e;
291         }
292     }
293
294     private static Object toXMLResponseBody(final NormalizedNodeContext errorsNode,
295                                             final DataNodeContainer errorsSchemaNode) {
296         final InstanceIdentifierContext<?> pathContext = errorsNode.getInstanceIdentifierContext();
297         final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
298
299         final XMLStreamWriter xmlWriter;
300         try {
301             xmlWriter = XML_FACTORY.createXMLStreamWriter(outStream, StandardCharsets.UTF_8.name());
302         } catch (final XMLStreamException e) {
303             throw new IllegalStateException(e);
304         } catch (final FactoryConfigurationError e) {
305             throw new IllegalStateException(e);
306         }
307         NormalizedNode<?, ?> data = errorsNode.getData();
308         SchemaPath schemaPath = pathContext.getSchemaNode().getPath();
309
310         boolean isDataRoot = false;
311         if (SchemaPath.ROOT.equals(schemaPath)) {
312             isDataRoot = true;
313         } else {
314             schemaPath = schemaPath.getParent();
315         }
316
317         final NormalizedNodeStreamWriter xmlStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter,
318                 pathContext.getSchemaContext(), schemaPath);
319
320         // We create a delegating writer to special-case error-info as error-info is defined as an empty
321         // container in the restconf yang schema but we create a leaf node so we can output it. The delegate
322         // stream writer validates the node type against the schema and thus will expect a LeafSchemaNode but
323         // the schema has a ContainerSchemaNode so, to avoid an error, we override the leafNode behavior
324         // for error-info.
325         final NormalizedNodeStreamWriter streamWriter = new ForwardingNormalizedNodeStreamWriter() {
326             @Override
327             protected NormalizedNodeStreamWriter delegate() {
328                 return xmlStreamWriter;
329             }
330
331             @Override
332             public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
333                 if (name.getNodeType().equals(Draft02.RestConfModule.ERROR_INFO_QNAME)) {
334                     String ns = Draft02.RestConfModule.ERROR_INFO_QNAME.getNamespace().toString();
335                     try {
336                         xmlWriter.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX,
337                                 Draft02.RestConfModule.ERROR_INFO_QNAME.getLocalName(), ns);
338                         xmlWriter.writeCharacters(value.toString());
339                         xmlWriter.writeEndElement();
340                     } catch (XMLStreamException e) {
341                         throw new IOException("Error writing error-info", e);
342                     }
343                 } else {
344                     super.leafNode(name, value);
345                 }
346             }
347         };
348
349         final NormalizedNodeWriter nnWriter = NormalizedNodeWriter.forStreamWriter(streamWriter);
350         try {
351             if (isDataRoot) {
352                 writeRootElement(xmlWriter, nnWriter, (ContainerNode) data);
353             } else {
354                 if (data instanceof MapEntryNode) {
355                     // Restconf allows returning one list item. We need to wrap it
356                     // in map node in order to serialize it properly
357                     data = ImmutableNodes.mapNodeBuilder(data.getNodeType()).addChild((MapEntryNode) data).build();
358                 }
359                 nnWriter.write(data);
360                 nnWriter.flush();
361             }
362         } catch (final IOException e) {
363             LOG.warn("Error writing error response body.", e);
364         }
365
366         try {
367             return outStream.toString(StandardCharsets.UTF_8.name());
368         } catch (UnsupportedEncodingException e) {
369             // Shouldn't happen
370             return "Failure encoding error response: " + e;
371         }
372     }
373
374     private static void writeRootElement(final XMLStreamWriter xmlWriter, final NormalizedNodeWriter nnWriter,
375                                          final ContainerNode data)
376             throws IOException {
377         try {
378             final QName name = SchemaContext.NAME;
379             xmlWriter.writeStartElement(name.getNamespace().toString(), name.getLocalName());
380             for (final DataContainerChild<? extends PathArgument, ?> child : data.getValue()) {
381                 nnWriter.write(child);
382             }
383             nnWriter.flush();
384             xmlWriter.writeEndElement();
385             xmlWriter.flush();
386         } catch (final XMLStreamException e) {
387             Throwables.propagate(e);
388         }
389     }
390
391     private static void writeDataRoot(final OutputStreamWriter outputWriter, final NormalizedNodeWriter nnWriter,
392                                       final ContainerNode data) throws IOException {
393         final Iterator<DataContainerChild<? extends PathArgument, ?>> iterator = data.getValue().iterator();
394         while (iterator.hasNext()) {
395             final DataContainerChild<? extends PathArgument, ?> child = iterator.next();
396             nnWriter.write(child);
397             nnWriter.flush();
398         }
399     }
400 }