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