2f6d298f0170d372d46402b1eedf7c6b68dc462e
[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 Map<String, String> errorCodeToResponseStatus =
54           FileUtils.readViaInputStream(ERROR_CODES_TO_RESPONSE_STATUS_MAPPING_FILE,
55                   stream -> JsonUtil.json2Object(stream, Map.class));
56
57   private static Logger logger = (Logger) LoggerFactory.getLogger(DefaultExceptionMapper.class);
58
59   @Override
60   public Response toResponse(Exception exception) {
61     Response response;
62     if (exception instanceof CoreException) {
63       response = transform(CoreException.class.cast(exception));
64     } else if (exception instanceof ConstraintViolationException) {
65       response = transform(ConstraintViolationException.class.cast(exception));
66
67     } else if (exception instanceof JsonMappingException) {
68       response = transform(JsonMappingException.class.cast(exception));
69
70     } else {
71       response = transform(exception);
72     }
73
74     List<Object> contentTypes = new ArrayList<>();
75     contentTypes.add(MediaType.APPLICATION_JSON);
76     response.getMetadata().put("Content-Type", contentTypes);
77     return response;
78   }
79
80   private Response transform(CoreException coreException) {
81     Response response;
82     ErrorCode code = coreException.code();
83     logger.error(code.message(), coreException);
84
85     if (coreException.code().category().equals(ErrorCategory.APPLICATION)) {
86       if (Response.Status.NOT_FOUND.name().equals(errorCodeToResponseStatus.get(code.id()))) {
87         response = Response
88             .status(Response.Status.NOT_FOUND)
89             .entity(toEntity(Response.Status.NOT_FOUND, code))
90             .build();
91       } else if (Response.Status.BAD_REQUEST.name()
92           .equals(errorCodeToResponseStatus.get(code.id()))) {
93         response = Response
94             .status(Response.Status.BAD_REQUEST)
95             .entity(toEntity(Response.Status.BAD_REQUEST, code))
96             .build();
97       } else {
98         response = Response
99             .status(Response.Status.EXPECTATION_FAILED)
100             .entity(toEntity(Response.Status.EXPECTATION_FAILED, code))
101             .build();
102       }
103     } else {
104       response = Response
105           .status(Response.Status.INTERNAL_SERVER_ERROR)
106           .entity(toEntity(Response.Status.INTERNAL_SERVER_ERROR, code))
107           .build();
108     }
109
110
111     return response;
112   }
113
114   private Response transform(ConstraintViolationException validationException) {
115     Set<ConstraintViolation<?>> constraintViolationSet =
116         validationException.getConstraintViolations();
117     String message;
118
119     String fieldName = null;
120     if (!CommonMethods.isEmpty(constraintViolationSet)) {
121       // getting the first violation message for the output response.
122       ConstraintViolation<?> constraintViolation = constraintViolationSet.iterator().next();
123       message = constraintViolation.getMessage();
124       fieldName = getFieldName(constraintViolation.getPropertyPath());
125
126     } else {
127       message = validationException.getMessage();
128     }
129
130     ErrorCode validationErrorCode = new ValidationErrorBuilder(message, fieldName).build();
131
132     logger.error(validationErrorCode.message(), validationException);
133     return Response
134         .status(Response.Status.EXPECTATION_FAILED) //error 417
135         .entity(toEntity(Response.Status.EXPECTATION_FAILED, validationErrorCode))
136         .build();
137   }
138
139   private Response transform(JsonMappingException jsonMappingException) {
140     ErrorCode jsonMappingErrorCode = new JsonMappingErrorBuilder().build();
141     logger.error(jsonMappingErrorCode.message(), jsonMappingException);
142     return Response
143         .status(Response.Status.EXPECTATION_FAILED) //error 417
144         .entity(toEntity(Response.Status.EXPECTATION_FAILED, jsonMappingErrorCode))
145         .build();
146   }
147
148   private Response transform(Exception exception) {
149     ErrorCode generalErrorCode = new GeneralErrorBuilder(exception.getMessage()).build();
150     logger.error(generalErrorCode.message(), exception);
151     return Response
152         .status(Response.Status.INTERNAL_SERVER_ERROR)
153         .entity(toEntity(Response.Status.INTERNAL_SERVER_ERROR, generalErrorCode))
154         .build();
155   }
156
157   private String getFieldName(Path propertyPath) {
158     return ((PathImpl) propertyPath).getLeafNode().toString();
159   }
160
161   private Object toEntity(Response.Status status, ErrorCode code) {
162     return new ErrorCodeAndMessage(status, code);
163   }
164 }