0546180575d0940b1dd5d375126ed784f4d87bfe
[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.ext.ExceptionMapper;
29 import org.apache.commons.collections4.CollectionUtils;
30 import org.hibernate.validator.internal.engine.path.PathImpl;
31 import org.openecomp.core.utilities.file.FileUtils;
32 import org.openecomp.core.utilities.json.JsonUtil;
33 import org.openecomp.sdc.common.errors.CoreException;
34 import org.openecomp.sdc.common.errors.ErrorCategory;
35 import org.openecomp.sdc.common.errors.ErrorCode;
36 import org.openecomp.sdc.common.errors.ErrorCodeAndMessage;
37 import org.openecomp.sdc.common.errors.GeneralErrorBuilder;
38 import org.openecomp.sdc.common.errors.JsonMappingErrorBuilder;
39 import org.openecomp.sdc.common.errors.ValidationErrorBuilder;
40 import org.openecomp.sdc.logging.api.Logger;
41 import org.openecomp.sdc.logging.api.LoggerFactory;
42
43 public class DefaultExceptionMapper implements ExceptionMapper<Exception> {
44
45     private static final String ERROR_CODES_TO_RESPONSE_STATUS_MAPPING_FILE = "errorCodesToResponseStatusMapping.json";
46     @SuppressWarnings("unchecked")
47     private static final Map<String, String> ERROR_CODE_TO_RESPONSE_STATUS = FileUtils
48         .readViaInputStream(ERROR_CODES_TO_RESPONSE_STATUS_MAPPING_FILE, stream -> JsonUtil.json2Object(stream, Map.class));
49     private static final Logger LOGGER = LoggerFactory.getLogger(DefaultExceptionMapper.class);
50
51     @Override
52     public Response toResponse(Exception exception) {
53         Response response;
54         if (exception instanceof CoreException) {
55             response = transform(CoreException.class.cast(exception));
56         } else if (exception instanceof ConstraintViolationException) {
57             response = transform(ConstraintViolationException.class.cast(exception));
58         } else if (exception instanceof JsonMappingException) {
59             response = transform(JsonMappingException.class.cast(exception));
60         } else {
61             response = transform(exception);
62         }
63         List<Object> contentTypes = new ArrayList<>();
64         contentTypes.add(MediaType.APPLICATION_JSON);
65         response.getMetadata().put("Content-Type", contentTypes);
66         return response;
67     }
68
69     private Response transform(CoreException coreException) {
70         Response response;
71         ErrorCode code = coreException.code();
72         LOGGER.error(code.message(), coreException);
73         if (coreException.code().category().equals(ErrorCategory.APPLICATION)) {
74             if (Response.Status.NOT_FOUND.name().equals(ERROR_CODE_TO_RESPONSE_STATUS.get(code.id()))) {
75                 response = Response.status(Response.Status.NOT_FOUND).entity(toEntity(Response.Status.NOT_FOUND, code)).build();
76             } else if (Response.Status.BAD_REQUEST.name().equals(ERROR_CODE_TO_RESPONSE_STATUS.get(code.id()))) {
77                 response = Response.status(Response.Status.BAD_REQUEST).entity(toEntity(Response.Status.BAD_REQUEST, code)).build();
78             } else {
79                 response = Response.status(Response.Status.EXPECTATION_FAILED).entity(toEntity(Response.Status.EXPECTATION_FAILED, code)).build();
80             }
81         } else {
82             response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(toEntity(Response.Status.INTERNAL_SERVER_ERROR, code)).build();
83         }
84         return response;
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 Response.status(Response.Status.EXPECTATION_FAILED) //error 417
102             .entity(toEntity(Response.Status.EXPECTATION_FAILED, validationErrorCode)).build();
103     }
104
105     private Response transform(JsonMappingException jsonMappingException) {
106         ErrorCode jsonMappingErrorCode = new JsonMappingErrorBuilder().build();
107         LOGGER.error(jsonMappingErrorCode.message(), jsonMappingException);
108         return Response.status(Response.Status.EXPECTATION_FAILED) //error 417
109             .entity(toEntity(Response.Status.EXPECTATION_FAILED, jsonMappingErrorCode)).build();
110     }
111
112     private Response transform(Exception exception) {
113         ErrorCode errorCode = new GeneralErrorBuilder().build();
114         LOGGER.error(errorCode.message(), exception);
115         return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(toEntity(Response.Status.INTERNAL_SERVER_ERROR, errorCode)).build();
116     }
117
118     private String getFieldName(Path propertyPath) {
119         return ((PathImpl) propertyPath).getLeafNode().toString();
120     }
121
122     private Object toEntity(Response.Status status, ErrorCode code) {
123         return new ErrorCodeAndMessage(status, code);
124     }
125 }