package com.danielbohry.stocks.client; import com.danielbohry.stocks.service.ExchangeService.ExchangeRateResponse; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import static org.springframework.http.HttpMethod.GET; import static org.springframework.http.HttpStatus.OK; import static org.springframework.http.MediaType.APPLICATION_JSON; @Component @RequiredArgsConstructor public class ExchangeRateClient { private final RestTemplate rest; @Value("${clients.exchange.url}") private String baseUrl; public ExchangeRateResponse getRate(String symbol, String apiKey) { String url = baseUrl + "/" + apiKey + "/latest/" + symbol; HttpHeaders headers = new HttpHeaders(); headers.setContentType(APPLICATION_JSON); HttpEntity entity = new HttpEntity<>(headers); try { ResponseEntity response = rest.exchange( url, GET, entity, ExchangeRateResponse.class ); if (response.getStatusCode() == OK) { return response.getBody(); } else { throw new RuntimeException("Unexpected response status: " + response.getStatusCode()); } } catch (HttpClientErrorException e) { throw new RuntimeException("Error calling exchange API: " + e.getStatusCode() + " - " + e.getResponseBodyAsString()); } catch (Exception e) { throw new RuntimeException("An error occurred calling exchange API: " + e.getMessage()); } } }