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