aboutsummaryrefslogtreecommitdiffstats
path: root/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/errors/DefaultExceptionMapper.java
blob: af772685997f935e7b186c49eb32532053451611 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.sdcrests.errors;

import org.codehaus.jackson.map.JsonMappingException;
import org.hibernate.validator.internal.engine.path.PathImpl;
import org.openecomp.sdc.logging.api.Logger;
import org.openecomp.sdc.logging.api.LoggerFactory;
import org.openecomp.core.utilities.CommonMethods;
import org.openecomp.core.utilities.file.FileUtils;
import org.openecomp.core.utilities.json.JsonUtil;
import org.openecomp.sdc.common.errors.CoreException;
import org.openecomp.sdc.common.errors.ErrorCategory;
import org.openecomp.sdc.common.errors.ErrorCode;
import org.openecomp.sdc.common.errors.ErrorCodeAndMessage;
import org.openecomp.sdc.common.errors.GeneralErrorBuilder;
import org.openecomp.sdc.common.errors.JsonMappingErrorBuilder;
import org.openecomp.sdc.common.errors.ValidationErrorBuilder;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.core.Response;

public class DefaultExceptionMapper implements ExceptionMapper<Exception> {
  private static final String ERROR_CODES_TO_RESPONSE_STATUS_MAPPING_FILE =
      "errorCodesToResponseStatusMapping.json";
  private static Map<String, String> errorCodeToResponseStatus = JsonUtil
      .json2Object(FileUtils.getFileInputStream(ERROR_CODES_TO_RESPONSE_STATUS_MAPPING_FILE),
          Map.class);
  private static Logger logger = (Logger) LoggerFactory.getLogger(DefaultExceptionMapper.class);

  @Override
  public Response toResponse(Exception exception) {
    Response response;
    if (exception instanceof CoreException) {
      response = transform(CoreException.class.cast(exception));
    } else if (exception instanceof ConstraintViolationException) {
      response = transform(ConstraintViolationException.class.cast(exception));

    } else if (exception instanceof JsonMappingException) {
      response = transform(JsonMappingException.class.cast(exception));

    } else {
      response = transform(exception);
    }

    try {
      writeStackTraceToFile(exception);
    } catch (IOException e) {
      e.printStackTrace();
    }
    List<Object> contentTypes = new ArrayList<>();
    contentTypes.add(MediaType.APPLICATION_JSON);
    response.getMetadata().put("Content-Type", contentTypes);
    return response;
  }

  private Response transform(CoreException coreException) {
    Response response;
    ErrorCode code = coreException.code();
    logger.error(code.message(), coreException);

    if (coreException.code().category().equals(ErrorCategory.APPLICATION)) {
      if (Response.Status.NOT_FOUND.name().equals(errorCodeToResponseStatus.get(code.id()))) {
        response = Response
            .status(Response.Status.NOT_FOUND)
            .entity(toEntity(Response.Status.NOT_FOUND, code))
            .build();
      } else if (Response.Status.BAD_REQUEST.name()
          .equals(errorCodeToResponseStatus.get(code.id()))) {
        response = Response
            .status(Response.Status.BAD_REQUEST)
            .entity(toEntity(Response.Status.BAD_REQUEST, code))
            .build();
      } else {
        response = Response
            .status(Response.Status.EXPECTATION_FAILED)
            .entity(toEntity(Response.Status.EXPECTATION_FAILED, code))
            .build();
      }
    } else {
      response = Response
          .status(Response.Status.INTERNAL_SERVER_ERROR)
          .entity(toEntity(Response.Status.INTERNAL_SERVER_ERROR, code))
          .build();
    }


    return response;
  }

  private Response transform(ConstraintViolationException validationException) {
    Set<ConstraintViolation<?>> constraintViolationSet =
        validationException.getConstraintViolations();
    String message;

    String fieldName = null;
    if (!CommonMethods.isEmpty(constraintViolationSet)) {
      // getting the first violation message for the output response.
      ConstraintViolation<?> constraintViolation = constraintViolationSet.iterator().next();
      message = constraintViolation.getMessage();
      fieldName = getFieldName(constraintViolation.getPropertyPath());

    } else {
      message = validationException.getMessage();
    }

    ErrorCode validationErrorCode = new ValidationErrorBuilder(message, fieldName).build();

    logger.error(validationErrorCode.message(), validationException);
    return Response
        .status(Response.Status.EXPECTATION_FAILED) //error 417
        .entity(toEntity(Response.Status.EXPECTATION_FAILED, validationErrorCode))
        .build();
  }

  private Response transform(JsonMappingException jsonMappingException) {
    ErrorCode jsonMappingErrorCode = new JsonMappingErrorBuilder().build();
    logger.error(jsonMappingErrorCode.message(), jsonMappingException);
    return Response
        .status(Response.Status.EXPECTATION_FAILED) //error 417
        .entity(toEntity(Response.Status.EXPECTATION_FAILED, jsonMappingErrorCode))
        .build();
  }

  private Response transform(Exception exception) {
    ErrorCode generalErrorCode = new GeneralErrorBuilder(exception.getMessage()).build();
    logger.error(generalErrorCode.message(), exception);
    return Response
        .status(Response.Status.INTERNAL_SERVER_ERROR)
        .entity(toEntity(Response.Status.INTERNAL_SERVER_ERROR, generalErrorCode))
        .build();
  }

  private String getFieldName(Path propertyPath) {
    return ((PathImpl) propertyPath).getLeafNode().toString();
  }

  private Object toEntity(Response.Status status, ErrorCode code) {
    return new ErrorCodeAndMessage(status, code);
  }

  private void writeStackTraceToFile(Exception exception) throws IOException {
    File file = new File("stack_trace.txt");
    OutputStream outputStream = new FileOutputStream(file);

    if(!file.exists()){
      file.createNewFile();
    }

    PrintWriter printWriter = new PrintWriter(file);
    exception.printStackTrace(printWriter);
    printWriter.close();
  }

}