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