Cenralized handling of USER_ID header
[sdc/sdc-workflow-designer.git] / workflow-designer-be / src / main / java / org / onap / sdc / workflow / api / ExceptionsHandler.java
1 /*
2  * Copyright © 2018 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.onap.sdc.workflow.api;
18
19 import static org.springframework.http.HttpStatus.BAD_REQUEST;
20 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
21 import static org.springframework.http.HttpStatus.NOT_FOUND;
22 import static org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY;
23
24 import java.util.function.Function;
25 import org.apache.commons.lang3.exception.ExceptionUtils;
26 import org.apache.commons.text.RandomStringGenerator;
27 import org.onap.sdc.workflow.api.types.ErrorResponse;
28 import org.onap.sdc.workflow.api.types.UnexpectedErrorResponse;
29 import org.onap.sdc.workflow.services.exceptions.EntityNotFoundException;
30 import org.onap.sdc.workflow.services.exceptions.InvalidArtifactException;
31 import org.onap.sdc.workflow.services.exceptions.UniqueValueViolationException;
32 import org.onap.sdc.workflow.services.exceptions.VersionCreationException;
33 import org.onap.sdc.workflow.services.exceptions.VersionModificationException;
34 import org.onap.sdc.workflow.services.exceptions.VersionStateModificationException;
35 import org.onap.sdc.workflow.services.exceptions.VersionStatusModificationException;
36 import org.openecomp.sdc.logging.api.Logger;
37 import org.openecomp.sdc.logging.api.LoggerFactory;
38 import org.springframework.context.support.DefaultMessageSourceResolvable;
39 import org.springframework.http.HttpHeaders;
40 import org.springframework.http.HttpStatus;
41 import org.springframework.http.ResponseEntity;
42 import org.springframework.web.bind.MethodArgumentNotValidException;
43 import org.springframework.web.bind.ServletRequestBindingException;
44 import org.springframework.web.bind.annotation.ControllerAdvice;
45 import org.springframework.web.bind.annotation.ExceptionHandler;
46 import org.springframework.web.bind.annotation.RestController;
47 import org.springframework.web.context.request.WebRequest;
48 import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
49
50 @ControllerAdvice
51 @RestController
52 public class ExceptionsHandler extends ResponseEntityExceptionHandler {
53
54     private static final Logger LOG = LoggerFactory.getLogger(ExceptionsHandler.class);
55
56     private static final String LOG_MSG = "Exception was mapped to {} response";
57     private static final String UNEXPECTED_ERROR_MSG = "Something bad happened. Please contact support with code %s";
58     private static final RandomStringGenerator CODE_GENERATOR =
59             new RandomStringGenerator.Builder().withinRange('A', 'Z').build();
60     private static final int CODE_LENGTH = 8;
61
62     private static final Function<Exception, UnexpectedErrorResponse> UNEXPECTED_EXCEPTION_MAPPER =
63             isDevInfoDisabled()
64                     ? e -> new UnexpectedErrorResponse(getUnexpectedErrorMessage())
65                     : e -> new UnexpectedErrorResponse(getUnexpectedErrorMessage(), ExceptionUtils.getStackTrace(e));
66
67     @Override
68     public ResponseEntity<Object> handleServletRequestBindingException(ServletRequestBindingException ex,
69             HttpHeaders headers, HttpStatus status, WebRequest request) {
70         LOG.debug(LOG_MSG, BAD_REQUEST, ex);
71         // Convert Spring-generated binding exceptions into the format of an application message
72         return new ResponseEntity<>(new ErrorResponse(ex.getMessage()), BAD_REQUEST);
73     }
74
75     @Override
76     protected final ResponseEntity<Object> handleMethodArgumentNotValid(final MethodArgumentNotValidException exception,
77             final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
78         LOG.debug(LOG_MSG, BAD_REQUEST, exception);
79         String errorMsg = exception.getBindingResult().getFieldErrors().stream()
80                                   .map(DefaultMessageSourceResolvable::getDefaultMessage).findFirst()
81                                   .orElse(exception.getMessage());
82         return new ResponseEntity<>(new ErrorResponse(errorMsg), BAD_REQUEST);
83     }
84
85     @ExceptionHandler(EntityNotFoundException.class)
86     public final ResponseEntity<ErrorResponse> handleNotFoundException(Exception exception) {
87         LOG.debug(LOG_MSG, NOT_FOUND, exception);
88         return new ResponseEntity<>(new ErrorResponse(exception.getMessage()), NOT_FOUND);
89     }
90
91     @ExceptionHandler(
92             {InvalidArtifactException.class, VersionCreationException.class, VersionModificationException.class,
93                     VersionStateModificationException.class, VersionStatusModificationException.class,
94                     UniqueValueViolationException.class})
95     public final ResponseEntity<ErrorResponse> handleUnprocessableEntityException(Exception exception) {
96         LOG.debug(LOG_MSG, UNPROCESSABLE_ENTITY, exception);
97         return new ResponseEntity<>(new ErrorResponse(exception.getMessage()), UNPROCESSABLE_ENTITY);
98     }
99
100     @ExceptionHandler(Exception.class)
101     public final ResponseEntity<UnexpectedErrorResponse> handleUnexpectedException(Exception exception) {
102         UnexpectedErrorResponse response = UNEXPECTED_EXCEPTION_MAPPER.apply(exception);
103         LOG.error(response.getMessage(), exception);
104         return new ResponseEntity<>(response, INTERNAL_SERVER_ERROR);
105     }
106
107     private static boolean isDevInfoDisabled() {
108         return Boolean.FALSE.toString().equalsIgnoreCase(System.getProperty("errors.includeDevInfo"));
109     }
110
111     private static String getUnexpectedErrorMessage() {
112         return String.format(UNEXPECTED_ERROR_MSG, CODE_GENERATOR.generate(CODE_LENGTH));
113     }
114 }