2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.sdcrests.errors;
23 import org.codehaus.jackson.map.JsonMappingException;
24 import org.hibernate.validator.internal.engine.path.PathImpl;
25 import org.openecomp.sdc.logging.api.Logger;
26 import org.openecomp.sdc.logging.api.LoggerFactory;
27 import org.openecomp.core.utilities.CommonMethods;
28 import org.openecomp.core.utilities.file.FileUtils;
29 import org.openecomp.core.utilities.json.JsonUtil;
30 import org.openecomp.sdc.common.errors.CoreException;
31 import org.openecomp.sdc.common.errors.ErrorCategory;
32 import org.openecomp.sdc.common.errors.ErrorCode;
33 import org.openecomp.sdc.common.errors.ErrorCodeAndMessage;
34 import org.openecomp.sdc.common.errors.GeneralErrorBuilder;
35 import org.openecomp.sdc.common.errors.JsonMappingErrorBuilder;
36 import org.openecomp.sdc.common.errors.ValidationErrorBuilder;
38 import java.io.ByteArrayOutputStream;
40 import java.io.FileNotFoundException;
41 import java.io.FileOutputStream;
42 import java.io.IOException;
43 import java.io.OutputStream;
44 import java.io.PrintWriter;
45 import java.util.ArrayList;
46 import java.util.List;
49 import javax.validation.ConstraintViolation;
50 import javax.validation.ConstraintViolationException;
51 import javax.validation.Path;
52 import javax.ws.rs.core.MediaType;
53 import javax.ws.rs.ext.ExceptionMapper;
54 import javax.ws.rs.core.Response;
56 public class DefaultExceptionMapper implements ExceptionMapper<Exception> {
57 private static final String ERROR_CODES_TO_RESPONSE_STATUS_MAPPING_FILE =
58 "errorCodesToResponseStatusMapping.json";
59 private static Map<String, String> errorCodeToResponseStatus = JsonUtil
60 .json2Object(FileUtils.getFileInputStream(ERROR_CODES_TO_RESPONSE_STATUS_MAPPING_FILE),
62 private static Logger logger = (Logger) LoggerFactory.getLogger(DefaultExceptionMapper.class);
65 public Response toResponse(Exception exception) {
67 if (exception instanceof CoreException) {
68 response = transform(CoreException.class.cast(exception));
69 } else if (exception instanceof ConstraintViolationException) {
70 response = transform(ConstraintViolationException.class.cast(exception));
72 } else if (exception instanceof JsonMappingException) {
73 response = transform(JsonMappingException.class.cast(exception));
76 response = transform(exception);
80 writeStackTraceToFile(exception);
81 } catch (IOException e) {
84 List<Object> contentTypes = new ArrayList<>();
85 contentTypes.add(MediaType.APPLICATION_JSON);
86 response.getMetadata().put("Content-Type", contentTypes);
90 private Response transform(CoreException coreException) {
92 ErrorCode code = coreException.code();
93 logger.error(code.message(), coreException);
95 if (coreException.code().category().equals(ErrorCategory.APPLICATION)) {
96 if (Response.Status.NOT_FOUND.name().equals(errorCodeToResponseStatus.get(code.id()))) {
98 .status(Response.Status.NOT_FOUND)
99 .entity(toEntity(Response.Status.NOT_FOUND, code))
101 } else if (Response.Status.BAD_REQUEST.name()
102 .equals(errorCodeToResponseStatus.get(code.id()))) {
104 .status(Response.Status.BAD_REQUEST)
105 .entity(toEntity(Response.Status.BAD_REQUEST, code))
109 .status(Response.Status.EXPECTATION_FAILED)
110 .entity(toEntity(Response.Status.EXPECTATION_FAILED, code))
115 .status(Response.Status.INTERNAL_SERVER_ERROR)
116 .entity(toEntity(Response.Status.INTERNAL_SERVER_ERROR, code))
124 private Response transform(ConstraintViolationException validationException) {
125 Set<ConstraintViolation<?>> constraintViolationSet =
126 validationException.getConstraintViolations();
129 String fieldName = null;
130 if (!CommonMethods.isEmpty(constraintViolationSet)) {
131 // getting the first violation message for the output response.
132 ConstraintViolation<?> constraintViolation = constraintViolationSet.iterator().next();
133 message = constraintViolation.getMessage();
134 fieldName = getFieldName(constraintViolation.getPropertyPath());
137 message = validationException.getMessage();
140 ErrorCode validationErrorCode = new ValidationErrorBuilder(message, fieldName).build();
142 logger.error(validationErrorCode.message(), validationException);
144 .status(Response.Status.EXPECTATION_FAILED) //error 417
145 .entity(toEntity(Response.Status.EXPECTATION_FAILED, validationErrorCode))
149 private Response transform(JsonMappingException jsonMappingException) {
150 ErrorCode jsonMappingErrorCode = new JsonMappingErrorBuilder().build();
151 logger.error(jsonMappingErrorCode.message(), jsonMappingException);
153 .status(Response.Status.EXPECTATION_FAILED) //error 417
154 .entity(toEntity(Response.Status.EXPECTATION_FAILED, jsonMappingErrorCode))
158 private Response transform(Exception exception) {
159 ErrorCode generalErrorCode = new GeneralErrorBuilder(exception.getMessage()).build();
160 logger.error(generalErrorCode.message(), exception);
162 .status(Response.Status.INTERNAL_SERVER_ERROR)
163 .entity(toEntity(Response.Status.INTERNAL_SERVER_ERROR, generalErrorCode))
167 private String getFieldName(Path propertyPath) {
168 return ((PathImpl) propertyPath).getLeafNode().toString();
171 private Object toEntity(Response.Status status, ErrorCode code) {
172 return new ErrorCodeAndMessage(status, code);
175 private void writeStackTraceToFile(Exception exception) throws IOException {
176 File file = new File("stack_trace.txt");
177 OutputStream outputStream = new FileOutputStream(file);
180 file.createNewFile();
183 PrintWriter printWriter = new PrintWriter(file);
184 exception.printStackTrace(printWriter);