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