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