Fix RestconfDocumentedExceptionMapper exception
[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 MediaType mediaType = headers.getAcceptableMediaTypes().stream()
103                 .filter(type -> type != MediaType.WILDCARD_TYPE).findFirst().orElse(MediaType.APPLICATION_JSON_TYPE);
104
105         LOG.debug("Using MediaType: {}", mediaType);
106
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.
112
113             return Response.status(exception.getStatus()).type(MediaType.TEXT_PLAIN_TYPE).entity(" ").build();
114         }
115
116         final int status = errors.iterator().next().getErrorTag().getStatusCode();
117
118         final DataNodeContainer errorsSchemaNode =
119                 (DataNodeContainer) controllerContext.getRestconfModuleErrorsSchemaNode();
120
121         if (errorsSchemaNode == null) {
122             return Response.status(status).type(MediaType.TEXT_PLAIN_TYPE).entity(exception.getMessage()).build();
123         }
124
125         Preconditions.checkState(errorsSchemaNode instanceof ContainerSchemaNode,
126                 "Found Errors SchemaNode isn't ContainerNode");
127         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> errContBuild =
128                 Builders.containerBuilder((ContainerSchemaNode) errorsSchemaNode);
129
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);
137
138
139         for (final RestconfError error : errors) {
140             listErorsBuilder.withChild(toErrorEntryNode(error, errListSchemaNode));
141         }
142         errContBuild.withChild(listErorsBuilder.build());
143
144         final NormalizedNodeContext errContext =  new NormalizedNodeContext(new InstanceIdentifierContext<>(null,
145                 (DataSchemaNode) errorsSchemaNode, null, controllerContext.getGlobalSchema()), errContBuild.build());
146
147         Object responseBody;
148         if (mediaType.getSubtype().endsWith("json")) {
149             responseBody = toJsonResponseBody(errContext, errorsSchemaNode);
150         } else {
151             responseBody = toXMLResponseBody(errContext, errorsSchemaNode);
152         }
153
154         return Response.status(status).type(mediaType).entity(responseBody).build();
155     }
156
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);
163
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());
170
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());
177
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());
185         }
186
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());
193
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
197             // with string data.
198             errNodeValues.withChild(ImmutableNodes.leafNode(Draft02.RestConfModule.ERROR_INFO_QNAME,
199                     error.getErrorInfo()));
200         }
201
202         // TODO : find how could we add possible "error-path"
203
204         return errNodeValues.build();
205     }
206
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();
213
214         SchemaPath path = context.getSchemaNode().getPath();
215         final OutputStreamWriter outputWriter = new OutputStreamWriter(outStream, StandardCharsets.UTF_8);
216         if (data == null) {
217             throw new RestconfDocumentedException(Response.Status.NOT_FOUND);
218         }
219
220         boolean isDataRoot = false;
221         URI initialNs = null;
222         if (SchemaPath.ROOT.equals(path)) {
223             isDataRoot = true;
224         } else {
225             path = path.getParent();
226             // FIXME: Add proper handling of reading root.
227         }
228         if (!schema.isAugmenting() && !(schema instanceof SchemaContext)) {
229             initialNs = schema.getQName().getNamespace();
230         }
231
232         final JsonWriter jsonWriter = JsonWriterFactory.createJsonWriter(outputWriter);
233         final NormalizedNodeStreamWriter jsonStreamWriter = JSONNormalizedNodeStreamWriter.createExclusiveWriter(
234                 JSONCodecFactory.getShared(context.getSchemaContext()), path, initialNs, jsonWriter);
235
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
240         // for error-info.
241         final NormalizedNodeStreamWriter streamWriter = new ForwardingNormalizedNodeStreamWriter() {
242             @Override
243             protected NormalizedNodeStreamWriter delegate() {
244                 return jsonStreamWriter;
245             }
246
247             @Override
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());
252                 } else {
253                     super.leafNode(name, value);
254                 }
255             }
256         };
257
258         final NormalizedNodeWriter nnWriter = NormalizedNodeWriter.forStreamWriter(streamWriter);
259         try {
260             if (isDataRoot) {
261                 writeDataRoot(outputWriter,nnWriter,(ContainerNode) data);
262             } else {
263                 if (data instanceof MapEntryNode) {
264                     data = ImmutableNodes.mapNodeBuilder(data.getNodeType()).withChild((MapEntryNode) data).build();
265                 }
266                 nnWriter.write(data);
267             }
268             nnWriter.flush();
269             outputWriter.flush();
270         } catch (final IOException e) {
271             LOG.warn("Error writing error response body", e);
272         }
273
274         try {
275             return outStream.toString(StandardCharsets.UTF_8.name());
276         } catch (UnsupportedEncodingException e) {
277             // Shouldn't happen
278             return "Failure encoding error response: " + e;
279         }
280     }
281
282     private static Object toXMLResponseBody(final NormalizedNodeContext errorsNode,
283                                             final DataNodeContainer errorsSchemaNode) {
284         final InstanceIdentifierContext<?> pathContext = errorsNode.getInstanceIdentifierContext();
285         final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
286
287         final XMLStreamWriter xmlWriter;
288         try {
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);
294         }
295         NormalizedNode<?, ?> data = errorsNode.getData();
296         SchemaPath schemaPath = pathContext.getSchemaNode().getPath();
297
298         boolean isDataRoot = false;
299         if (SchemaPath.ROOT.equals(schemaPath)) {
300             isDataRoot = true;
301         } else {
302             schemaPath = schemaPath.getParent();
303         }
304
305         final NormalizedNodeStreamWriter xmlStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter,
306                 pathContext.getSchemaContext(), schemaPath);
307
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
312         // for error-info.
313         final NormalizedNodeStreamWriter streamWriter = new ForwardingNormalizedNodeStreamWriter() {
314             @Override
315             protected NormalizedNodeStreamWriter delegate() {
316                 return xmlStreamWriter;
317             }
318
319             @Override
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();
323                     try {
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);
330                     }
331                 } else {
332                     super.leafNode(name, value);
333                 }
334             }
335         };
336
337         final NormalizedNodeWriter nnWriter = NormalizedNodeWriter.forStreamWriter(streamWriter);
338         try {
339             if (isDataRoot) {
340                 writeRootElement(xmlWriter, nnWriter, (ContainerNode) data);
341             } else {
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();
346                 }
347                 nnWriter.write(data);
348                 nnWriter.flush();
349             }
350         } catch (final IOException e) {
351             LOG.warn("Error writing error response body.", e);
352         }
353
354         try {
355             return outStream.toString(StandardCharsets.UTF_8.name());
356         } catch (UnsupportedEncodingException e) {
357             // Shouldn't happen
358             return "Failure encoding error response: " + e;
359         }
360     }
361
362     private static void writeRootElement(final XMLStreamWriter xmlWriter, final NormalizedNodeWriter nnWriter,
363                                          final ContainerNode data)
364             throws IOException {
365         try {
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);
370             }
371             nnWriter.flush();
372             xmlWriter.writeEndElement();
373             xmlWriter.flush();
374         } catch (final XMLStreamException e) {
375             Throwables.propagate(e);
376         }
377     }
378
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);
385             nnWriter.flush();
386         }
387     }
388 }