diff --git a/src/main/java/SuMoC/backend/carta/DirectionsRequest.java b/src/main/java/SuMoC/backend/carta/DirectionsRequest.java new file mode 100644 index 0000000..d62ffa1 --- /dev/null +++ b/src/main/java/SuMoC/backend/carta/DirectionsRequest.java @@ -0,0 +1,32 @@ +package SuMoC.backend.carta; + +public interface DirectionsRequest { + + Double getOriginLat(); + + void setOriginLat(Double originLat); + + Double getOriginLon(); + + void setOriginLon(Double originLon); + + Double getDestinationLat(); + + void setDestinationLat(Double destinationLat); + + Double getDestinationLon(); + + void setDestinationLon(Double destinationLon); + + java.time.Instant getArrivalTime(); + + void setArrivalTime(java.time.Instant arrivalTime); + + java.time.Instant getDepartureTime(); + + void setDepartureTime(java.time.Instant departureTime); + + SuMoC.backend.routing.dtos.RoutingPreferencesDTO getRoutingPreferencesDTO(); + + void setRoutingPreferencesDTO(SuMoC.backend.routing.dtos.RoutingPreferencesDTO routingPreferencesDTO); +} diff --git a/src/main/java/SuMoC/backend/routing/services/RoutingService.java b/src/main/java/SuMoC/backend/carta/DirectionsService.java similarity index 68% rename from src/main/java/SuMoC/backend/routing/services/RoutingService.java rename to src/main/java/SuMoC/backend/carta/DirectionsService.java index a8c400c..8a81ae7 100644 --- a/src/main/java/SuMoC/backend/routing/services/RoutingService.java +++ b/src/main/java/SuMoC/backend/carta/DirectionsService.java @@ -1,15 +1,12 @@ -package SuMoC.backend.routing.services; +package SuMoC.backend.carta; -import SuMoC.backend.carta.CartaClient; import SuMoC.backend.geocoding.AddressDTO; import SuMoC.backend.geocoding.GeoCodingService; -import SuMoC.backend.routing.config.AdHocRoutingProperties; -import SuMoC.backend.routing.config.OnCallRoutingProperties; import SuMoC.backend.routing.dtos.RouteDTO; -import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO; import SuMoC.backend.routing.dtos.StepDTO; import SuMoC.backend.routing.exceptions.NoCarRouteFoundException; import SuMoC.backend.routing.exceptions.NoCarbonEmissionFoundException; +import SuMoC.backend.routing.services.CartaTransitRouteProcessor; import SuMoC.backend.trip.Modality; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @@ -25,40 +22,170 @@ import java.util.concurrent.CompletableFuture; @Service @RequiredArgsConstructor -public class RoutingService { - - private final GeoCodingService geoCodingService; +public class DirectionsService { private final CartaClient cartaClient; - private final AlternativeFilterService alternativeFilterService; + private final GeoCodingService geoCodingService; - private final OnCallRoutingProperties onCallRoutingProperties; - - private final AdHocRoutingProperties adHocRoutingProperties; + public List getPossibleAlternativeRoutes(DirectionsRequest requestDTO) { + return getPossibleRoutes(requestDTO, false); + } /** - * Makes an individual call to the CARTA API and returns a direction future. + * Returns possible routes for the request - no sanity filtering regarding travel times etc. is applied. + * TODO this does not handle the case where only departure time is provided + * TODO this does not handle the case where origin/destination is provided as address only + * TODO IF both arrival and departure are provided -> use that as baseline time */ - private CompletableFuture getCartaFuture( - RoutingAlternativeRequestDTO requestDTO, - String mode, - String types, - int alternatives - ) { - return cartaClient.asyncGetRoute( - requestDTO.getOriginLat() + "," + requestDTO.getOriginLon(), - requestDTO.getDestinationLat() + "," + requestDTO.getDestinationLon(), - mode, - requestDTO.getArrivalTime(), - null, - alternatives, // alternatives - null, // walkingSpeed - null, // transferTime TODO what is default? adapt? - types, - null, // range - requestDTO.getOriginLat() + "," + requestDTO.getOriginLon() + public List getPossibleRoutes(DirectionsRequest requestDTO, boolean includeCarRoute) { + assert requestDTO.getRoutingPreferencesDTO() != null; + HashMap directionMap = getPossibleDirections(requestDTO); + ArrayList suggestedRoutes = new ArrayList<>(); + + // Fetch origin and destination addresses concurrently + var addressesMono = Mono.zip( + geoCodingService.getAddress(requestDTO.getOriginLat(), requestDTO.getOriginLon()), + geoCodingService.getAddress(requestDTO.getDestinationLat(), requestDTO.getDestinationLon()) ); + var addressesTuple = addressesMono.block(); + AddressDTO originAddress = addressesTuple.getT1(); + AddressDTO destinationAddress = addressesTuple.getT2(); + + // Setting up car data for baseline + Route carRoute; + try { + carRoute = directionMap.get("car").getRoutes().getFirst(); + } catch (NullPointerException e) { + throw new NoCarRouteFoundException("No car route to compare to was found."); + } + double carCarbondDioxide; + try { + carCarbondDioxide = carRoute.getEmission().getCarbonDioxide(); + } catch (NullPointerException e) { + throw new NoCarbonEmissionFoundException("No carbon emission was provided for the car route."); + } + + if (includeCarRoute) { + Direction carDirection = directionMap.get("car"); + if (carDirection.getRoutes() != null && !carDirection.getRoutes().isEmpty()) { + ArrayList steps = new ArrayList<>(); + steps.add(new StepDTO( + Modality.CAR, + carRoute.getDistance() + ) + ); + + RouteDTO routeDTO = new RouteDTO( + originAddress, + null, + carRoute.getSourceCoordinate().getLatitude(), + carRoute.getSourceCoordinate().getLongitude(), + destinationAddress, + null, + carRoute.getTargetCoordinate().getLatitude(), + carRoute.getTargetCoordinate().getLongitude(), + requestDTO.getArrivalTime().minusSeconds(carRoute.getDuration()), + requestDTO.getArrivalTime(), + steps, + 0.0, + 0L, + carCarbondDioxide + ); + + suggestedRoutes.add(routeDTO); + } + } + + if (directionMap.containsKey("bike")) { + Direction bikeDirection = directionMap.get("bike"); + if (bikeDirection.getRoutes() != null && !bikeDirection.getRoutes().isEmpty()) { + Route bikeRoute = bikeDirection.getRoutes().getFirst(); + ArrayList steps = new ArrayList<>(); + steps.add(new StepDTO( + Modality.BICYCLE, + bikeRoute.getDistance() + ) + ); + + RouteDTO routeDTO = new RouteDTO( + originAddress, + null, + bikeRoute.getSourceCoordinate().getLatitude(), + bikeRoute.getSourceCoordinate().getLongitude(), + destinationAddress, + null, + bikeRoute.getTargetCoordinate().getLatitude(), + bikeRoute.getTargetCoordinate().getLongitude(), + requestDTO.getArrivalTime().minusSeconds(bikeRoute.getDuration()), + requestDTO.getArrivalTime(), + steps, + carCarbondDioxide, + bikeRoute.getDuration() - carRoute.getDuration(), + 0.0 + ); + suggestedRoutes.add(routeDTO); + } + } + + if (directionMap.containsKey("walk")) { + Direction walkDirection = directionMap.get("walk"); + if (walkDirection.getRoutes() != null && !walkDirection.getRoutes().isEmpty()) { + Route walkRoute = walkDirection.getRoutes().getFirst(); + ArrayList steps = new ArrayList<>(); + steps.add(new StepDTO( + Modality.WALKING, + walkRoute.getDistance() + )); + + RouteDTO routeDTO = new RouteDTO( + originAddress, + null, + walkRoute.getSourceCoordinate().getLatitude(), + walkRoute.getSourceCoordinate().getLongitude(), + destinationAddress, + null, + walkRoute.getTargetCoordinate().getLatitude(), + walkRoute.getTargetCoordinate().getLongitude(), + requestDTO.getArrivalTime().minusSeconds(walkRoute.getDuration()), + requestDTO.getArrivalTime(), + steps, + carCarbondDioxide, + walkRoute.getDuration() - carRoute.getDuration(), + 0.0 + ); + suggestedRoutes.add(routeDTO); + } + } + + if (directionMap.containsKey("transit")) { + Direction transitDirection = directionMap.get("transit"); + if (transitDirection.getRoutes() != null && !transitDirection.getRoutes().isEmpty()) { + for (Route route : transitDirection.getRoutes()) { + CartaTransitRouteProcessor routeProcessor = new CartaTransitRouteProcessor(route); + + RouteDTO routeDTO = new RouteDTO( + originAddress, + routeProcessor.getFirstStopName(), + route.getSourceCoordinate().getLatitude(), + route.getSourceCoordinate().getLongitude(), + destinationAddress, + routeProcessor.getLastStopName(), + route.getTargetCoordinate().getLatitude(), + route.getTargetCoordinate().getLongitude(), + requestDTO.getArrivalTime().minusSeconds(route.getDuration()), + requestDTO.getArrivalTime(), + routeProcessor.getSteps(), + carCarbondDioxide - route.getEmission().getCarbonDioxide(), + route.getDuration() - carRoute.getDuration(), + route.getEmission().getCarbonDioxide() + ); + suggestedRoutes.add(routeDTO); + } + } + } + + return suggestedRoutes; } /** @@ -69,7 +196,7 @@ public class RoutingService { * - bike (optional) * - transit (optional) */ - private HashMap getPossibleDirectionsFromCarta(RoutingAlternativeRequestDTO requestDTO) { + private HashMap getPossibleDirections(DirectionsRequest requestDTO) { Map> futuresByMode = new HashMap<>(); assert requestDTO.getRoutingPreferencesDTO() != null; @@ -113,188 +240,26 @@ public class RoutingService { } /** - * Gets possible routes from CARTA, converts them to our format and applies filter to only provide acceptable solutions without excessive additional travel time. - * This is the public method for alternatives explicitly asked for by the client. + * Makes an individual call to the CARTA API and returns a direction future. */ - public List determineAlternativeRoutesOnUserRequest(RoutingAlternativeRequestDTO requestDTO) { - List routes = getPossibleAlternativeRoutes(requestDTO); - routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, onCallRoutingProperties); - - return routes; - } - - /** - * Public alternative retrieval method which is used to check for alternatives we suggest to user via notification - * right after user finished the trip. - * Similar to determineAlternativeRoutesOnUserRequest but here we apply stricter thresholds for alternatives - * and also apply weather filtering (if enabled) to not suggest routes the user definitly would not have consideres. - */ - public List determineAlternativeRoutesAdHoc(RoutingAlternativeRequestDTO requestDTO) { - assert requestDTO.getRoutingPreferencesDTO() != null; - - List routes = getPossibleAlternativeRoutes(requestDTO); - routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, adHocRoutingProperties); - - if (requestDTO.getRoutingPreferencesDTO().isConsiderWeatherConditions()) { - routes = alternativeFilterService.filterForBadWeather(requestDTO, routes, adHocRoutingProperties); - } - - return routes; - } - - public RouteDTO determineBestAlternativeRouteForRegularTrip(RoutingAlternativeRequestDTO requestDTO) { - assert requestDTO.getRoutingPreferencesDTO() != null; - - // TODO for now we use adHocRoutingProperties here, in the future we might want to have separate properties for regular trip alternatives - List routes = getPossibleAlternativeRoutes(requestDTO); - routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, adHocRoutingProperties); - if (requestDTO.getRoutingPreferencesDTO().isConsiderWeatherConditions()) { - routes = alternativeFilterService.filterForBadWeather(requestDTO, routes, adHocRoutingProperties); - } - - RouteDTO bestRoute = null; - // if users wants physical activity, we pick the fastest physical activity route, if any - if (requestDTO.getRoutingPreferencesDTO().isPreferPhysicalActivity()) { - bestRoute = routes.stream() - .filter(RouteDTO::isPhysicalActivity) - .min((r1, r2) -> Long.compare( - r1.getDurationSeconds(), - r2.getDurationSeconds() - )).orElse(null); - if (bestRoute != null) { - return bestRoute; - } - } - // else we pick the fastest route overall - bestRoute = routes.stream() - .min((r1, r2) -> Long.compare( - r1.getDurationSeconds(), - r2.getDurationSeconds() - )).orElse(null); - return bestRoute; - } - - /** - * Returns possible alternative routes for the request - no sanity filtering regarding travel times etc. is applied. - */ - private List getPossibleAlternativeRoutes(RoutingAlternativeRequestDTO requestDTO) { - assert requestDTO.getRoutingPreferencesDTO() != null; - HashMap directionMap = getPossibleDirectionsFromCarta(requestDTO); - ArrayList suggestedAlternatives = new ArrayList<>(); - - // Fetch origin and destination addresses concurrently - var addressesMono = Mono.zip( - geoCodingService.getAddress(requestDTO.getOriginLat(), requestDTO.getOriginLon()), - geoCodingService.getAddress(requestDTO.getDestinationLat(), requestDTO.getDestinationLon()) + private CompletableFuture getCartaFuture( + DirectionsRequest requestDTO, + String mode, + String types, + int alternatives + ) { + return cartaClient.asyncGetRoute( + requestDTO.getOriginLat() + "," + requestDTO.getOriginLon(), + requestDTO.getDestinationLat() + "," + requestDTO.getDestinationLon(), + mode, + requestDTO.getArrivalTime(), + null, + alternatives, // alternatives + null, // walkingSpeed + null, // transferTime TODO what is default? adapt? + types, + null, // range + requestDTO.getOriginLat() + "," + requestDTO.getOriginLon() ); - var addressesTuple = addressesMono.block(); - AddressDTO originAddress = addressesTuple.getT1(); - AddressDTO destinationAddress = addressesTuple.getT2(); - - // Setting up car data for baseline - Route carRoute; - try { - carRoute = directionMap.get("car").getRoutes().getFirst(); - } catch (NullPointerException e) { - throw new NoCarRouteFoundException("No car route to compare to was found."); - } - double carCarbondDioxide; - try { - carCarbondDioxide = carRoute.getEmission().getCarbonDioxide(); - } catch (NullPointerException e) { - throw new NoCarbonEmissionFoundException("No carbon emission was provided for the car route."); - } - - if (directionMap.containsKey("bike")) { - Direction bikeDirection = directionMap.get("bike"); - if (bikeDirection.getRoutes() != null && !bikeDirection.getRoutes().isEmpty()) { - Route bikeRoute = bikeDirection.getRoutes().getFirst(); - ArrayList steps = new ArrayList<>(); - steps.add(new StepDTO( - Modality.BICYCLE, - null, - bikeRoute.getDistance() - ) - ); - - RouteDTO routeDTO = new RouteDTO( - originAddress, - null, - bikeRoute.getSourceCoordinate().getLatitude(), - bikeRoute.getSourceCoordinate().getLongitude(), - destinationAddress, - null, - bikeRoute.getTargetCoordinate().getLatitude(), - bikeRoute.getTargetCoordinate().getLongitude(), - requestDTO.getArrivalTime().minusSeconds(bikeRoute.getDuration()), - requestDTO.getArrivalTime(), - steps, - carCarbondDioxide, - bikeRoute.getDuration() - carRoute.getDuration(), - 0.0 - ); - suggestedAlternatives.add(routeDTO); - } - } - - if (directionMap.containsKey("walk")) { - Direction walkDirection = directionMap.get("walk"); - if (walkDirection.getRoutes() != null && !walkDirection.getRoutes().isEmpty()) { - Route walkRoute = walkDirection.getRoutes().getFirst(); - ArrayList steps = new ArrayList<>(); - steps.add(new StepDTO( - Modality.WALKING, - null, - walkRoute.getDistance() - )); - - RouteDTO routeDTO = new RouteDTO( - originAddress, - null, - walkRoute.getSourceCoordinate().getLatitude(), - walkRoute.getSourceCoordinate().getLongitude(), - destinationAddress, - null, - walkRoute.getTargetCoordinate().getLatitude(), - walkRoute.getTargetCoordinate().getLongitude(), - requestDTO.getArrivalTime().minusSeconds(walkRoute.getDuration()), - requestDTO.getArrivalTime(), - steps, - carCarbondDioxide, - walkRoute.getDuration() - carRoute.getDuration(), - 0.0 - ); - suggestedAlternatives.add(routeDTO); - } - } - - if (directionMap.containsKey("transit")) { - Direction transitDirection = directionMap.get("transit"); - if (transitDirection.getRoutes() != null && !transitDirection.getRoutes().isEmpty()) { - for (Route route : transitDirection.getRoutes()) { - CartaTransitRouteProcessor routeProcessor = new CartaTransitRouteProcessor(route); - - RouteDTO routeDTO = new RouteDTO( - originAddress, - routeProcessor.getFirstStopName(), - route.getSourceCoordinate().getLatitude(), - route.getSourceCoordinate().getLongitude(), - destinationAddress, - routeProcessor.getLastStopName(), - route.getTargetCoordinate().getLatitude(), - route.getTargetCoordinate().getLongitude(), - requestDTO.getArrivalTime().minusSeconds(route.getDuration()), - requestDTO.getArrivalTime(), - routeProcessor.getSteps(), - carCarbondDioxide - route.getEmission().getCarbonDioxide(), - route.getDuration() - carRoute.getDuration(), - route.getEmission().getCarbonDioxide() - ); - suggestedAlternatives.add(routeDTO); - } - } - } - - return suggestedAlternatives; } } diff --git a/src/main/java/SuMoC/backend/routing/controller/RoutingController.java b/src/main/java/SuMoC/backend/routing/controller/RoutingAlternativeController.java similarity index 86% rename from src/main/java/SuMoC/backend/routing/controller/RoutingController.java rename to src/main/java/SuMoC/backend/routing/controller/RoutingAlternativeController.java index 3a7ecfc..d4c09a4 100644 --- a/src/main/java/SuMoC/backend/routing/controller/RoutingController.java +++ b/src/main/java/SuMoC/backend/routing/controller/RoutingAlternativeController.java @@ -2,8 +2,8 @@ package SuMoC.backend.routing.controller; import SuMoC.backend.routing.dtos.RouteDTO; import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO; +import SuMoC.backend.routing.services.AlternativeRoutingService; import SuMoC.backend.routing.services.RoutingPreferencesService; -import SuMoC.backend.routing.services.RoutingService; import SuMoC.backend.user.service.CurrentUserService; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.Valid; @@ -22,11 +22,11 @@ import java.util.logging.Logger; @RestController @RequestMapping("/routing/alternative") @RequiredArgsConstructor -public class RoutingController { +public class RoutingAlternativeController { - private final Logger logger = Logger.getLogger(RoutingController.class.getName()); + private final Logger logger = Logger.getLogger(RoutingAlternativeController.class.getName()); - private final RoutingService routingService; + private final AlternativeRoutingService alternativeRoutingService; private final RoutingPreferencesService routingPreferencesService; @@ -48,7 +48,7 @@ public class RoutingController { routingAlternativeRequestDTO.setRoutingPreferencesDTO(routingPreferencesService.getRoutingPreferencesForCurrentUser()); } - var routeDTOs = routingService.determineAlternativeRoutesOnUserRequest(routingAlternativeRequestDTO); + var routeDTOs = alternativeRoutingService.determineAlternativeRoutesOnUserRequest(routingAlternativeRequestDTO); return ResponseEntity.ok(routeDTOs); } catch (WebClientRequestException e) { // nominatim container is not up yet, we return mock diff --git a/src/main/java/SuMoC/backend/routing/controller/RoutingDirectionsController.java b/src/main/java/SuMoC/backend/routing/controller/RoutingDirectionsController.java new file mode 100644 index 0000000..5d81d5a --- /dev/null +++ b/src/main/java/SuMoC/backend/routing/controller/RoutingDirectionsController.java @@ -0,0 +1,54 @@ +package SuMoC.backend.routing.controller; + +import SuMoC.backend.routing.dtos.RouteDTO; +import SuMoC.backend.routing.dtos.RoutingDirectionsRequestDTO; +import SuMoC.backend.routing.services.DirectionsRoutingService; +import SuMoC.backend.routing.services.RoutingPreferencesService; +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/routing/directions") +@RequiredArgsConstructor +class RoutingDirectionsController { + + private final DirectionsRoutingService directionsRoutingService; + + private final RoutingPreferencesService routingPreferencesService; + + @PostMapping("/request") + @Schema(description = "Endpoint to request routes from point A to B, also see RoutingDirectionsRequestDTO.") + public ResponseEntity> requestDirections(@Valid @RequestBody RoutingDirectionsRequestDTO directionsRequestDTO) { + validateRequestDTO(directionsRequestDTO); + + // if routing preferences are not provided, get stored preferences or default + if (directionsRequestDTO.getRoutingPreferencesDTO() == null) { + directionsRequestDTO.setRoutingPreferencesDTO(routingPreferencesService.getRoutingPreferencesForCurrentUser()); + } + + return ResponseEntity.ok(directionsRoutingService.getDirections(directionsRequestDTO)); + } + + private void validateRequestDTO(RoutingDirectionsRequestDTO requestDTO) { + if (requestDTO.getArrivalTime() == null && requestDTO.getDepartureTime() == null) { + throw new IllegalArgumentException("Either arrivalTime or departureTime must be provided."); + } + if (requestDTO.getArrivalTime() != null && requestDTO.getDepartureTime() != null) { + throw new IllegalArgumentException("Only one of arrivalTime or departureTime should be provided."); + } + if (requestDTO.getOriginAddress() == null && (requestDTO.getOriginLat() == 0.0 || requestDTO.getOriginLon() == 0.0)) { + throw new IllegalArgumentException("Origin must be specified either by address or coordinates."); + } + if (requestDTO.getDestinationAddress() == null && (requestDTO.getDestinationLat() == 0.0 || requestDTO.getDestinationLon() == 0.0)) { + throw new IllegalArgumentException("Destination must be specified either by address or coordinates."); + } + } +} diff --git a/src/main/java/SuMoC/backend/routing/dtos/RouteDTO.java b/src/main/java/SuMoC/backend/routing/dtos/RouteDTO.java index cb02baa..dd16449 100644 --- a/src/main/java/SuMoC/backend/routing/dtos/RouteDTO.java +++ b/src/main/java/SuMoC/backend/routing/dtos/RouteDTO.java @@ -46,7 +46,7 @@ public class RouteDTO { private double co2Savings; @Schema(description = "CO2e emission of this route.") private double co2Emissions; - @Schema(description = "The temporal difference in minutes compared to the original route the user requested alternatives for.") + @Schema(description = "The temporal difference in minutes compared to the original route (in case alternative was requested) / the car route (when simply directions requested) .") private double timeDifferenceSeconds; public RouteDTO(AddressDTO startAddress, @Nullable String firstStopName, double startLat, double startLon, AddressDTO endAddress, @Nullable String lastStopName, double endLat, double endLon, Instant startDateTime, Instant endDateTime, List steps, double co2Savings, double timeDifferenceSeconds, double co2Emissions) { @@ -114,17 +114,18 @@ public class RouteDTO { ); dto.steps.add(new StepDTO( Modality.WALKING, - null, 400f )); - dto.steps.add(new StepDTO( + dto.steps.add(new TransitStepDTO( Modality.TRAM, + 5000f, "106", - 5000f + "Ich bin eine Testlinie", + "Ich bin ein Teststartbahnhof", + "Ich bin ein Testendbahnhof" )); dto.steps.add(new StepDTO( Modality.WALKING, - null, 300f )); return dto; diff --git a/src/main/java/SuMoC/backend/routing/dtos/RoutingAlternativeRequestDTO.java b/src/main/java/SuMoC/backend/routing/dtos/RoutingAlternativeRequestDTO.java index de7b21c..715ce5c 100644 --- a/src/main/java/SuMoC/backend/routing/dtos/RoutingAlternativeRequestDTO.java +++ b/src/main/java/SuMoC/backend/routing/dtos/RoutingAlternativeRequestDTO.java @@ -1,5 +1,6 @@ package SuMoC.backend.routing.dtos; +import SuMoC.backend.carta.DirectionsRequest; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.annotation.Nullable; import jakarta.validation.constraints.NotNull; @@ -13,7 +14,7 @@ import java.time.Instant; @AllArgsConstructor @NoArgsConstructor @Schema(description = "This DTO represents a request for alternative routes between an origin and a destination.") -public class RoutingAlternativeRequestDTO { +public class RoutingAlternativeRequestDTO implements DirectionsRequest { @NotNull private Double originLat; @NotNull diff --git a/src/main/java/SuMoC/backend/routing/dtos/RoutingDirectionsRequestDTO.java b/src/main/java/SuMoC/backend/routing/dtos/RoutingDirectionsRequestDTO.java new file mode 100644 index 0000000..5607759 --- /dev/null +++ b/src/main/java/SuMoC/backend/routing/dtos/RoutingDirectionsRequestDTO.java @@ -0,0 +1,27 @@ +package SuMoC.backend.routing.dtos; + +import SuMoC.backend.carta.DirectionsRequest; +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.annotation.Nullable; +import lombok.Getter; +import lombok.Setter; + +import java.time.Instant; + +@Getter +@Setter +@Schema(description = "DTO representing a request for routing directions between two points. Points can be specified either by coordinates or addresses." + + "If both provided, coordinates are preferred.") +public class RoutingDirectionsRequestDTO implements DirectionsRequest { + private Double originLat; + private Double originLon; + private Double destinationLat; + private Double destinationLon; + private String originAddress; + private String destinationAddress; + private Instant arrivalTime; + private Instant departureTime; + @Nullable + @Schema(description = "Routing preferences to customize the routing behavior. If null, will search for stored user preferences, if not found, use default.") + private RoutingPreferencesDTO routingPreferencesDTO; +} diff --git a/src/main/java/SuMoC/backend/routing/dtos/RoutingPreferencesDTO.java b/src/main/java/SuMoC/backend/routing/dtos/RoutingPreferencesDTO.java index 5d17f4a..45a3e46 100644 --- a/src/main/java/SuMoC/backend/routing/dtos/RoutingPreferencesDTO.java +++ b/src/main/java/SuMoC/backend/routing/dtos/RoutingPreferencesDTO.java @@ -12,7 +12,9 @@ import java.util.List; @Setter @Schema(description = "This DTO represents the user preferences for routing / alternative route suggestions.") public class RoutingPreferencesDTO { + @Schema(description = "Whether to prefer alternative routes that involve physical activity (walking, cycling) when suggestin alternative routes.") private boolean preferPhysicalActivity = false; + @Schema(description = "Whether to consider current weather conditions when suggesting alternative routes.") private boolean considerWeatherConditions = true; private List modalitiesToConsider = new ArrayList<>( List.of(Modality.WALKING, Modality.BICYCLE, Modality.ESCOOTER, Modality.BUS, Modality.TRAM, Modality.TRAIN) diff --git a/src/main/java/SuMoC/backend/routing/dtos/StepDTO.java b/src/main/java/SuMoC/backend/routing/dtos/StepDTO.java index 583ef28..1f98956 100644 --- a/src/main/java/SuMoC/backend/routing/dtos/StepDTO.java +++ b/src/main/java/SuMoC/backend/routing/dtos/StepDTO.java @@ -14,6 +14,5 @@ import lombok.Setter; @Schema(description = "A single step within a suggested alternative route.") public class StepDTO { private Modality modality; - private String lineNumber; private double distanceMeters; } diff --git a/src/main/java/SuMoC/backend/routing/dtos/TransitStepDTO.java b/src/main/java/SuMoC/backend/routing/dtos/TransitStepDTO.java new file mode 100644 index 0000000..9ad088e --- /dev/null +++ b/src/main/java/SuMoC/backend/routing/dtos/TransitStepDTO.java @@ -0,0 +1,24 @@ +package SuMoC.backend.routing.dtos; + +import SuMoC.backend.trip.Modality; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@Schema(description = "A single transit step within a suggested alternative route.") +public class TransitStepDTO extends StepDTO { + private String lineNumber; + private String lineHeadsign; + private String startStop; + private String endStop; + + public TransitStepDTO(Modality modality, double distanceMeters, String lineNumber, String lineHeadsign, String startStop, String endStop) { + super(modality, distanceMeters); + this.lineNumber = lineNumber; + this.lineHeadsign = lineHeadsign; + this.startStop = startStop; + this.endStop = endStop; + } +} diff --git a/src/main/java/SuMoC/backend/routing/services/AlternativeRoutingService.java b/src/main/java/SuMoC/backend/routing/services/AlternativeRoutingService.java new file mode 100644 index 0000000..a6c2f34 --- /dev/null +++ b/src/main/java/SuMoC/backend/routing/services/AlternativeRoutingService.java @@ -0,0 +1,89 @@ +package SuMoC.backend.routing.services; + +import SuMoC.backend.carta.DirectionsService; +import SuMoC.backend.routing.config.AdHocRoutingProperties; +import SuMoC.backend.routing.config.OnCallRoutingProperties; +import SuMoC.backend.routing.dtos.RouteDTO; +import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * Service to determine alternative routes for a given routing request. + */ +@Service +@RequiredArgsConstructor +public class AlternativeRoutingService { + + private final AlternativeFilterService alternativeFilterService; + + private final OnCallRoutingProperties onCallRoutingProperties; + + private final AdHocRoutingProperties adHocRoutingProperties; + + private final DirectionsService directionsService; + + /** + * Gets possible routes from CARTA, converts them to our format and applies filter to only provide acceptable solutions without excessive additional travel time. + * This is the public method for alternatives explicitly asked for by the client. + */ + public List determineAlternativeRoutesOnUserRequest(RoutingAlternativeRequestDTO requestDTO) { + List routes = directionsService.getPossibleAlternativeRoutes(requestDTO); + routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, onCallRoutingProperties); + + return routes; + } + + /** + * Public alternative retrieval method which is used to check for alternatives we suggest to user via notification + * right after user finished the trip. + * Similar to determineAlternativeRoutesOnUserRequest but here we apply stricter thresholds for alternatives + * and also apply weather filtering (if enabled) to not suggest routes the user definitly would not have consideres. + */ + public List determineAlternativeRoutesAdHoc(RoutingAlternativeRequestDTO requestDTO) { + assert requestDTO.getRoutingPreferencesDTO() != null; + + List routes = directionsService.getPossibleAlternativeRoutes(requestDTO); + routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, adHocRoutingProperties); + + if (requestDTO.getRoutingPreferencesDTO().isConsiderWeatherConditions()) { + routes = alternativeFilterService.filterForBadWeather(requestDTO, routes, adHocRoutingProperties); + } + + return routes; + } + + public RouteDTO determineBestAlternativeRouteForRegularTrip(RoutingAlternativeRequestDTO requestDTO) { + assert requestDTO.getRoutingPreferencesDTO() != null; + + // TODO for now we use adHocRoutingProperties here, in the future we might want to have separate properties for regular trip alternatives + List routes = directionsService.getPossibleAlternativeRoutes(requestDTO); + routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, adHocRoutingProperties); + if (requestDTO.getRoutingPreferencesDTO().isConsiderWeatherConditions()) { + routes = alternativeFilterService.filterForBadWeather(requestDTO, routes, adHocRoutingProperties); + } + + RouteDTO bestRoute = null; + // if users wants physical activity, we pick the fastest physical activity route, if any + if (requestDTO.getRoutingPreferencesDTO().isPreferPhysicalActivity()) { + bestRoute = routes.stream() + .filter(RouteDTO::isPhysicalActivity) + .min((r1, r2) -> Long.compare( + r1.getDurationSeconds(), + r2.getDurationSeconds() + )).orElse(null); + if (bestRoute != null) { + return bestRoute; + } + } + // else we pick the fastest route overall + bestRoute = routes.stream() + .min((r1, r2) -> Long.compare( + r1.getDurationSeconds(), + r2.getDurationSeconds() + )).orElse(null); + return bestRoute; + } +} diff --git a/src/main/java/SuMoC/backend/routing/services/CartaTransitRouteProcessor.java b/src/main/java/SuMoC/backend/routing/services/CartaTransitRouteProcessor.java index 8c16522..015ce8b 100644 --- a/src/main/java/SuMoC/backend/routing/services/CartaTransitRouteProcessor.java +++ b/src/main/java/SuMoC/backend/routing/services/CartaTransitRouteProcessor.java @@ -1,6 +1,7 @@ package SuMoC.backend.routing.services; import SuMoC.backend.routing.dtos.StepDTO; +import SuMoC.backend.routing.dtos.TransitStepDTO; import SuMoC.backend.trip.Modality; import sumoc.backend.carta.client.model.Route; import sumoc.backend.carta.client.model.Step; @@ -28,7 +29,7 @@ public class CartaTransitRouteProcessor { /** * Extracts information from the route. */ - public void process() { + private void process() { ArrayList steps = new ArrayList<>(); assert cartaRoute.getSteps() != null; @@ -46,11 +47,21 @@ public class CartaTransitRouteProcessor { ? Modality.fromCartaString(step.getLine().getType().toString()) : Modality.fromCartaString(step.getType()); - steps.add(new StepDTO( - stepModality, - step.getType().equals("TransitStep") ? step.getLine().getCode() : null, - step.getDistance() - )); + if (step.getType().equals("TransitStep")) { + steps.add(new TransitStepDTO( + stepModality, + step.getDistance(), + step.getLine().getCode(), + step.getLine().getHeadsign(), + step.getStops().getFirst().getName(), + step.getStops().getLast().getName() + )); + } else { + steps.add(new StepDTO( + stepModality, + step.getDistance() + )); + } } this.steps = steps; diff --git a/src/main/java/SuMoC/backend/routing/services/DirectionsRoutingService.java b/src/main/java/SuMoC/backend/routing/services/DirectionsRoutingService.java new file mode 100644 index 0000000..a0002e8 --- /dev/null +++ b/src/main/java/SuMoC/backend/routing/services/DirectionsRoutingService.java @@ -0,0 +1,23 @@ +package SuMoC.backend.routing.services; + +import SuMoC.backend.carta.DirectionsService; +import SuMoC.backend.routing.dtos.RouteDTO; +import SuMoC.backend.routing.dtos.RoutingDirectionsRequestDTO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * Service for getting directions between two given points. + */ +@Service +@RequiredArgsConstructor +public class DirectionsRoutingService { + + private final DirectionsService directionsService; + + public List getDirections(RoutingDirectionsRequestDTO requestDTO) { + return directionsService.getPossibleRoutes(requestDTO, true); + } +} diff --git a/src/main/java/SuMoC/backend/security/SecurityConfiguration.java b/src/main/java/SuMoC/backend/security/SecurityConfiguration.java index 717d643..d1f0e08 100644 --- a/src/main/java/SuMoC/backend/security/SecurityConfiguration.java +++ b/src/main/java/SuMoC/backend/security/SecurityConfiguration.java @@ -94,6 +94,7 @@ public class SecurityConfiguration { auth.requestMatchers("/logs").permitAll(); auth.requestMatchers("/routing/alternative/**").permitAll(); auth.requestMatchers("/auth/user/**").permitAll(); + auth.requestMatchers("/routing/directions/**").permitAll(); auth.requestMatchers("/admin/**").hasRole("ADMIN"); //looks for "ROLE_ADMIN" //alternative: hasAuthoritiy("ADMIN") auth.requestMatchers("/user/**").hasAnyRole("ADMIN", "USER"); auth.requestMatchers("/friendship/**").hasAnyRole("ADMIN", "USER"); diff --git a/src/main/java/SuMoC/backend/suggestion/services/AdHocSuggestionService.java b/src/main/java/SuMoC/backend/suggestion/services/AdHocSuggestionService.java index be623a8..303d607 100644 --- a/src/main/java/SuMoC/backend/suggestion/services/AdHocSuggestionService.java +++ b/src/main/java/SuMoC/backend/suggestion/services/AdHocSuggestionService.java @@ -6,8 +6,8 @@ import SuMoC.backend.notification.services.NotificationSchedulerService; import SuMoC.backend.routing.dtos.RouteDTO; import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO; import SuMoC.backend.routing.dtos.RoutingPreferencesDTO; +import SuMoC.backend.routing.services.AlternativeRoutingService; import SuMoC.backend.routing.services.RoutingPreferencesService; -import SuMoC.backend.routing.services.RoutingService; import SuMoC.backend.suggestion.config.AdHocSuggestionProperties; import SuMoC.backend.trip.Modality; import SuMoC.backend.trip.models.Trip; @@ -23,7 +23,7 @@ import java.util.List; @RequiredArgsConstructor public class AdHocSuggestionService { - private final RoutingService routingService; + private final AlternativeRoutingService alternativeRoutingService; private final RoutingPreferencesService routingPreferencesService; @@ -42,7 +42,7 @@ public class AdHocSuggestionService { return; // only suggest alternatives for trips mainly done by car, motorcycle or taxi } - var viableAlternatives = routingService.determineAlternativeRoutesAdHoc(alternativeRequestFromTrip(newTrip)); + var viableAlternatives = alternativeRoutingService.determineAlternativeRoutesAdHoc(alternativeRequestFromTrip(newTrip)); if (!viableAlternatives.isEmpty()) { // Since notification bodies have a size limit, we only send the best alternative diff --git a/src/main/java/SuMoC/backend/suggestion/services/RegularTripSuggestionService.java b/src/main/java/SuMoC/backend/suggestion/services/RegularTripSuggestionService.java index 3ffc48b..bd223a9 100644 --- a/src/main/java/SuMoC/backend/suggestion/services/RegularTripSuggestionService.java +++ b/src/main/java/SuMoC/backend/suggestion/services/RegularTripSuggestionService.java @@ -7,8 +7,8 @@ import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO; import SuMoC.backend.regulartrip.services.RegularTripDetectionService; import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO; import SuMoC.backend.routing.dtos.RoutingPreferencesDTO; +import SuMoC.backend.routing.services.AlternativeRoutingService; import SuMoC.backend.routing.services.RoutingPreferencesService; -import SuMoC.backend.routing.services.RoutingService; import SuMoC.backend.suggestion.config.RegularTripSuggestionProperties; import com.uber.h3core.util.LatLng; import lombok.RequiredArgsConstructor; @@ -25,7 +25,7 @@ import java.util.List; @RequiredArgsConstructor public class RegularTripSuggestionService { - private final RoutingService routingService; + private final AlternativeRoutingService alternativeRoutingService; private final RoutingPreferencesService routingPreferencesService; @@ -56,7 +56,7 @@ public class RegularTripSuggestionService { var alternativeRequest = createAlternativeRequest(detectedRegularTrip); alternativeRequest.setRoutingPreferencesDTO(preferencesDTO); - var bestAlternative = routingService.determineBestAlternativeRouteForRegularTrip(alternativeRequest); + var bestAlternative = alternativeRoutingService.determineBestAlternativeRouteForRegularTrip(alternativeRequest); // if present, schedule notification if (bestAlternative != null) { notificationSchedulerService.schedule(