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