|
1 | 1 | package com.ODG.ODG_back.external.google; |
2 | 2 |
|
| 3 | +import com.ODG.ODG_back.domain.enums.TransportType; |
3 | 4 | import org.springframework.beans.factory.annotation.Value; |
4 | 5 | import org.springframework.stereotype.Component; |
5 | | -import org.springframework.web.client.RestTemplate; |
| 6 | +import org.springframework.web.reactive.function.client.WebClient; |
6 | 7 |
|
7 | | -import java.math.BigDecimal; |
8 | 8 | import java.util.List; |
| 9 | +import java.util.Map; |
| 10 | + |
| 11 | +import static com.ODG.ODG_back.external.google.parser.GoogleMatrixResponseParser.parseTimeMatrix; |
9 | 12 |
|
10 | 13 | @Component("googleMatrixApiClient") |
11 | 14 | public class GoogleMatrixApiClientImpl implements GoogleMatrixApiClient { |
12 | 15 |
|
13 | | - @Value("{google.api.key}") |
14 | | - private String googleApiKey; |
| 16 | + private final String googleApiKey; |
| 17 | + private final WebClient webClient; |
15 | 18 |
|
16 | | - private final RestTemplate restTemplate = new RestTemplate(); |
| 19 | + public GoogleMatrixApiClientImpl(WebClient.Builder builder, @Value("${google.api.key}") String googleApiKey) { |
| 20 | + this.webClient = builder.build(); |
| 21 | + this.googleApiKey = googleApiKey; |
| 22 | + } |
17 | 23 |
|
18 | 24 | @Override |
19 | | - public int[][] getTimeMatrix(List<List<BigDecimal>> origins, List<List<BigDecimal>> destinations) { |
20 | | - return new int[0][]; |
| 25 | + public int[][] getTimeMatrix(List<String> origins, List<String> destinations, TransportType transport) { |
| 26 | + |
| 27 | + String url = buildUrl(origins, destinations, transport); |
| 28 | + Map<String, Object> response = fetchApiResponse(url); |
| 29 | + |
| 30 | + return parseTimeMatrix(response, origins.size(), destinations.size()); |
| 31 | + } |
| 32 | + |
| 33 | + private String buildUrl(List<String> origins, List<String> destinations, TransportType transport) { |
| 34 | + |
| 35 | + String originsParam = String.join("|", origins); |
| 36 | + String destinationsParam = String.join("|", destinations); |
| 37 | + String mode = transport == TransportType.CAR ? "driving" : "transit"; |
| 38 | + |
| 39 | + String url = String.format( |
| 40 | + "https://maps.googleapis.com/maps/api/distancematrix/json?" + |
| 41 | + "origins=%s&destinations=%s&mode=%s&key=%s", |
| 42 | + originsParam, destinationsParam, mode, googleApiKey |
| 43 | + ); |
| 44 | + |
| 45 | + return url; |
| 46 | + } |
| 47 | + |
| 48 | + private Map<String, Object> fetchApiResponse(String url) { |
| 49 | + return webClient.get() |
| 50 | + .uri(url) |
| 51 | + .retrieve() |
| 52 | + .bodyToMono(Map.class) |
| 53 | + .block(); |
21 | 54 | } |
22 | 55 | } |
0 commit comments