2

Hello I have a problem with my service says that "Internal Server Error Exception occured! Exception details: IdentificationResponse cannot be cast to org.springframework.http.ResponseEntity"" any help on this matter ?

my code blocks below;

my IdentificationService Impl;

Slf4j
@Service
@RequiredArgsConstructor
public class IdentificationServiceImpl implements IdentificationService {

    private final RestTemplate restTemplate;

    @Value("${platform.url}")
    private String platform;

    private final ServiceConfig serviceConfig;

    @Override
    public ResponseEntity<IdentificationResponse> createIdentification(Request request) {

        IdentificationRequest identificationRequest = new IdentificationRequest(serviceConfig.getIssuerKey(), serviceConfig.getSecureKey());

        identificationRequest.setOperation(ClientConstants.CREATE_IDENTIFICATION_ADD);

        HttpEntity<IdentificationRequest> requestHttpEntity = new HttpEntity<>(IdentificationRequest);

        ResponseEntity<IdentificationResponse> response = restTemplate.exchange(platform, HttpMethod.POST, requestHttpEntity, IdentificationResponse.class);

        return HandleResponse.handleResponse(response);
    }

my handle Response class below;

public static <T> T handleResponse(ResponseEntity response) {
        HttpStatus code = response.getStatusCode();
        if (code == HttpStatus.OK || code == HttpStatus.CREATED) {
            return (T) response.getBody();

        } else if (code == HttpStatus.NO_CONTENT) {
            return null;
        } else if (code == HttpStatus.BAD_REQUEST)
            throw new BadRequestException("BadRequest Exception occured while requesting! Exception details: " + response.getBody());
        else if (code == HttpStatus.UNAUTHORIZED)
            throw new UnauthorizedException("Unauthorized Exception occured while requesting! Exception details: " + response.getBody());
        else
            throw new HttpClientException("Exception occured! Exception details: " + response.getBody(), code.value());
    }
}

my IdentificationRequest class below;

 @Data
 public class IdentificationRequest {

    @Setter(AccessLevel.NONE)
    @NotNull
    @JsonProperty("IssuerKey")
    private String issuerKey;
    @Setter(AccessLevel.NONE)
    @NotNull
    @JsonProperty("SecurityKey")
    private String secureKey;
    @NotNull
    @JsonProperty("TransactionId")
    private String transactionId;
    @NotNull
    @JsonProperty("TransactionDate")
    @DateTimeFormat(pattern = "YYYY-MM-DD HH:mm:ss.SSS")
    private String transactionDate;
    @NotNull
    @JsonProperty("Msisdn")
    @Pattern(regexp = "^905.{9}", message = "must be of 12 char/digit")
    private Long msisdn;
    private String operation;
    @NotNull
    @JsonProperty("Package")
    private String Package;
    @NotNull
    @JsonProperty("STB")
    private Boolean isStb;
    @JsonProperty("STB_SerialNumber")
    private String stbSerialNumber;
    @JsonProperty("STB_MacAddress")
    private String stbMacAddress;

    public IdentificationRequest(String issuerKey, String secureKey) {
        this.issuerKey = issuerKey;
        this.secureKey = secureKey;
    }
}

my Request class below;

@Data
public class Request {
    @JsonProperty("OrderId")
    private String orderId;

    @JsonProperty("OrderItemId")
    private String orderItemId;

    @JsonProperty("ProcessInstanceId")
    private String processId;

    @JsonProperty("step_id")
    private String stepId;

    @JsonProperty("step_name")
    private String stepName;

my Response class below;

@Data
public class IdentificationResponse {

    @JsonProperty("IsSuccessful")
    private Boolean isSuccessful;
    @JsonProperty("Code")
    private Integer code;
    @JsonProperty("Message")
    private String message;
    @JsonProperty("Data")
    private Object data;
}

Do I need a map to response to response Entity?

john deltana
  • 37
  • 1
  • 6
  • It should be something like this: `return new ResponseEntity<>(your_object, HttpStatus.OK);` – Faramarz Afzali Sep 16 '21 at 16:34
  • Hello, thank you for your answer but I have return Handle response how can ı put that ? – john deltana Sep 16 '21 at 16:43
  • A quite good way is to use `@ControllerAdvice`. You can handle exceptions for all status codes you want. [An example](https://www.bezkoder.com/spring-boot-controlleradvice-exceptionhandler/) – Faramarz Afzali Sep 16 '21 at 17:35
  • hello, thank you @FaramarzAfzali, but my logic is a little bit different so I need to handle my generic response, so how can ı do that – john deltana Sep 16 '21 at 21:42

2 Answers2

0

Basically you are trying to cast an object to an incompatible one, the cast could be done if both objects implement the same interface or if the hierarchy of objects allows it, if this cast cannot be achieved, it is a good idea to create a instance of the response object based on the value of the object that you retrieved.

Luan Kevin Ferreira
  • 1,184
  • 2
  • 16
  • 40
  • Lauran, thank you for your response, could you please kindly change my code so I can understand – john deltana Sep 16 '21 at 16:14
  • @johndeltana you can try something like this `return ResponseEntity.ok(restTemplate.exchange(platform, HttpMethod.POST, requestHttpEntity, IdentificationResponse.class));` Also is a good idea to add exactly where the error is happening, the stack trace shows the line of the code where the error originated. – Luan Kevin Ferreira Sep 16 '21 at 16:31
  • thank you but I return handleResponse where can ı put that – john deltana Sep 16 '21 at 16:40
  • comment out the actual return line and test with the code that I mentioned above, then maybe you will understand better and get the idea to change your code correctly. – Luan Kevin Ferreira Sep 16 '21 at 16:43
  • thank you I have already can return response; but I like to handle my HandleResponse class on return – john deltana Sep 16 '21 at 16:46
0

As per your code, when you call response.getBody() method you'll get IdentificationResponse and it is converting it to ResponseEntity which is throwing ClassCastException.

  if (code == HttpStatus.OK || code == HttpStatus.CREATED)
      return (T) response.getBody();

You can either return response directly instead of response.getBody() to resolve your issue or you can follow the below implementation to your method if you want your createIdentification method to return IdentificationResponse instance

return HandleResponse.handleResponse(response, IdentificationResponse.class);

 public static <T> T handleResponse(ResponseEntity response, Class<T> type) {
        HttpStatus code = response.getStatusCode();
        if (code == HttpStatus.OK || code == HttpStatus.CREATED)
            return (T) response.getBody();
 }

You can find some more info related to generics here