push addional code
[sdc.git] / openecomp-be / api / openecomp-sdc-rest-webapp / openecomp-sdc-common-rest / src / main / java / org / openecomp / sdcrests / errors / DefaultExceptionMapper.java
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.slf4j.LoggerFactory;
36
37 import java.util.ArrayList;
38 import java.util.List;
39 import java.util.Map;
40 import java.util.Set;
41 import javax.validation.ConstraintViolation;
42 import javax.validation.ConstraintViolationException;
43 import javax.validation.Path;
44 import javax.ws.rs.core.MediaType;
45 import javax.ws.rs.core.Response;
46 import javax.ws.rs.ext.ExceptionMapper;
47
48 public class DefaultExceptionMapper implements ExceptionMapper<Exception> {
49   private static final String ERROR_CODES_TO_RESPONSE_STATUS_MAPPING_FILE =
50       "errorCodesToResponseStatusMapping.json";
51   private static Map<String, String> errorCodeToResponseStatus = JsonUtil
52       .json2Object(FileUtils.getFileInputStream(ERROR_CODES_TO_RESPONSE_STATUS_MAPPING_FILE),
53           Map.class);
54   private static org.slf4j.Logger logger = LoggerFactory.getLogger(DefaultExceptionMapper.class);
55
56   @Override
57   public Response toResponse(Exception e0) {
58     Response response;
59     if (e0 instanceof CoreException) {
60       response = transform(CoreException.class.cast(e0));
61     } else if (e0 instanceof ConstraintViolationException) {
62       response = transform(ConstraintViolationException.class.cast(e0));
63
64     } else if (e0 instanceof JsonMappingException) {
65       response = transform(JsonMappingException.class.cast(e0));
66
67     } else {
68       response = transform(e0);
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(errorCodeToResponseStatus.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(errorCodeToResponseStatus.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
137   private Response transform(JsonMappingException jsonMappingException) {
138     ErrorCode jsonMappingErrorCode = new JsonMappingErrorBuilder().build();
139     logger.error(jsonMappingErrorCode.message(), jsonMappingException);
140     return Response
141         .status(Response.Status.EXPECTATION_FAILED) //error 417
142         .entity(toEntity(Response.Status.EXPECTATION_FAILED, jsonMappingErrorCode))
143         .build();
144   }
145
146   private Response transform(Exception e0) {
147     ErrorCode generalErrorCode = new GeneralErrorBuilder(e0.getMessage()).build();
148     logger.error(generalErrorCode.message(), e0);
149     return Response
150         .status(Response.Status.INTERNAL_SERVER_ERROR)
151         .entity(toEntity(Response.Status.INTERNAL_SERVER_ERROR, generalErrorCode))
152         .build();
153   }
154
155   private String getFieldName(Path propertyPath) {
156     return ((PathImpl) propertyPath).getLeafNode().toString();
157   }
158
159   private Object toEntity(Response.Status status, ErrorCode code) {
160     return new ErrorCodeAndMessage(status, code);
161   }
162
163 }