implement routing/drections endpoint for requesting routes without alternatives logic, includes refactoring of previous alternative routing logic into carta DirectionsService to reuse code
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good

This commit is contained in:
2026-02-01 18:07:37 +01:00
parent 6aaff14c0d
commit cb397e7e63
16 changed files with 466 additions and 237 deletions
@@ -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);
}
@@ -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<RouteDTO> 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<Direction> 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<RouteDTO> getPossibleRoutes(DirectionsRequest requestDTO, boolean includeCarRoute) {
assert requestDTO.getRoutingPreferencesDTO() != null;
HashMap<String, Direction> directionMap = getPossibleDirections(requestDTO);
ArrayList<RouteDTO> 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<StepDTO> 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<StepDTO> 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<StepDTO> 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<String, Direction> getPossibleDirectionsFromCarta(RoutingAlternativeRequestDTO requestDTO) {
private HashMap<String, Direction> getPossibleDirections(DirectionsRequest requestDTO) {
Map<String, CompletableFuture<Direction>> 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<RouteDTO> determineAlternativeRoutesOnUserRequest(RoutingAlternativeRequestDTO requestDTO) {
List<RouteDTO> 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<RouteDTO> determineAlternativeRoutesAdHoc(RoutingAlternativeRequestDTO requestDTO) {
assert requestDTO.getRoutingPreferencesDTO() != null;
List<RouteDTO> 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<RouteDTO> 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<RouteDTO> getPossibleAlternativeRoutes(RoutingAlternativeRequestDTO requestDTO) {
assert requestDTO.getRoutingPreferencesDTO() != null;
HashMap<String, Direction> directionMap = getPossibleDirectionsFromCarta(requestDTO);
ArrayList<RouteDTO> 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<Direction> 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<StepDTO> 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<StepDTO> 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;
}
}
@@ -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
@@ -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<List<RouteDTO>> 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.");
}
}
}
@@ -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<StepDTO> 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;
@@ -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
@@ -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;
}
@@ -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<Modality> modalitiesToConsider = new ArrayList<>(
List.of(Modality.WALKING, Modality.BICYCLE, Modality.ESCOOTER, Modality.BUS, Modality.TRAM, Modality.TRAIN)
@@ -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;
}
@@ -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;
}
}
@@ -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<RouteDTO> determineAlternativeRoutesOnUserRequest(RoutingAlternativeRequestDTO requestDTO) {
List<RouteDTO> 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<RouteDTO> determineAlternativeRoutesAdHoc(RoutingAlternativeRequestDTO requestDTO) {
assert requestDTO.getRoutingPreferencesDTO() != null;
List<RouteDTO> 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<RouteDTO> 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;
}
}
@@ -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<StepDTO> 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;
@@ -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<RouteDTO> getDirections(RoutingDirectionsRequestDTO requestDTO) {
return directionsService.getPossibleRoutes(requestDTO, true);
}
}
@@ -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");
@@ -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
@@ -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(