| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- 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<Void> entity = new HttpEntity<>(headers);
- try {
- ResponseEntity<ExchangeRateResponse> 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());
- }
- }
- }
|