route_alternatives into main #3

Merged
neuhauss merged 11 commits from route_alternatives into main 2026-01-06 14:08:34 +01:00
27 changed files with 555 additions and 386 deletions
+8 -3
View File
@@ -154,15 +154,20 @@
<source>21</source>
<target>21</target>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.32</version>
</path>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.5.5.Final</version>
<version>1.6.3</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
<artifactId>lombok-mapstruct-binding</artifactId>
<version>0.2.0</version>
</path>
</annotationProcessorPaths>
<!--<compilerArgs>- -enable-preview</compilerArgs> -->
@@ -0,0 +1,37 @@
package SuMoC.backend.geocoding;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Setter
@Getter
@NoArgsConstructor
public class AddressDTO {
// Getters and setters
private String houseNumber;
private String road;
private String suburb;
private String cityDistrict;
private String city;
private String state;
private String iso3166_2_lvl4;
private String postcode;
private String country;
private String countryCode;
// Constructor with fields
public AddressDTO(String houseNumber, String road, String suburb, String cityDistrict, String city, String state, String iso3166_2_lvl4, String postcode, String country, String countryCode) {
this.houseNumber = houseNumber;
this.road = road;
this.suburb = suburb;
this.cityDistrict = cityDistrict;
this.city = city;
this.state = state;
this.iso3166_2_lvl4 = iso3166_2_lvl4;
this.postcode = postcode;
this.country = country;
this.countryCode = countryCode;
}
}
@@ -0,0 +1,37 @@
package SuMoC.backend.geocoding;
import SuMoC.backend.nominatim.NominatimClient;
import SuMoC.backend.nominatim.ReverseResponse;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
@Service
public class GeoCodingService {
private final NominatimClient nominatimClient;
public GeoCodingService(NominatimClient nominatimClient) {
this.nominatimClient = nominatimClient;
}
public Mono<AddressDTO> getAddress(double lat, double lon) {
return nominatimClient.reverse(lat, lon)
.map(this::mapToAddressDTO);
}
private AddressDTO mapToAddressDTO(ReverseResponse response) {
var addressMap = response.address();
return new AddressDTO(
addressMap.get("house_number"),
addressMap.get("road"),
addressMap.get("suburb"),
addressMap.get("city_district"),
addressMap.get("city"),
addressMap.get("state"),
addressMap.get("ISO3166-2-lvl4"),
addressMap.get("postcode"),
addressMap.get("country"),
addressMap.get("country_code")
);
}
}
@@ -1,7 +1,5 @@
package SuMoC.backend.geocoding;
import SuMoC.backend.nominatim.NominatimClient;
import SuMoC.backend.nominatim.ReverseResponse;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -13,15 +11,15 @@ import reactor.core.publisher.Mono;
@RequestMapping("/geocoding")
public class GeocodingController {
private final NominatimClient nominatimClient;
private final GeoCodingService geoCodingService;
public GeocodingController(NominatimClient nominatimClient) {
this.nominatimClient = nominatimClient;
public GeocodingController(GeoCodingService geoCodingService) {
this.geoCodingService = geoCodingService;
}
@GetMapping("/reverse")
@Operation(description = "Returns the OSM location at the given lat / lon including the address.")
public Mono<ReverseResponse> reverse(@RequestParam double lat, @RequestParam double lon) {
return nominatimClient.reverse(lat, lon);
@Operation(description = "Returns the address at the given lat / lon.")
public Mono<AddressDTO> reverse(@RequestParam double lat, @RequestParam double lon) {
return geoCodingService.getAddress(lat, lon);
}
}
@@ -0,0 +1,7 @@
Weather client based on the public API from https://open-meteo.com:
[Forecast](https://open-meteo.com/en/docs)
- to be used for future and
[Historical Weather](https://open-meteo.com/en/docs/historical-weather-api)
@@ -4,13 +4,17 @@ import SuMoC.backend.routing.dtos.RouteDTO;
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
import SuMoC.backend.routing.dtos.RoutingPreferencesDTO;
import jakarta.validation.Valid;
import org.apache.commons.lang3.NotImplementedException;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.reactive.function.client.WebClientRequestException;
import sumoc.backend.carta.client.model.Route;
import java.util.ArrayList;
import java.util.List;
@RestController
@@ -26,19 +30,22 @@ public class RoutingController {
// TODO operation description + how to handle preferences (optional, if not provided use saved users prefs or default
@PostMapping("/request")
public ResponseEntity<List<RouteDTO>> requestAlternativeRoutes(@Valid @RequestBody RoutingAlternativeRequestDTO routingAlternativeRequestDTO) {
RoutingPreferencesDTO preferences = routingAlternativeRequestDTO.getRoutingPreferencesDTO();
if (preferences == null) { // Use default preferences if none are provided
// TODO we might want to also save users preferences in the future
preferences = new RoutingPreferencesDTO(); // use default preferences
routingAlternativeRequestDTO.setRoutingPreferencesDTO(preferences);
try {
if (routingAlternativeRequestDTO.getRoutingPreferencesDTO() == null) { // Use default preferences if none are provided
// TODO we might want to also save users preferences in the future
var preferences = new RoutingPreferencesDTO(); // use default preferences
routingAlternativeRequestDTO.setRoutingPreferencesDTO(preferences);
}
var routeDTOs = routingService.getAlternativeRoute(routingAlternativeRequestDTO);
return ResponseEntity.ok(routeDTOs);
} catch (WebClientRequestException e) {
// nominatim container is not up yet, we return mock
ArrayList<RouteDTO> mockDTOs = new ArrayList<>();
mockDTOs.add(RouteDTO.getMockRouteDTO());
mockDTOs.add(RouteDTO.getMockRouteDTO());
mockDTOs.add(RouteDTO.getMockRouteDTO());
return ResponseEntity.ok(mockDTOs);
}
//var routeDTOs = routingService.getAlternativeRoute(routingAlternativeRequestDTO);
// Mocking response for app development
var routeDTOs = List.of(RouteDTO.getMockRouteDTO());
return ResponseEntity.ok(routeDTOs);
}
}
@@ -1,12 +1,20 @@
package SuMoC.backend.routing;
import SuMoC.backend.carta.CartaClient;
import SuMoC.backend.geocoding.AddressDTO;
import SuMoC.backend.geocoding.GeoCodingService;
import SuMoC.backend.routing.config.RoutingProperties;
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.trip.Modality;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import sumoc.backend.carta.client.model.Direction;
import sumoc.backend.carta.client.model.Route;
import java.util.ArrayList;
import java.util.HashMap;
@@ -17,11 +25,17 @@ import java.util.concurrent.CompletableFuture;
@Service
public class RoutingService {
private final GeoCodingService geoCodingService;
private final CartaClient cartaClient;
private final RoutingProperties routingProperties;
@Autowired
public RoutingService(CartaClient cartaClient) {
public RoutingService(CartaClient cartaClient, RoutingProperties routingProperties, GeoCodingService geoCodingService) {
this.cartaClient = cartaClient;
this.routingProperties = routingProperties;
this.geoCodingService = geoCodingService;
}
/**
@@ -50,6 +64,11 @@ public class RoutingService {
/**
* Makes concurrent direction calls to CARTA for all modes requested + car as baseline.
* Possible keys of the returned Map:
* - car (always)
* - walk (optional)
* - bike (optional)
* - transit (optional)
*/
private HashMap<String, Direction> getPossibleDirectionsFromCarta(RoutingAlternativeRequestDTO requestDTO) {
Map<String, CompletableFuture<Direction>> futuresByMode = new HashMap<>();
@@ -62,8 +81,8 @@ public class RoutingService {
// add request futures for all modes request by user + assemble type string for a possible transit directions request
for (Modality modality : requestDTO.getRoutingPreferencesDTO().getModalitiesToConsider()) {
switch (modality) {
case WALK -> futuresByMode.put("walk", getCartaFuture(requestDTO, "walking", "", 1));
case BIKE -> futuresByMode.put("bike", getCartaFuture(requestDTO, "cycling", "", 1));
case WALKING -> futuresByMode.put("walk", getCartaFuture(requestDTO, "walking", "", 1));
case BICYCLE -> futuresByMode.put("bike", getCartaFuture(requestDTO, "cycling", "", 1));
case BUS -> {
typeList.add("3"); // bus
typeList.add("8"); // trolleybus
@@ -95,18 +114,111 @@ public class RoutingService {
}
public List<RouteDTO> getAlternativeRoute(RoutingAlternativeRequestDTO requestDTO) {
HashMap<String, Direction> directionHashMap = getPossibleDirectionsFromCarta(requestDTO);
assert requestDTO.getRoutingPreferencesDTO() != null;
HashMap<String, Direction> directionMap = getPossibleDirectionsFromCarta(requestDTO);
ArrayList<RouteDTO> suggestedAlternatives = new ArrayList<>();
// if consider weather
// 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();
// Define max additional time for sustainable alternatives
int maxAdditionalTimeNonPhysical = routingProperties.getToleratedAdditionalTravelSeconds();
int maxAdditionalTimePhysical = requestDTO.getRoutingPreferencesDTO().isPreferPhysicalActivity() ?
routingProperties.getToleratedAdditionalPhysicalActivitiesSeconds() :
routingProperties.getToleratedAdditionalTravelSeconds();
// 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();
int durationDifferenceCar = bikeRoute.getDuration() - carRoute.getDuration();
if (durationDifferenceCar < maxAdditionalTimePhysical) {
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()
);
suggestedAlternatives.add(routeDTO);
}
}
}
if (directionMap.containsKey("walk")) {
Direction walkDirection = directionMap.get("walk");
if (walkDirection.getRoutes() != null && !walkDirection.getRoutes().isEmpty()) {
Route walkRoute = walkDirection.getRoutes().getFirst();
int durationDifferenceCar = walkRoute.getDuration() - carRoute.getDuration();
if (durationDifferenceCar < maxAdditionalTimePhysical) {
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()
);
suggestedAlternatives.add(routeDTO);
}
}
}
// TODO public transit
// TODO if consider weather
// get weather for origin
// if bad, remove walking and biking options
// filter applicable routes (car is only baseline, never suggested)
// certain threshold how much more delay is okay
// apply physical preference if set
// convert remaining routes to routedto
return new ArrayList<RouteDTO>();
return suggestedAlternatives;
}
}
@@ -0,0 +1,9 @@
package SuMoC.backend.routing.config;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties(RoutingProperties.class)
public class RoutingConfig {
}
@@ -0,0 +1,13 @@
package SuMoC.backend.routing.config;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "routing")
@Getter
@Setter
public class RoutingProperties {
private int toleratedAdditionalTravelSeconds = 15 * 60;
private int toleratedAdditionalPhysicalActivitiesSeconds = 45 * 60;
}
@@ -1,9 +1,9 @@
package SuMoC.backend.routing.dtos;
import SuMoC.backend.geocoding.AddressDTO;
import SuMoC.backend.trip.Modality;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.annotation.Nullable;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@@ -15,11 +15,10 @@ import java.util.List;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "This DTO represents a suggested route as a response to a requested alternative route.")
public class RouteDTO {
@Schema(description = "The actual address of the start location.")
private String startAddress;
private AddressDTO startAddress;
@Schema(description = "The name of the first stop if the route uses public transport. E.g. \"Essen West\" if the route starts with a footpath to the first train leaving there.")
@Nullable
private String firstStopName;
@@ -28,14 +27,14 @@ public class RouteDTO {
@Schema(description = "The longitude of the start address.")
private double startLon;
@Schema(description = "The actual address of the end location.")
private String endAddress;
private AddressDTO endAddress;
@Schema(description = "The name of the last stop if the route uses public transport. E.g. \"Essen Hbf\" if the route ends with a train arriving there (might still contain a footpath afterwards).")
@Nullable
private String lastStopName;
@Schema(description = "The latitude of the end address.")
private String endLat;
private double endLat;
@Schema(description = "The longitude of the end address.")
private String endLon;
private double endLon;
@Schema(description = "The start date and time of the route.")
private LocalDateTime startDateTime;
@Schema(description = "The end date and time of the route.")
@@ -43,9 +42,25 @@ public class RouteDTO {
@Schema(description = "The steps the route consists of.")
private List<StepDTO> steps;
@Schema(description = "Amount of CO2e savings in gramm compared to a car trip for the same route.")
private float co2Savings;
private double co2Savings;
@Schema(description = "The temporal difference in minutes compared to the original route the user requested alternatives for.")
private float timeDifferenceMinutes;
private double timeDifferenceSeconds;
public RouteDTO(AddressDTO startAddress, @Nullable String firstStopName, double startLat, double startLon, AddressDTO endAddress, @Nullable String lastStopName, double endLat, double endLon, LocalDateTime startDateTime, LocalDateTime endDateTime, List<StepDTO> steps, double co2Savings, double timeDifferenceSeconds) {
this.startAddress = startAddress;
this.firstStopName = firstStopName;
this.startLat = startLat;
this.startLon = startLon;
this.endAddress = endAddress;
this.lastStopName = lastStopName;
this.endLat = endLat;
this.endLon = endLon;
this.startDateTime = startDateTime;
this.endDateTime = endDateTime;
this.steps = steps;
this.co2Savings = co2Savings;
this.timeDifferenceSeconds = timeDifferenceSeconds;
}
/**
* Mock method for testing purposes
@@ -53,15 +68,39 @@ public class RouteDTO {
* @return RouteDto with mock data
*/
public static RouteDTO getMockRouteDTO() {
var startAddress = new AddressDTO(
"28a",
"Janssenstraße",
"Holsterhausen",
"Stadtbezirk III",
"Essen",
"Nordrhein-Westfalen",
"DE-NW",
"45147",
"Deutschland",
"de"
);
var endAddress = new AddressDTO(
"70",
"Schützenbahn",
null,
null,
"Essen",
"Nordrhein-Westfalen",
"DE-NW",
"45127",
"Deutschland",
"de"
);
var dto = new RouteDTO(
"Janssenstraße 28a, 45147 Essen, Germany",
startAddress,
"Rubensstraße",
51.440395,
6.984785,
"Schützenbahn 70, 45127 Essen, Germany",
endAddress,
"Viehhofer Platz",
"51.459167",
"7.014928",
51.459167,
7.014928,
LocalDateTime.now().minusMinutes(30),
LocalDateTime.now(),
new ArrayList<StepDTO>(),
@@ -69,7 +108,7 @@ public class RouteDTO {
+16.3f
);
dto.steps.add(new StepDTO(
Modality.WALK,
Modality.WALKING,
null,
400f
));
@@ -79,7 +118,7 @@ public class RouteDTO {
5000f
));
dto.steps.add(new StepDTO(
Modality.WALK,
Modality.WALKING,
null,
300f
));
@@ -13,13 +13,13 @@ import java.time.LocalDateTime;
@Schema(description = "This DTO represents a request for alternative routes between an origin and a destination.")
public class RoutingAlternativeRequestDTO {
@NotNull
private String originLat;
private Double originLat;
@NotNull
private String originLon;
private Double originLon;
@NotNull
private String destinationLat;
private Double destinationLat;
@NotNull
private String destinationLon;
private Double destinationLon;
@NotNull
private LocalDateTime arrivalTime;
@NotNull
@@ -15,6 +15,6 @@ public class RoutingPreferencesDTO {
private boolean preferPhysicalActivity = false;
private boolean considerWeatherConditions = true;
private List<Modality> modalitiesToConsider = new ArrayList<>(
List.of(Modality.WALK, Modality.BIKE, Modality.ESCOOTER, Modality.BUS, Modality.TRAM, Modality.TRAIN)
List.of(Modality.WALKING, Modality.BICYCLE, Modality.ESCOOTER, Modality.BUS, Modality.TRAM, Modality.TRAIN)
);
}
@@ -15,5 +15,5 @@ import lombok.Setter;
public class StepDTO {
private Modality modality;
private String lineNumber;
private float distanceMeters;
private double distanceMeters;
}
@@ -0,0 +1,7 @@
package SuMoC.backend.routing.exceptions;
public class NoCarRouteFoundException extends RuntimeException {
public NoCarRouteFoundException(String message) {
super(message);
}
}
@@ -0,0 +1,7 @@
package SuMoC.backend.routing.exceptions;
public class NoCarbonEmissionFoundException extends RuntimeException {
public NoCarbonEmissionFoundException(String message) {
super(message);
}
}
@@ -1,7 +1,9 @@
package SuMoC.backend.security.dtos;
import jakarta.validation.constraints.NotNull;
import lombok.Builder;
@Builder
public class UserRegistrationDTO {
@NotNull
@@ -0,0 +1,41 @@
package SuMoC.backend.seed.trip;
import SuMoC.backend.trip.TripFactory;
import SuMoC.backend.trip.TripService;
import SuMoC.backend.trip.dtos.NewTripDTO;
import SuMoC.backend.user.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Profile("dev")
@Order(2)
public class DevTripSeeder implements CommandLineRunner {
private final TripService tripService;
private final UserRepository userRepository;
@Autowired
public DevTripSeeder(TripService tripService, UserRepository userRepository) {
this.tripService = tripService;
this.userRepository = userRepository;
}
@Override
public void run(String... args) throws Exception {
// Iterate over all users and create 5 random trips for each
userRepository.findAll().forEach(user -> {
for (int i = 0; i < 5; i++) {
NewTripDTO newTrip = TripFactory.randomNewTripDTO(
java.time.LocalDateTime.now().minusDays((long) (Math.random() * 30))
);
tripService.addTrip(user, newTrip);
}
});
}
}
@@ -0,0 +1,40 @@
package SuMoC.backend.seed.user;
import SuMoC.backend.security.dtos.UserRegistrationDTO;
import SuMoC.backend.security.services.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Profile("dev")
@Order(1)
public class DevUserSeeder implements CommandLineRunner {
private final AuthenticationService authenticationService;
@Autowired
public DevUserSeeder(AuthenticationService authenticationService) {
this.authenticationService = authenticationService;
}
@Override
public void run(String... args) throws Exception {
UserRegistrationDTO user1 = UserRegistrationDTO.builder()
.email("user1@email.com")
.publicName("Nutzer 1 Public")
.privateName("Nutzer 1 Privat")
.password("password1")
.build();
authenticationService.registerUser(user1);
UserRegistrationDTO user2 = UserRegistrationDTO.builder()
.email("user2@email.com")
.publicName("Nutzer 2 Public")
.privateName("Nutzer 2 Privat")
.password("password2")
.build();
authenticationService.registerUser(user2);
}
}
@@ -2,11 +2,13 @@ package SuMoC.backend.trip;
public enum Modality {
IDLE,
WALK,
BIKE,
WALKING,
BICYCLE,
ESCOOTER,
BUS,
TRAM,
TRAIN,
CAR
CAR,
MOTORCYCLE,
TAXI
}
@@ -0,0 +1,64 @@
package SuMoC.backend.trip;
import SuMoC.backend.trip.dtos.NewTripDTO;
import SuMoC.backend.trip.dtos.NewTripSegmentDTO;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
@NoArgsConstructor
public class TripFactory {
private static final List<String> NRW_CITIES = List.of(
"Cologne", "Düsseldorf", "Dortmund", "Essen", "Bonn",
"Aachen", "Wuppertal", "Münster", "Bielefeld", "Bochum"
);
private static Modality randomModality() {
Modality[] modalities = Modality.values();
return modalities[ThreadLocalRandom.current().nextInt(modalities.length)];
}
/**
* Generates a random NewTripDTO that always consists of two random segments that start at the given startTime,
* take 2 hours in total, and have random start and end places from a predefined list of NRW cities.
* So data is not really realistic.
*/
public static NewTripDTO randomNewTripDTO(LocalDateTime startTime) {
String startPlace = NRW_CITIES.get(ThreadLocalRandom.current().nextInt(NRW_CITIES.size()));
String endPlace = NRW_CITIES.get(ThreadLocalRandom.current().nextInt(NRW_CITIES.size()));
while (endPlace.equals(startPlace)) {
endPlace = NRW_CITIES.get(ThreadLocalRandom.current().nextInt(NRW_CITIES.size()));
}
Set<NewTripSegmentDTO> segments = Set.of(
NewTripSegmentDTO.builder()
.modality(randomModality())
.startTime(startTime)
.distanceMeters(ThreadLocalRandom.current().nextFloat() * 10000)
.build(),
NewTripSegmentDTO.builder()
.modality(randomModality())
.startTime(startTime.plusMinutes(60))
.distanceMeters(ThreadLocalRandom.current().nextFloat() * 10000)
.build()
);
return NewTripDTO.builder()
.startPlace(startPlace)
.endPlace(endPlace)
.startLatitude(51.4617108)
.startLongitude(7.0170745)
.endLatitude(51.4319410541684)
.endLongitude(6.800951430299369)
.co2Emissions(100.0)
.startTime(startTime)
.endTime(startTime.plusMinutes(120))
.mobilityScore(ThreadLocalRandom.current().nextFloat() * 100)
.tripSegments(segments)
.build();
}
}
@@ -1,9 +1,9 @@
package SuMoC.backend.trip.dtos;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.*;
import java.time.LocalDateTime;
import java.util.Set;
@@ -12,73 +12,26 @@ import java.util.Set;
* DTO representing a trip submitted from the App which is not yet persisted in the database.
* TODO assumption is that cost of trip is calculated server-side
*/
@Builder
@Schema(description = "DTO for creating a new Trip")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class NewTripDTO {
private String startPlace; // High level description of the trip's starting location
private String endPlace; // High level description of the trip's ending location
@Schema(description = "High level description of the trip's starting location")
private String startPlace;
private double startLatitude;
private double startLongitude;
@Schema(description = "High level description of the trip's ending location")
private String endPlace;
private double endLatitude;
private double endLongitude;
private LocalDateTime startTime;
private LocalDateTime endTime;
private float mobilityScore;
private double mobilityScore;
private double co2Emissions;
@NotNull
@Size(min = 1, message = "Trip must contain at least one segment.")
private Set<NewTripSegmentDTO> tripSegments;
public NewTripDTO() {}
public NewTripDTO (String startPlace, String endPlace, LocalDateTime startTime, LocalDateTime endTime, float mobilityScore, Set<NewTripSegmentDTO> tripSegments) {
this.startPlace = startPlace;
this.endPlace = endPlace;
this.startTime = startTime;
this.endTime = endTime;
this.mobilityScore = mobilityScore;
this.tripSegments = tripSegments;
}
public String getStartPlace() {
return startPlace;
}
public void setStartPlace(String startPlace) {
this.startPlace = startPlace;
}
public String getEndPlace() {
return endPlace;
}
public void setEndPlace(String endPlace) {
this.endPlace = endPlace;
}
public LocalDateTime getStartTime() {
return startTime;
}
public void setStartTime(LocalDateTime startTime) {
this.startTime = startTime;
}
public LocalDateTime getEndTime() {
return endTime;
}
public void setEndTime(LocalDateTime endTime) {
this.endTime = endTime;
}
public float getMobilityScore() {
return mobilityScore;
}
public void setMobilityScore(float mobilityScore) {
this.mobilityScore = mobilityScore;
}
public Set<NewTripSegmentDTO> getTripSegments() {
return tripSegments;
}
public void setTripSegments(Set<NewTripSegmentDTO> tripSegments) {
this.tripSegments = tripSegments;
}
}
@@ -1,18 +1,21 @@
package SuMoC.backend.trip.dtos;
import SuMoC.backend.trip.Modality;
import lombok.Builder;
import java.time.LocalDateTime;
/**
* DTO representing a trip segment submitted from the App which is not yet persisted in the database.
*/
@Builder
public class NewTripSegmentDTO {
private Modality modality;
private LocalDateTime startTime;
private float distanceMeters;
public NewTripSegmentDTO() { }
public NewTripSegmentDTO() {
}
public NewTripSegmentDTO(Modality modality, LocalDateTime startTime, float distanceMeters) {
this.modality = modality;
@@ -1,104 +1,32 @@
package SuMoC.backend.trip.dtos;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.time.LocalDateTime;
import java.util.List;
@Schema(description = "Represents a trip uploaded to the backend by a user that is already stored in the DB.")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class TripDTO {
private long tripId;
private int userId;
private String startPlace;
private double startLatitude;
private double startLongitude;
private String endPlace;
private double endLatitude;
private double endLongitude;
private LocalDateTime startTime;
private LocalDateTime endTime;
private float mobilityScore;
private double mobilityScore;
private double co2Emissions;
private List<TripSegmentDTO> tripSegments;
private boolean invalidated;
public TripDTO() {
}
public TripDTO(int userId, String startPlace, String endPlace, LocalDateTime startTime, LocalDateTime endTime, float mobilityScore, List<TripSegmentDTO> tripSegmentDTOS) {
this.userId = userId;
this.startPlace = startPlace;
this.endPlace = endPlace;
this.startTime = startTime;
this.endTime = endTime;
this.mobilityScore = mobilityScore;
this.tripSegments = tripSegmentDTOS;
}
public long getTripId() {
return tripId;
}
public void setTripId(long tripId) {
this.tripId = tripId;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getStartPlace() {
return startPlace;
}
public void setStartPlace(String startPlace) {
this.startPlace = startPlace;
}
public String getEndPlace() {
return endPlace;
}
public void setEndPlace(String endPlace) {
this.endPlace = endPlace;
}
public LocalDateTime getStartTime() {
return startTime;
}
public void setStartTime(LocalDateTime startTime) {
this.startTime = startTime;
}
public LocalDateTime getEndTime() {
return endTime;
}
public void setEndTime(LocalDateTime endTime) {
this.endTime = endTime;
}
public float getMobilityScore() {
return mobilityScore;
}
public void setMobilityScore(float mobilityScore) {
this.mobilityScore = mobilityScore;
}
public List<TripSegmentDTO> getTripSegments() {
return tripSegments;
}
public void setTripSegments(List<TripSegmentDTO> tripSegments) {
this.tripSegments = tripSegments;
}
public boolean isInvalidated() {
return invalidated;
}
public void setInvalidated(boolean invalidated) {
this.invalidated = invalidated;
}
}
@@ -1,12 +1,16 @@
package SuMoC.backend.trip.dtos;
import SuMoC.backend.trip.Modality;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDateTime;
/**
* DTO representing a trip segment already persisted in the database.
*/
@Setter
@Getter
public class TripSegmentDTO {
private long tripSegmentId;
private long tripId;
@@ -24,43 +28,4 @@ public class TripSegmentDTO {
this.distanceMeters = distanceMeters;
}
public long getTripSegmentId() {
return tripSegmentId;
}
public void setTripSegmentId(long tripSegmentId) {
this.tripSegmentId = tripSegmentId;
}
public long getTripId() {
return tripId;
}
public void setTripId(long tripId) {
this.tripId = tripId;
}
public Modality getModality() {
return modality;
}
public void setModality(Modality modality) {
this.modality = modality;
}
public LocalDateTime getStartTime() {
return startTime;
}
public void setStartTime(LocalDateTime startTime) {
this.startTime = startTime;
}
public float getDistanceMeters() {
return distanceMeters;
}
public void setDistanceMeters(float distanceMeters) {
this.distanceMeters = distanceMeters;
}
}
@@ -3,6 +3,10 @@ package SuMoC.backend.trip.models;
import SuMoC.backend.user.models.User;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.time.LocalDateTime;
import java.util.HashSet;
@@ -10,6 +14,10 @@ import java.util.Set;
@Entity
@Table(name = "trips")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Trip {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@@ -22,9 +30,21 @@ public class Trip {
@Column(nullable = false)
private String startPlace;
@Column(nullable = false)
private double startLatitude;
@Column(nullable = false)
private double startLongitude;
@Column(nullable = false)
private String endPlace;
@Column(nullable = false)
private double endLatitude;
@Column(nullable = false)
private double endLongitude;
@Column(nullable = false)
private LocalDateTime startTime;
@@ -32,10 +52,13 @@ public class Trip {
private LocalDateTime endTime;
/**
* Mobilityscore for the trip. TODO determine if this needs an own data type
* Mobilityscore for the trip.
*/
@Column(nullable = false)
private float mobilityScore;
private double mobilityScore;
@Column(nullable = false)
private double co2Emissions;
@Column(nullable = true)
private float cost;
@@ -45,100 +68,4 @@ public class Trip {
@OneToMany(mappedBy = "trip", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<TripSegment> tripSegments = new HashSet<>();
public Trip() {
}
public Trip(Long id, User user, String startPlace, String endPlace, LocalDateTime startTime, LocalDateTime endTime, float mobilityScore, float cost, Set<TripSegment> tripSegments) {
this.id = id;
this.user = user;
this.startPlace = startPlace;
this.endPlace = endPlace;
this.startTime = startTime;
this.endTime = endTime;
this.mobilityScore = mobilityScore;
this.cost = cost;
this.tripSegments = tripSegments;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getStartPlace() {
return startPlace;
}
public void setStartPlace(String startPlace) {
this.startPlace = startPlace;
}
public String getEndPlace() {
return endPlace;
}
public void setEndPlace(String endPlace) {
this.endPlace = endPlace;
}
public LocalDateTime getStartTime() {
return startTime;
}
public void setStartTime(LocalDateTime startTime) {
this.startTime = startTime;
}
public LocalDateTime getEndTime() {
return endTime;
}
public void setEndTime(LocalDateTime endTime) {
this.endTime = endTime;
}
public float getMobilityScore() {
return mobilityScore;
}
public void setMobilityScore(float mobilityScore) {
this.mobilityScore = mobilityScore;
}
public float getCost() {
return cost;
}
public void setCost(float cost) {
this.cost = cost;
}
public Set<TripSegment> getTripSegments() {
return tripSegments;
}
public void setTripSegments(Set<TripSegment> segments) {
this.tripSegments = segments;
}
public boolean isInvalidated() {
return invalidated;
}
public void setInvalidated(boolean invalidated) {
this.invalidated = invalidated;
}
}
@@ -3,9 +3,13 @@ package SuMoC.backend.trip.models;
import SuMoC.backend.trip.Modality;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDateTime;
@Setter
@Getter
@Entity
@Table(name = "trip_segments")
public class TripSegment {
@@ -41,43 +45,4 @@ public class TripSegment {
this.distanceMeters = distanceMeters;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Trip getTrip() {
return trip;
}
public void setTrip(Trip trip) {
this.trip = trip;
}
public Modality getModality() {
return modality;
}
public void setModality(Modality modality) {
this.modality = modality;
}
public LocalDateTime getStartTime() {
return startTime;
}
public void setStartTime(LocalDateTime startTime) {
this.startTime = startTime;
}
public Long getDistanceMeters() {
return distanceMeters;
}
public void setDistanceMeters(Long distance) {
this.distanceMeters = distance;
}
}
@@ -11,3 +11,4 @@ springdoc.api-docs.path=/v3/api-docs
springdoc.swagger-ui.path=/swagger-ui.html
carta.base-url=https://mobydex.locoslab.com/carta
nominatim.base-url=http://localhost:6666
spring.profiles.active=dev