Add DatabindContext and its wiring
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / nb / rfc8040 / jersey / providers / errors / RestconfDocumentedExceptionMapper.java
1 /*
2  * Copyright © 2019 FRINX s.r.o. 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 package org.opendaylight.restconf.nb.rfc8040.jersey.providers.errors;
9
10 import static com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
12 import static org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.restconf.rev170126.$YangModuleInfoImpl.qnameOf;
13
14 import com.google.common.annotations.VisibleForTesting;
15 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
16 import java.io.ByteArrayOutputStream;
17 import java.io.IOException;
18 import java.io.OutputStreamWriter;
19 import java.nio.charset.StandardCharsets;
20 import java.util.Collections;
21 import java.util.LinkedHashSet;
22 import java.util.List;
23 import java.util.Optional;
24 import java.util.Set;
25 import java.util.stream.Collectors;
26 import javax.ws.rs.core.Context;
27 import javax.ws.rs.core.HttpHeaders;
28 import javax.ws.rs.core.MediaType;
29 import javax.ws.rs.core.Response;
30 import javax.ws.rs.core.Response.Status;
31 import javax.ws.rs.ext.ExceptionMapper;
32 import javax.ws.rs.ext.Provider;
33 import org.opendaylight.restconf.common.ErrorTags;
34 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
35 import org.opendaylight.restconf.common.errors.RestconfError;
36 import org.opendaylight.restconf.nb.rfc8040.MediaTypes;
37 import org.opendaylight.restconf.nb.rfc8040.databind.DatabindProvider;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.restconf.rev170126.errors.Errors;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.restconf.rev170126.errors.errors.Error;
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.schema.ContainerNode;
43 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
44 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
46 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
47 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 /**
52  *  Mapper that is responsible for transformation of thrown {@link RestconfDocumentedException} to errors structure
53  *  that is modelled by RESTCONF module (see section 8 of RFC-8040).
54  */
55 @Provider
56 public final class RestconfDocumentedExceptionMapper implements ExceptionMapper<RestconfDocumentedException> {
57     private static final Logger LOG = LoggerFactory.getLogger(RestconfDocumentedExceptionMapper.class);
58     private static final MediaType DEFAULT_MEDIA_TYPE = MediaType.APPLICATION_JSON_TYPE;
59     private static final Status DEFAULT_STATUS_CODE = Status.INTERNAL_SERVER_ERROR;
60     private static final QName ERROR_TYPE_QNAME = qnameOf("error-type");
61     private static final QName ERROR_TAG_QNAME = qnameOf("error-tag");
62     private static final QName ERROR_APP_TAG_QNAME = qnameOf("error-app-tag");
63     private static final QName ERROR_MESSAGE_QNAME = qnameOf("error-message");
64     private static final QName ERROR_PATH_QNAME = qnameOf("error-path");
65     static final QName ERROR_INFO_QNAME = qnameOf("error-info");
66
67     private final DatabindProvider databindProvider;
68
69     @Context
70     private HttpHeaders headers;
71
72     /**
73      * Initialization of the exception mapper.
74      *
75      * @param databindProvider A {@link DatabindProvider}
76      */
77     public RestconfDocumentedExceptionMapper(final DatabindProvider databindProvider) {
78         this.databindProvider = requireNonNull(databindProvider);
79     }
80
81     @Override
82     @SuppressFBWarnings(value = "SLF4J_MANUALLY_PROVIDED_MESSAGE", justification = "In the debug messages "
83             + "we don't to have full stack trace - getMessage(..) method provides finer output.")
84     public Response toResponse(final RestconfDocumentedException exception) {
85         LOG.debug("Starting to map received exception to error response: {}", exception.getMessage());
86         final Status responseStatus = getResponseStatusCode(exception);
87         if (responseStatus != Response.Status.FORBIDDEN
88                 && responseStatus.getFamily() == Response.Status.Family.CLIENT_ERROR
89                 && exception.getErrors().isEmpty()) {
90             // There should be at least one error entry for 4xx errors except 409 according to RFC8040, but we do not
91             // have it. Issue a warning with the call trace so we can fix whoever was the originator.
92             LOG.warn("Input exception has a family of 4xx but does not contain any descriptive errors", exception);
93         }
94
95         final ContainerNode errorsContainer = buildErrorsContainer(exception);
96         final String serializedResponseBody;
97         final MediaType responseMediaType = transformToResponseMediaType(getSupportedMediaType());
98         if (MediaTypes.APPLICATION_YANG_DATA_JSON_TYPE.equals(responseMediaType)) {
99             serializedResponseBody = serializeErrorsContainerToJson(errorsContainer);
100         } else {
101             serializedResponseBody = serializeErrorsContainerToXml(errorsContainer);
102         }
103
104         final Response preparedResponse = Response.status(responseStatus)
105                 .type(responseMediaType)
106                 .entity(serializedResponseBody)
107                 .build();
108         LOG.debug("Exception {} has been successfully mapped to response: {}",
109                 exception.getMessage(), preparedResponse);
110         return preparedResponse;
111     }
112
113     /**
114      * Filling up of the errors container with data from input {@link RestconfDocumentedException}.
115      *
116      * @param exception Thrown exception.
117      * @return Built errors container.
118      */
119     private static ContainerNode buildErrorsContainer(final RestconfDocumentedException exception) {
120         return Builders.containerBuilder()
121             .withNodeIdentifier(NodeIdentifier.create(Errors.QNAME))
122             .withChild(Builders.unkeyedListBuilder()
123                 .withNodeIdentifier(NodeIdentifier.create(Error.QNAME))
124                 .withValue(exception.getErrors().stream()
125                     .map(RestconfDocumentedExceptionMapper::createErrorEntry)
126                     .collect(Collectors.toList()))
127                 .build())
128             .build();
129     }
130
131     /**
132      * Building of one error entry using provided {@link RestconfError}.
133      *
134      * @param restconfError Error details.
135      * @return Built list entry.
136      */
137     private static UnkeyedListEntryNode createErrorEntry(final RestconfError restconfError) {
138         // filling in mandatory leafs
139         final var entryBuilder = Builders.unkeyedListEntryBuilder()
140             .withNodeIdentifier(NodeIdentifier.create(Error.QNAME))
141             .withChild(ImmutableNodes.leafNode(ERROR_TYPE_QNAME, restconfError.getErrorType().elementBody()))
142             .withChild(ImmutableNodes.leafNode(ERROR_TAG_QNAME, restconfError.getErrorTag().elementBody()));
143
144         // filling in optional fields
145         if (restconfError.getErrorMessage() != null) {
146             entryBuilder.withChild(ImmutableNodes.leafNode(ERROR_MESSAGE_QNAME, restconfError.getErrorMessage()));
147         }
148         if (restconfError.getErrorAppTag() != null) {
149             entryBuilder.withChild(ImmutableNodes.leafNode(ERROR_APP_TAG_QNAME, restconfError.getErrorAppTag()));
150         }
151         if (restconfError.getErrorInfo() != null) {
152             // Oddly, error-info is defined as an empty container in the restconf yang. Apparently the
153             // intention is for implementors to define their own data content so we'll just treat it as a leaf
154             // with string data.
155             entryBuilder.withChild(ImmutableNodes.leafNode(ERROR_INFO_QNAME, restconfError.getErrorInfo()));
156         }
157
158         if (restconfError.getErrorPath() != null) {
159             entryBuilder.withChild(ImmutableNodes.leafNode(ERROR_PATH_QNAME, restconfError.getErrorPath()));
160         }
161         return entryBuilder.build();
162     }
163
164     /**
165      * Serialization of the errors container into JSON representation.
166      *
167      * @param errorsContainer To be serialized errors container.
168      * @return JSON representation of the errors container.
169      */
170     private String serializeErrorsContainerToJson(final ContainerNode errorsContainer) {
171         try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
172              OutputStreamWriter streamStreamWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
173         ) {
174             return writeNormalizedNode(errorsContainer, outputStream,
175                 new JsonStreamWriterWithDisabledValidation(databindProvider.currentContext(), streamStreamWriter));
176         } catch (IOException e) {
177             throw new IllegalStateException("Cannot close some of the output JSON writers", e);
178         }
179     }
180
181     /**
182      * Serialization of the errors container into XML representation.
183      *
184      * @param errorsContainer To be serialized errors container.
185      * @return XML representation of the errors container.
186      */
187     private String serializeErrorsContainerToXml(final ContainerNode errorsContainer) {
188         try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
189             return writeNormalizedNode(errorsContainer, outputStream,
190                 new XmlStreamWriterWithDisabledValidation(databindProvider.currentContext(), outputStream));
191         } catch (IOException e) {
192             throw new IllegalStateException("Cannot close some of the output XML writers", e);
193         }
194     }
195
196     private static String writeNormalizedNode(final NormalizedNode errorsContainer,
197             final ByteArrayOutputStream outputStream, final StreamWriterWithDisabledValidation streamWriter) {
198         try (NormalizedNodeWriter nnWriter = NormalizedNodeWriter.forStreamWriter(streamWriter)) {
199             nnWriter.write(errorsContainer);
200         } catch (IOException e) {
201             throw new IllegalStateException("Cannot write error response body", e);
202         }
203         return outputStream.toString(StandardCharsets.UTF_8);
204     }
205
206     /**
207      * Deriving of the status code from the thrown exception. At the first step, status code is tried to be read using
208      * {@link RestconfDocumentedException#getStatus()}. If it is {@code null}, status code will be derived from status
209      * codes appended to error entries (the first that will be found). If there are not any error entries,
210      * {@link RestconfDocumentedExceptionMapper#DEFAULT_STATUS_CODE} will be used.
211      *
212      * @param exception Thrown exception.
213      * @return Derived status code.
214      */
215     private static Status getResponseStatusCode(final RestconfDocumentedException exception) {
216         final Status status = exception.getStatus();
217         if (status != null) {
218             // status code that is specified directly as field in exception has the precedence over error entries
219             return status;
220         }
221
222         final List<RestconfError> errors = exception.getErrors();
223         if (errors.isEmpty()) {
224             // if the module, that thrown exception, doesn't specify status code, it is treated as internal
225             // server error
226             return DEFAULT_STATUS_CODE;
227         }
228
229         final Set<Status> allStatusCodesOfErrorEntries = errors.stream()
230                 .map(restconfError -> ErrorTags.statusOf(restconfError.getErrorTag()))
231                 // we would like to preserve iteration order in collected entries - hence usage of LinkedHashSet
232                 .collect(Collectors.toCollection(LinkedHashSet::new));
233         // choosing of the first status code from appended errors, if there are different status codes in error
234         // entries, we should create WARN message
235         if (allStatusCodesOfErrorEntries.size() > 1) {
236             LOG.warn("An unexpected error occurred during translation of exception {} to response: "
237                     + "Different status codes have been found in appended error entries: {}. The first error "
238                     + "entry status code is chosen for response.", exception, allStatusCodesOfErrorEntries);
239         }
240         return allStatusCodesOfErrorEntries.iterator().next();
241     }
242
243     /**
244      * Selection of media type that will be used for creation suffix of 'application/yang-data'. Selection criteria
245      * is described in RFC 8040, section 7.1. At the first step, accepted media-type is analyzed and only supported
246      * media-types are filtered out. If both XML and JSON media-types are accepted, JSON is selected as a default one
247      * used in RESTCONF. If accepted-media type is not specified, the media-type used in request is chosen only if it
248      * is supported one. If it is not supported or it is not specified, again, the default one (JSON) is selected.
249      *
250      * @return Media type.
251      */
252     private MediaType getSupportedMediaType() {
253         final Set<MediaType> acceptableAndSupportedMediaTypes = headers.getAcceptableMediaTypes().stream()
254                 .filter(RestconfDocumentedExceptionMapper::isCompatibleMediaType)
255                 .collect(Collectors.toSet());
256         if (acceptableAndSupportedMediaTypes.isEmpty()) {
257             // check content type of the request
258             final MediaType requestMediaType = headers.getMediaType();
259             return requestMediaType == null ? DEFAULT_MEDIA_TYPE
260                     : chooseMediaType(Collections.singletonList(requestMediaType)).orElseGet(() -> {
261                         LOG.warn("Request doesn't specify accepted media-types and the media-type '{}' used by "
262                                 + "request is not supported - using of default '{}' media-type.",
263                                 requestMediaType, DEFAULT_MEDIA_TYPE);
264                         return DEFAULT_MEDIA_TYPE;
265                     });
266         }
267
268         // at first step, fully specified types without any wildcards are considered (for example, application/json)
269         final List<MediaType> fullySpecifiedMediaTypes = acceptableAndSupportedMediaTypes.stream()
270                 .filter(mediaType -> !mediaType.isWildcardType() && !mediaType.isWildcardSubtype())
271                 .collect(Collectors.toList());
272         if (!fullySpecifiedMediaTypes.isEmpty()) {
273             return chooseAndCheckMediaType(fullySpecifiedMediaTypes);
274         }
275
276         // at the second step, only types with specified subtype are considered (for example, */json)
277         final List<MediaType> mediaTypesWithSpecifiedSubtypes = acceptableAndSupportedMediaTypes.stream()
278                 .filter(mediaType -> !mediaType.isWildcardSubtype())
279                 .collect(Collectors.toList());
280         if (!mediaTypesWithSpecifiedSubtypes.isEmpty()) {
281             return chooseAndCheckMediaType(mediaTypesWithSpecifiedSubtypes);
282         }
283
284         // at the third step, only types with specified parent are considered (for example, application/*)
285         final List<MediaType> mediaTypesWithSpecifiedParent = acceptableAndSupportedMediaTypes.stream()
286                 .filter(mediaType -> !mediaType.isWildcardType())
287                 .collect(Collectors.toList());
288         if (!mediaTypesWithSpecifiedParent.isEmpty()) {
289             return chooseAndCheckMediaType(mediaTypesWithSpecifiedParent);
290         }
291
292         // it must be fully-wildcard-ed type - */*
293         return DEFAULT_MEDIA_TYPE;
294     }
295
296     private static MediaType chooseAndCheckMediaType(final List<MediaType> options) {
297         final Optional<MediaType> mediaTypeOpt = chooseMediaType(options);
298         checkState(mediaTypeOpt.isPresent());
299         return mediaTypeOpt.get();
300     }
301
302     /**
303      * This method is responsible for choosing of he media type from multiple options. At the first step,
304      * JSON-compatible types are considered, then, if there are not any JSON types, XML types are considered. The first
305      * compatible media-type is chosen.
306      *
307      * @param options Supported media types.
308      * @return Selected one media type or {@link Optional#empty()} if none of the provided options are compatible with
309      *     RESTCONF.
310      */
311     private static Optional<MediaType> chooseMediaType(final List<MediaType> options) {
312         return options.stream()
313                 .filter(RestconfDocumentedExceptionMapper::isJsonCompatibleMediaType)
314                 .findFirst()
315                 .map(Optional::of)
316                 .orElse(options.stream()
317                         .filter(RestconfDocumentedExceptionMapper::isXmlCompatibleMediaType)
318                         .findFirst());
319     }
320
321     /**
322      * Mapping of JSON-compatible type to {@link RestconfDocumentedExceptionMapper#YANG_DATA_JSON_TYPE}
323      * or XML-compatible type to {@link RestconfDocumentedExceptionMapper#YANG_DATA_XML_TYPE}.
324      *
325      * @param mediaTypeBase Base media type from which the response media-type is built.
326      * @return Derived media type.
327      */
328     private static MediaType transformToResponseMediaType(final MediaType mediaTypeBase) {
329         if (isJsonCompatibleMediaType(mediaTypeBase)) {
330             return MediaTypes.APPLICATION_YANG_DATA_JSON_TYPE;
331         } else if (isXmlCompatibleMediaType(mediaTypeBase)) {
332             return MediaTypes.APPLICATION_YANG_DATA_XML_TYPE;
333         } else {
334             throw new IllegalStateException(String.format("Unexpected input media-type %s "
335                     + "- it should be JSON/XML compatible type.", mediaTypeBase));
336         }
337     }
338
339     private static boolean isCompatibleMediaType(final MediaType mediaType) {
340         return isJsonCompatibleMediaType(mediaType) || isXmlCompatibleMediaType(mediaType);
341     }
342
343     private static boolean isJsonCompatibleMediaType(final MediaType mediaType) {
344         return mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE)
345                 || mediaType.isCompatible(MediaTypes.APPLICATION_YANG_DATA_JSON_TYPE)
346                 || mediaType.isCompatible(MediaTypes.APPLICATION_YANG_PATCH_JSON_TYPE);
347     }
348
349     private static boolean isXmlCompatibleMediaType(final MediaType mediaType) {
350         return mediaType.isCompatible(MediaType.APPLICATION_XML_TYPE)
351                 || mediaType.isCompatible(MediaTypes.APPLICATION_YANG_DATA_XML_TYPE)
352                 || mediaType.isCompatible(MediaTypes.APPLICATION_YANG_PATCH_XML_TYPE);
353     }
354
355     /**
356      * Used just for testing purposes - simulation of HTTP headers with different accepted types and content type.
357      *
358      * @param httpHeaders Mocked HTTP headers.
359      */
360     @VisibleForTesting
361     void setHttpHeaders(final HttpHeaders httpHeaders) {
362         headers = httpHeaders;
363     }
364 }