2 * Copyright © 2016-2018 European Support Limited
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.openecomp.sdc.common.errors;
18 import com.fasterxml.jackson.databind.JsonMappingException;
19 import java.io.IOException;
20 import java.util.ArrayList;
21 import java.util.List;
24 import javax.servlet.http.HttpServletResponse;
25 import javax.validation.ConstraintViolation;
26 import javax.validation.ConstraintViolationException;
27 import javax.validation.Path;
28 import javax.ws.rs.core.MediaType;
29 import javax.ws.rs.core.Response;
30 import javax.ws.rs.core.Response.Status;
31 import javax.ws.rs.ext.ExceptionMapper;
32 import org.apache.commons.collections4.CollectionUtils;
33 import org.hibernate.validator.internal.engine.path.PathImpl;
34 import org.onap.sdc.security.RepresentationUtils;
35 import org.openecomp.core.utilities.file.FileUtils;
36 import org.openecomp.core.utilities.json.JsonUtil;
37 import org.openecomp.sdc.exception.NotAllowedSpecialCharsException;
38 import org.openecomp.sdc.exception.ResponseFormat;
39 import org.openecomp.sdc.exception.ServiceException;
40 import org.openecomp.sdc.logging.api.Logger;
41 import org.openecomp.sdc.logging.api.LoggerFactory;
43 public class DefaultExceptionMapper implements ExceptionMapper<Exception> {
45 private static final String ERROR_CODES_TO_RESPONSE_STATUS_MAPPING_FILE = "errorCodesToResponseStatusMapping.json";
46 @SuppressWarnings("unchecked")
47 private static final Map<String, String> ERROR_CODE_TO_RESPONSE_STATUS = FileUtils
48 .readViaInputStream(ERROR_CODES_TO_RESPONSE_STATUS_MAPPING_FILE, stream -> JsonUtil.json2Object(stream, Map.class));
49 private static final Logger LOGGER = LoggerFactory.getLogger(DefaultExceptionMapper.class);
52 public Response toResponse(Exception exception) {
54 if (exception instanceof CoreException) {
55 response = transform((CoreException) exception);
56 } else if (exception instanceof ConstraintViolationException) {
57 response = transform((ConstraintViolationException) exception);
58 } else if (exception instanceof JsonMappingException) {
59 response = transform((JsonMappingException) exception);
61 response = transform(exception);
63 List<Object> contentTypes = new ArrayList<>();
64 contentTypes.add(MediaType.APPLICATION_JSON);
65 response.getMetadata().put("Content-Type", contentTypes);
69 private Response transform(final CoreException coreException) {
70 final ErrorCode code = coreException.code();
71 LOGGER.error(code.message(), coreException);
72 if (coreException.code().category().equals(ErrorCategory.APPLICATION)) {
73 final Status errorStatus = Status.valueOf(ERROR_CODE_TO_RESPONSE_STATUS.get(code.id()));
74 if (List.of(Status.BAD_REQUEST, Status.FORBIDDEN, Status.NOT_FOUND, Status.INTERNAL_SERVER_ERROR).contains(errorStatus)) {
75 return buildResponse(errorStatus, code);
77 return buildResponse(Status.EXPECTATION_FAILED, code);
79 return buildResponse(Status.INTERNAL_SERVER_ERROR, code);
82 private Response buildResponse(final Status status, final ErrorCode code) {
83 return Response.status(status).entity(toEntity(status, code)).build();
86 private Response transform(ConstraintViolationException validationException) {
87 Set<ConstraintViolation<?>> constraintViolationSet = validationException.getConstraintViolations();
89 String fieldName = null;
90 if (CollectionUtils.isEmpty(constraintViolationSet)) {
91 message = validationException.getMessage();
93 // getting the first violation message for the output response.
94 ConstraintViolation<?> constraintViolation = constraintViolationSet.iterator().next();
95 message = constraintViolation.getMessage();
96 fieldName = getFieldName(constraintViolation.getPropertyPath());
98 ErrorCode validationErrorCode = new ValidationErrorBuilder(message, fieldName).build();
99 LOGGER.error(validationErrorCode.message(), validationException);
100 return buildResponse(Status.EXPECTATION_FAILED, validationErrorCode);
103 private Response transform(JsonMappingException jsonMappingException) {
104 ErrorCode jsonMappingErrorCode = new JsonMappingErrorBuilder().build();
105 LOGGER.error(jsonMappingErrorCode.message(), jsonMappingException);
106 return buildResponse(Status.EXPECTATION_FAILED, jsonMappingErrorCode);
109 private Response transform(Exception exception) {
110 ErrorCode errorCode = new GeneralErrorBuilder().build();
111 LOGGER.error(errorCode.message(), exception);
112 return buildResponse(Status.INTERNAL_SERVER_ERROR, errorCode);
115 private String getFieldName(Path propertyPath) {
116 return ((PathImpl) propertyPath).getLeafNode().toString();
119 private Object toEntity(final Status status, final ErrorCode code) {
120 return new ErrorCodeAndMessage(status, code);
123 public void writeToResponse(final NotAllowedSpecialCharsException e, final HttpServletResponse httpResponse) throws IOException {
124 final ResponseFormat responseFormat = new ResponseFormat(400);
125 responseFormat.setServiceException(new ServiceException(e.getErrorId(), e.getMessage(), new String[0]));
126 httpResponse.setStatus(responseFormat.getStatus());
127 httpResponse.setContentType("application/json");
128 httpResponse.setCharacterEncoding("UTF-8");
129 httpResponse.getWriter().write(RepresentationUtils.toRepresentation(responseFormat.getRequestError()));