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