Onboarding upload control
[sdc.git] / openecomp-be / api / openecomp-sdc-rest-webapp / openecomp-sdc-common-rest / src / main / java / org / openecomp / sdcrests / errors / DefaultExceptionMapper.java
1 /*
2  * Copyright © 2016-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 package org.openecomp.sdcrests.errors;
17
18 import com.fasterxml.jackson.databind.JsonMappingException;
19 import java.util.ArrayList;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.Set;
23 import javax.validation.ConstraintViolation;
24 import javax.validation.ConstraintViolationException;
25 import javax.validation.Path;
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 org.apache.commons.collections4.CollectionUtils;
31 import org.hibernate.validator.internal.engine.path.PathImpl;
32 import org.openecomp.core.utilities.file.FileUtils;
33 import org.openecomp.core.utilities.json.JsonUtil;
34 import org.openecomp.sdc.common.errors.CoreException;
35 import org.openecomp.sdc.common.errors.ErrorCategory;
36 import org.openecomp.sdc.common.errors.ErrorCode;
37 import org.openecomp.sdc.common.errors.ErrorCodeAndMessage;
38 import org.openecomp.sdc.common.errors.GeneralErrorBuilder;
39 import org.openecomp.sdc.common.errors.JsonMappingErrorBuilder;
40 import org.openecomp.sdc.common.errors.ValidationErrorBuilder;
41 import org.openecomp.sdc.logging.api.Logger;
42 import org.openecomp.sdc.logging.api.LoggerFactory;
43
44 public class DefaultExceptionMapper implements ExceptionMapper<Exception> {
45
46     private static final String ERROR_CODES_TO_RESPONSE_STATUS_MAPPING_FILE = "errorCodesToResponseStatusMapping.json";
47     @SuppressWarnings("unchecked")
48     private static final Map<String, String> ERROR_CODE_TO_RESPONSE_STATUS = FileUtils
49         .readViaInputStream(ERROR_CODES_TO_RESPONSE_STATUS_MAPPING_FILE, stream -> JsonUtil.json2Object(stream, Map.class));
50     private static final Logger LOGGER = LoggerFactory.getLogger(DefaultExceptionMapper.class);
51
52     @Override
53     public Response toResponse(Exception exception) {
54         Response response;
55         if (exception instanceof CoreException) {
56             response = transform((CoreException) exception);
57         } else if (exception instanceof ConstraintViolationException) {
58             response = transform((ConstraintViolationException) exception);
59         } else if (exception instanceof JsonMappingException) {
60             response = transform((JsonMappingException) exception);
61         } else {
62             response = transform(exception);
63         }
64         List<Object> contentTypes = new ArrayList<>();
65         contentTypes.add(MediaType.APPLICATION_JSON);
66         response.getMetadata().put("Content-Type", contentTypes);
67         return response;
68     }
69
70     private Response transform(final CoreException coreException) {
71         final ErrorCode code = coreException.code();
72         LOGGER.error(code.message(), coreException);
73         if (coreException.code().category().equals(ErrorCategory.APPLICATION)) {
74             final Status errorStatus = Status.valueOf(ERROR_CODE_TO_RESPONSE_STATUS.get(code.id()));
75             if (List.of(Status.BAD_REQUEST, Status.FORBIDDEN, Status.NOT_FOUND, Status.INTERNAL_SERVER_ERROR).contains(errorStatus)) {
76                 return buildResponse(errorStatus, code);
77             }
78             return buildResponse(Status.EXPECTATION_FAILED, code);
79         }
80         return buildResponse(Status.INTERNAL_SERVER_ERROR, code);
81     }
82
83     private Response buildResponse(Status notFound, ErrorCode code) {
84         return Response.status(notFound).entity(toEntity(notFound, code)).build();
85     }
86
87     private Response transform(ConstraintViolationException validationException) {
88         Set<ConstraintViolation<?>> constraintViolationSet = validationException.getConstraintViolations();
89         String message;
90         String fieldName = null;
91         if (CollectionUtils.isEmpty(constraintViolationSet)) {
92             message = validationException.getMessage();
93         } else {
94             // getting the first violation message for the output response.
95             ConstraintViolation<?> constraintViolation = constraintViolationSet.iterator().next();
96             message = constraintViolation.getMessage();
97             fieldName = getFieldName(constraintViolation.getPropertyPath());
98         }
99         ErrorCode validationErrorCode = new ValidationErrorBuilder(message, fieldName).build();
100         LOGGER.error(validationErrorCode.message(), validationException);
101         return buildResponse(Status.EXPECTATION_FAILED, validationErrorCode);
102     }
103
104     private Response transform(JsonMappingException jsonMappingException) {
105         ErrorCode jsonMappingErrorCode = new JsonMappingErrorBuilder().build();
106         LOGGER.error(jsonMappingErrorCode.message(), jsonMappingException);
107         return buildResponse(Status.EXPECTATION_FAILED, jsonMappingErrorCode);
108     }
109
110     private Response transform(Exception exception) {
111         ErrorCode errorCode = new GeneralErrorBuilder().build();
112         LOGGER.error(errorCode.message(), exception);
113         return buildResponse(Status.INTERNAL_SERVER_ERROR, errorCode);
114     }
115
116     private String getFieldName(Path propertyPath) {
117         return ((PathImpl) propertyPath).getLeafNode().toString();
118     }
119
120     private Object toEntity(final Status status, final ErrorCode code) {
121         return new ErrorCodeAndMessage(status, code);
122     }
123 }