ExchangeRateClient.java 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package com.danielbohry.stocks.client;
  2. import com.danielbohry.stocks.service.ExchangeService.ExchangeRateResponse;
  3. import lombok.RequiredArgsConstructor;
  4. import org.springframework.beans.factory.annotation.Value;
  5. import org.springframework.http.HttpEntity;
  6. import org.springframework.http.HttpHeaders;
  7. import org.springframework.http.ResponseEntity;
  8. import org.springframework.stereotype.Component;
  9. import org.springframework.web.client.HttpClientErrorException;
  10. import org.springframework.web.client.RestTemplate;
  11. import static org.springframework.http.HttpMethod.GET;
  12. import static org.springframework.http.HttpStatus.OK;
  13. import static org.springframework.http.MediaType.APPLICATION_JSON;
  14. @Component
  15. @RequiredArgsConstructor
  16. public class ExchangeRateClient {
  17. private final RestTemplate rest;
  18. @Value("${clients.exchange.url}")
  19. private String baseUrl;
  20. public ExchangeRateResponse getRate(String symbol, String apiKey) {
  21. String url = baseUrl + "/" + apiKey + "/latest/" + symbol;
  22. HttpHeaders headers = new HttpHeaders();
  23. headers.setContentType(APPLICATION_JSON);
  24. HttpEntity<Void> entity = new HttpEntity<>(headers);
  25. try {
  26. ResponseEntity<ExchangeRateResponse> response = rest.exchange(
  27. url,
  28. GET,
  29. entity,
  30. ExchangeRateResponse.class
  31. );
  32. if (response.getStatusCode() == OK) {
  33. return response.getBody();
  34. } else {
  35. throw new RuntimeException("Unexpected response status: " + response.getStatusCode());
  36. }
  37. } catch (HttpClientErrorException e) {
  38. throw new RuntimeException("Error calling exchange API: " + e.getStatusCode() + " - " + e.getResponseBodyAsString());
  39. } catch (Exception e) {
  40. throw new RuntimeException("An error occurred calling exchange API: " + e.getMessage());
  41. }
  42. }
  43. }