Skip to content

Instantly share code, notes, and snippets.

@claeusdev
Created March 12, 2024 23:48
Show Gist options
  • Save claeusdev/caac9f1701cc0524a2ccd41b2e27dbe1 to your computer and use it in GitHub Desktop.
Save claeusdev/caac9f1701cc0524a2ccd41b2e27dbe1 to your computer and use it in GitHub Desktop.

Revisions

  1. claeusdev created this gist Mar 12, 2024.
    48 changes: 48 additions & 0 deletions spring_impl.java
    Original 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();
    }
    }