f46d19be1cb80411cb98f5825c877610d4f84d4d
[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 LOGGER = LoggerFactory.getLogger(ExceptionsHandler.class);
55     private static final String LOG_MSG = "Exception was mapped to {} response";
56     private static final String UNEXPECTED_ERROR_MSG = "Something bad happened. Please contact support with code %s";
57     private static final RandomStringGenerator CODE_GENERATOR =
58             new RandomStringGenerator.Builder().withinRange('A', 'Z').build();
59     private static final int CODE_LENGTH = 8;
60
61     private static final Function<Exception, UnexpectedErrorResponse> UNEXPECTED_EXCEPTION_MAPPER =
62             isDevInfoDisabled()
63                     ? e -> new UnexpectedErrorResponse(getUnexpectedErrorMessage())
64                     : e -> new UnexpectedErrorResponse(getUnexpectedErrorMessage(), ExceptionUtils.getStackTrace(e));
65
66     @Override
67     public ResponseEntity<Object> handleServletRequestBindingException(ServletRequestBindingException ex,
68             HttpHeaders headers, HttpStatus status, WebRequest request) {
69         //For missing header exceptions
70         LOGGER.debug(LOG_MSG, BAD_REQUEST, ex);
71         return new ResponseEntity<>(new ErrorResponse(ex.getMessage()), BAD_REQUEST);
72     }
73
74     @Override
75     protected final ResponseEntity<Object> handleMethodArgumentNotValid(final MethodArgumentNotValidException exception,
76             final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
77         LOGGER.debug(LOG_MSG, BAD_REQUEST, exception);
78         String errorMsg = exception.getBindingResult().getFieldErrors().stream()
79                                   .map(DefaultMessageSourceResolvable::getDefaultMessage).findFirst()
80                                   .orElse(exception.getMessage());
81         return new ResponseEntity<>(new ErrorResponse(errorMsg), BAD_REQUEST);
82     }
83
84     @ExceptionHandler(EntityNotFoundException.class)
85     public final ResponseEntity<ErrorResponse> handleNotFoundException(Exception exception) {
86         LOGGER.debug(LOG_MSG, NOT_FOUND, exception);
87         return new ResponseEntity<>(new ErrorResponse(exception.getMessage()), NOT_FOUND);
88     }
89
90     @ExceptionHandler(
91             {InvalidArtifactException.class, VersionCreationException.class, VersionModificationException.class,
92                     VersionStateModificationException.class, VersionStatusModificationException.class,
93                     UniqueValueViolationException.class})
94     public final ResponseEntity<ErrorResponse> handleUnprocessableEntityException(Exception exception) {
95         LOGGER.debug(LOG_MSG, UNPROCESSABLE_ENTITY, exception);
96         return new ResponseEntity<>(new ErrorResponse(exception.getMessage()), UNPROCESSABLE_ENTITY);
97     }
98
99     @ExceptionHandler(Exception.class)
100     public final ResponseEntity<UnexpectedErrorResponse> handleUnexpectedException(Exception exception) {
101         UnexpectedErrorResponse response = UNEXPECTED_EXCEPTION_MAPPER.apply(exception);
102         LOGGER.error(response.getMessage(), exception);
103         return new ResponseEntity<>(response, INTERNAL_SERVER_ERROR);
104     }
105
106     private static boolean isDevInfoDisabled() {
107         return Boolean.FALSE.toString().equalsIgnoreCase(System.getProperty("errors.includeDevInfo"));
108     }
109
110     private static String getUnexpectedErrorMessage() {
111         return String.format(UNEXPECTED_ERROR_MSG, CODE_GENERATOR.generate(CODE_LENGTH));
112     }
113 }