28917b9fb72a9033ebc3f6ffec37cd091433ae47
[sdc.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdcrests.errors;
22
23 import org.codehaus.jackson.map.JsonMappingException;
24 import org.hibernate.validator.internal.engine.path.PathImpl;
25 import org.openecomp.core.utilities.CommonMethods;
26 import org.openecomp.core.utilities.file.FileUtils;
27 import org.openecomp.core.utilities.json.JsonUtil;
28 import org.openecomp.sdc.common.errors.CoreException;
29 import org.openecomp.sdc.common.errors.ErrorCategory;
30 import org.openecomp.sdc.common.errors.ErrorCode;
31 import org.openecomp.sdc.common.errors.ErrorCodeAndMessage;
32 import org.openecomp.sdc.common.errors.GeneralErrorBuilder;
33 import org.openecomp.sdc.common.errors.JsonMappingErrorBuilder;
34 import org.openecomp.sdc.common.errors.ValidationErrorBuilder;
35 import org.openecomp.sdc.logging.api.Logger;
36 import org.openecomp.sdc.logging.api.LoggerFactory;
37
38 import javax.validation.ConstraintViolation;
39 import javax.validation.ConstraintViolationException;
40 import javax.validation.Path;
41 import javax.ws.rs.core.MediaType;
42 import javax.ws.rs.core.Response;
43 import javax.ws.rs.ext.ExceptionMapper;
44 import java.util.ArrayList;
45 import java.util.List;
46 import java.util.Map;
47 import java.util.Set;
48
49 public class DefaultExceptionMapper implements ExceptionMapper<Exception> {
50   private static final String ERROR_CODES_TO_RESPONSE_STATUS_MAPPING_FILE =
51       "errorCodesToResponseStatusMapping.json";
52   @SuppressWarnings("unchecked")
53   private static final Map<String, String> ERROR_CODE_TO_RESPONSE_STATUS =
54           FileUtils.readViaInputStream(ERROR_CODES_TO_RESPONSE_STATUS_MAPPING_FILE,
55               stream -> JsonUtil.json2Object(stream, Map.class));
56
57   private static final Logger LOGGER = (Logger) LoggerFactory.getLogger(DefaultExceptionMapper
58       .class);
59
60   @Override
61   public Response toResponse(Exception exception) {
62     Response response;
63     if (exception instanceof CoreException) {
64       response = transform(CoreException.class.cast(exception));
65     } else if (exception instanceof ConstraintViolationException) {
66       response = transform(ConstraintViolationException.class.cast(exception));
67
68     } else if (exception instanceof JsonMappingException) {
69       response = transform(JsonMappingException.class.cast(exception));
70
71     } else {
72       response = transform(exception);
73     }
74
75     List<Object> contentTypes = new ArrayList<>();
76     contentTypes.add(MediaType.APPLICATION_JSON);
77     response.getMetadata().put("Content-Type", contentTypes);
78     return response;
79   }
80
81   private Response transform(CoreException coreException) {
82     Response response;
83     ErrorCode code = coreException.code();
84     LOGGER.error(code.message(), coreException);
85
86     if (coreException.code().category().equals(ErrorCategory.APPLICATION)) {
87       if (Response.Status.NOT_FOUND.name().equals(ERROR_CODE_TO_RESPONSE_STATUS.get(code.id()))) {
88         response = Response
89             .status(Response.Status.NOT_FOUND)
90             .entity(toEntity(Response.Status.NOT_FOUND, code))
91             .build();
92       } else if (Response.Status.BAD_REQUEST.name()
93           .equals(ERROR_CODE_TO_RESPONSE_STATUS.get(code.id()))) {
94         response = Response
95             .status(Response.Status.BAD_REQUEST)
96             .entity(toEntity(Response.Status.BAD_REQUEST, code))
97             .build();
98       } else {
99         response = Response
100             .status(Response.Status.EXPECTATION_FAILED)
101             .entity(toEntity(Response.Status.EXPECTATION_FAILED, code))
102             .build();
103       }
104     } else {
105       response = Response
106           .status(Response.Status.INTERNAL_SERVER_ERROR)
107           .entity(toEntity(Response.Status.INTERNAL_SERVER_ERROR, code))
108           .build();
109     }
110
111
112     return response;
113   }
114
115   private Response transform(ConstraintViolationException validationException) {
116     Set<ConstraintViolation<?>> constraintViolationSet =
117         validationException.getConstraintViolations();
118     String message;
119
120     String fieldName = null;
121     if (!CommonMethods.isEmpty(constraintViolationSet)) {
122       // getting the first violation message for the output response.
123       ConstraintViolation<?> constraintViolation = constraintViolationSet.iterator().next();
124       message = constraintViolation.getMessage();
125       fieldName = getFieldName(constraintViolation.getPropertyPath());
126
127     } else {
128       message = validationException.getMessage();
129     }
130
131     ErrorCode validationErrorCode = new ValidationErrorBuilder(message, fieldName).build();
132
133     LOGGER.error(validationErrorCode.message(), validationException);
134     return Response
135         .status(Response.Status.EXPECTATION_FAILED) //error 417
136         .entity(toEntity(Response.Status.EXPECTATION_FAILED, validationErrorCode))
137         .build();
138   }
139
140   private Response transform(JsonMappingException jsonMappingException) {
141     ErrorCode jsonMappingErrorCode = new JsonMappingErrorBuilder().build();
142     LOGGER.error(jsonMappingErrorCode.message(), jsonMappingException);
143     return Response
144         .status(Response.Status.EXPECTATION_FAILED) //error 417
145         .entity(toEntity(Response.Status.EXPECTATION_FAILED, jsonMappingErrorCode))
146         .build();
147   }
148
149   private Response transform(Exception exception) {
150     ErrorCode generalErrorCode = new GeneralErrorBuilder(exception.getMessage()).build();
151     LOGGER.error(generalErrorCode.message(), exception);
152     return Response
153         .status(Response.Status.INTERNAL_SERVER_ERROR)
154         .entity(toEntity(Response.Status.INTERNAL_SERVER_ERROR, generalErrorCode))
155         .build();
156   }
157
158   private String getFieldName(Path propertyPath) {
159     return ((PathImpl) propertyPath).getLeafNode().toString();
160   }
161
162   private Object toEntity(Response.Status status, ErrorCode code) {
163     return new ErrorCodeAndMessage(status, code);
164   }
165 }