Use versioning, zusammen and session libs from sdc-common-be
[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.VersionStateModificationMissingArtifactException;
36 import org.onap.sdc.workflow.services.exceptions.VersionStatusModificationException;
37 import org.onap.sdc.workflow.services.exceptions.WorkflowModificationException;
38 import org.openecomp.sdc.logging.api.Logger;
39 import org.openecomp.sdc.logging.api.LoggerFactory;
40 import org.springframework.context.support.DefaultMessageSourceResolvable;
41 import org.springframework.http.HttpHeaders;
42 import org.springframework.http.HttpStatus;
43 import org.springframework.http.ResponseEntity;
44 import org.springframework.web.bind.MethodArgumentNotValidException;
45 import org.springframework.web.bind.ServletRequestBindingException;
46 import org.springframework.web.bind.annotation.ControllerAdvice;
47 import org.springframework.web.bind.annotation.ExceptionHandler;
48 import org.springframework.web.bind.annotation.RestController;
49 import org.springframework.web.context.request.WebRequest;
50 import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
51
52 @ControllerAdvice
53 @RestController
54 public class ExceptionsHandler extends ResponseEntityExceptionHandler {
55
56     private static final Logger LOG = LoggerFactory.getLogger(ExceptionsHandler.class);
57
58     private static final String LOG_MSG = "Exception was mapped to {} response";
59     private static final String UNEXPECTED_ERROR_MSG = "Something bad happened. Please contact support with code %s";
60     private static final RandomStringGenerator CODE_GENERATOR =
61             new RandomStringGenerator.Builder().withinRange('A', 'Z').build();
62     private static final int CODE_LENGTH = 8;
63
64     private static final Function<Exception, UnexpectedErrorResponse> UNEXPECTED_EXCEPTION_MAPPER =
65             isDevInfoDisabled()
66                     ? e -> new UnexpectedErrorResponse(getUnexpectedErrorMessage())
67                     : e -> new UnexpectedErrorResponse(getUnexpectedErrorMessage(), ExceptionUtils.getStackTrace(e));
68
69     @Override
70     public ResponseEntity<Object> handleServletRequestBindingException(ServletRequestBindingException ex,
71             HttpHeaders headers, HttpStatus status, WebRequest request) {
72         LOG.debug(LOG_MSG, BAD_REQUEST, ex);
73         // Convert Spring-generated binding exceptions into the format of an application message
74         return new ResponseEntity<>(new ErrorResponse(ex.getMessage()), BAD_REQUEST);
75     }
76
77     @Override
78     protected final ResponseEntity<Object> handleMethodArgumentNotValid(final MethodArgumentNotValidException exception,
79             final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
80         LOG.debug(LOG_MSG, BAD_REQUEST, exception);
81         String errorMsg = exception.getBindingResult().getFieldErrors().stream()
82                                   .map(DefaultMessageSourceResolvable::getDefaultMessage).findFirst()
83                                   .orElse(exception.getMessage());
84         return new ResponseEntity<>(new ErrorResponse(errorMsg), BAD_REQUEST);
85     }
86
87     @ExceptionHandler(EntityNotFoundException.class)
88     public final ResponseEntity<ErrorResponse> handleNotFoundException(Exception exception) {
89         LOG.debug(LOG_MSG, NOT_FOUND, exception);
90         return new ResponseEntity<>(new ErrorResponse(exception.getMessage()), NOT_FOUND);
91     }
92
93     @ExceptionHandler(
94             {InvalidArtifactException.class, VersionCreationException.class, VersionModificationException.class,
95                     VersionStateModificationException.class,
96                     VersionStateModificationMissingArtifactException.class,
97                     VersionStatusModificationException.class,
98                     UniqueValueViolationException.class,
99                     WorkflowModificationException.class})
100     public final ResponseEntity<ErrorResponse> handleUnprocessableEntityException(Exception exception) {
101         LOG.debug(LOG_MSG, UNPROCESSABLE_ENTITY, exception);
102         return new ResponseEntity<>(new ErrorResponse(exception.getMessage()), UNPROCESSABLE_ENTITY);
103     }
104
105     @ExceptionHandler(Exception.class)
106     public final ResponseEntity<UnexpectedErrorResponse> handleUnexpectedException(Exception exception) {
107         UnexpectedErrorResponse response = UNEXPECTED_EXCEPTION_MAPPER.apply(exception);
108         LOG.error(response.getMessage(), exception);
109         return new ResponseEntity<>(response, INTERNAL_SERVER_ERROR);
110     }
111
112     private static boolean isDevInfoDisabled() {
113         return Boolean.FALSE.toString().equalsIgnoreCase(System.getProperty("errors.includeDevInfo"));
114     }
115
116     private static String getUnexpectedErrorMessage() {
117         return String.format(UNEXPECTED_ERROR_MSG, CODE_GENERATOR.generate(CODE_LENGTH));
118     }
119 }