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