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