Created
March 12, 2024 23:48
-
-
Save claeusdev/caac9f1701cc0524a2ccd41b2e27dbe1 to your computer and use it in GitHub Desktop.
Revisions
-
claeusdev created this gist
Mar 12, 2024 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,48 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import java.util.Objects; public class RoutePlannerAdapter implements IDUServiceRoutePlanner { private final String apiKey; private final String baseUrl; public RoutePlannerAdapter(String apiKey) { this.apiKey = apiKey; this.baseUrl = "https://maps.googleapis.com/maps/api/directions/json"; } @Override public RouteDetails requestRouteAndEstimates(Address startLocation, Address targetLocation, String transportMeans) { // Prepare the request URL String url = baseUrl + "?origin=" + encodeAddress(startLocation) + "&destination=" + encodeAddress(targetLocation) + "&mode=" + transportMeans + "&key=" + apiKey; // Set up REST template RestTemplate restTemplate = new RestTemplate(); // Make the API call ResponseEntity<RouteDetails> responseEntity = restTemplate.exchange( url, HttpMethod.GET, null, RouteDetails.class); // Check if the response is successful if (responseEntity.getStatusCode().is2xxSuccessful()) { return Objects.requireNonNull(responseEntity.getBody()); } else { throw new RuntimeException("Failed to retrieve route details: " + responseEntity.getStatusCode()); } } // Utility method to encode address for URL private String encodeAddress(Address address) { return address.getStreet() + ", " + address.getCity() + ", " + address.getPostalCode() + ", " + address.getCountry(); } }