Skip to content

Instantly share code, notes, and snippets.

@claeusdev
Last active March 12, 2024 23:37
Show Gist options
  • Save claeusdev/1c6a7f11287872c6959ef186955e276b to your computer and use it in GitHub Desktop.
Save claeusdev/1c6a7f11287872c6959ef186955e276b to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.List;
public interface Address {
String getStreet();
String getCity();
String getPostalCode();
String getCountry();
}
public class RoutePlannerAdapter implements IDUServiceRoutePlanner {
// Assume there's a method to make HTTP requests to the API server
private HttpClient httpClient;
// Constructor for injecting the HttpClient
public RoutePlannerAdapter(HttpClient httpClient) {
this.httpClient = httpClient;
}
@Override
public RouteDetails requestRouteAndEstimates(Address startLocation, Address targetLocation, String transportMeans) {
// Prepare request body
RouteRequest request = new RouteRequest(startLocation, targetLocation, transportMeans);
// Make HTTP POST request to the API endpoint
HttpResponse<JsonNode> response = httpClient.post("https://example.com/api/route-planner", request);
// Parse response
if (response.getStatus() == 200) {
return parseRouteDetails(response.getBody());
} else {
throw new RuntimeException("Failed to retrieve route details: " + response.getStatusText());
}
}
private RouteDetails parseRouteDetails(JsonNode responseBody) {
// Parse JSON response and create RouteDetails object
// Implement according to the structure of the JSON response
// For simplicity, let's assume the structure matches RouteDetails schema
String estimatedTime = responseBody.get("estimatedTime").asText();
String distance = responseBody.get("distance").asText();
List<Address> waypoints = new ArrayList<>();
// Parse waypoints if available
if (responseBody.has("waypoints")) {
JsonNode waypointsNode = responseBody.get("waypoints");
for (JsonNode waypointNode : waypointsNode) {
Address waypoint = parseAddress(waypointNode);
waypoints.add(waypoint);
}
}
return new RouteDetails(estimatedTime, distance, waypoints);
}
private Address parseAddress(JsonNode addressNode) {
// Parse JSON node representing an address and create Address object
// Implement according to the structure of the JSON response
// For simplicity, let's assume the structure matches Address schema
String street = addressNode.get("street").asText();
String city = addressNode.get("city").asText();
String postalCode = addressNode.get("postalCode").asText();
String country = addressNode.get("country").asText();
return new Address(street, city, postalCode, country);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment