Home > database >  how to cast response to responseEntity
how to cast response to responseEntity

Time:09-21

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?

CodePudding user response:

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.

CodePudding user response:

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

  • Related