diff --git a/pom.xml b/pom.xml index 1f54585..94dd5c8 100644 --- a/pom.xml +++ b/pom.xml @@ -154,15 +154,20 @@ 21 21 + + org.projectlombok + lombok + 1.18.32 + org.mapstruct mapstruct-processor - 1.5.5.Final + 1.6.3 org.projectlombok - lombok - 1.18.30 + lombok-mapstruct-binding + 0.2.0 diff --git a/src/main/java/SuMoC/backend/geocoding/AddressDTO.java b/src/main/java/SuMoC/backend/geocoding/AddressDTO.java new file mode 100644 index 0000000..88ca568 --- /dev/null +++ b/src/main/java/SuMoC/backend/geocoding/AddressDTO.java @@ -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; + } + +} diff --git a/src/main/java/SuMoC/backend/geocoding/GeoCodingService.java b/src/main/java/SuMoC/backend/geocoding/GeoCodingService.java new file mode 100644 index 0000000..b2eaa2b --- /dev/null +++ b/src/main/java/SuMoC/backend/geocoding/GeoCodingService.java @@ -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 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") + ); + } +} diff --git a/src/main/java/SuMoC/backend/geocoding/GeocodingController.java b/src/main/java/SuMoC/backend/geocoding/GeocodingController.java index 446a0bc..3e52ca8 100644 --- a/src/main/java/SuMoC/backend/geocoding/GeocodingController.java +++ b/src/main/java/SuMoC/backend/geocoding/GeocodingController.java @@ -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 reverse(@RequestParam double lat, @RequestParam double lon) { - return nominatimClient.reverse(lat, lon); + @Operation(description = "Returns the address at the given lat / lon.") + public Mono reverse(@RequestParam double lat, @RequestParam double lon) { + return geoCodingService.getAddress(lat, lon); } } diff --git a/src/main/java/SuMoC/backend/meteo/README.MD b/src/main/java/SuMoC/backend/meteo/README.MD new file mode 100644 index 0000000..51b8253 --- /dev/null +++ b/src/main/java/SuMoC/backend/meteo/README.MD @@ -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) \ No newline at end of file diff --git a/src/main/java/SuMoC/backend/routing/RoutingController.java b/src/main/java/SuMoC/backend/routing/RoutingController.java index 16fa5c6..da5b13f 100644 --- a/src/main/java/SuMoC/backend/routing/RoutingController.java +++ b/src/main/java/SuMoC/backend/routing/RoutingController.java @@ -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> 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 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); } } diff --git a/src/main/java/SuMoC/backend/routing/RoutingService.java b/src/main/java/SuMoC/backend/routing/RoutingService.java index 67aef05..86448b6 100644 --- a/src/main/java/SuMoC/backend/routing/RoutingService.java +++ b/src/main/java/SuMoC/backend/routing/RoutingService.java @@ -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 getPossibleDirectionsFromCarta(RoutingAlternativeRequestDTO requestDTO) { Map> 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 getAlternativeRoute(RoutingAlternativeRequestDTO requestDTO) { - HashMap directionHashMap = getPossibleDirectionsFromCarta(requestDTO); + assert requestDTO.getRoutingPreferencesDTO() != null; + HashMap directionMap = getPossibleDirectionsFromCarta(requestDTO); + ArrayList 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 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 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(); + return suggestedAlternatives; } } diff --git a/src/main/java/SuMoC/backend/routing/config/RoutingConfig.java b/src/main/java/SuMoC/backend/routing/config/RoutingConfig.java new file mode 100644 index 0000000..99baa6c --- /dev/null +++ b/src/main/java/SuMoC/backend/routing/config/RoutingConfig.java @@ -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 { +} diff --git a/src/main/java/SuMoC/backend/routing/config/RoutingProperties.java b/src/main/java/SuMoC/backend/routing/config/RoutingProperties.java new file mode 100644 index 0000000..c9f2dd4 --- /dev/null +++ b/src/main/java/SuMoC/backend/routing/config/RoutingProperties.java @@ -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; +} diff --git a/src/main/java/SuMoC/backend/routing/dtos/RouteDTO.java b/src/main/java/SuMoC/backend/routing/dtos/RouteDTO.java index 3da416f..c5d9eb9 100644 --- a/src/main/java/SuMoC/backend/routing/dtos/RouteDTO.java +++ b/src/main/java/SuMoC/backend/routing/dtos/RouteDTO.java @@ -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 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 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(), @@ -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 )); diff --git a/src/main/java/SuMoC/backend/routing/dtos/RoutingAlternativeRequestDTO.java b/src/main/java/SuMoC/backend/routing/dtos/RoutingAlternativeRequestDTO.java index de0552f..37a0ff3 100644 --- a/src/main/java/SuMoC/backend/routing/dtos/RoutingAlternativeRequestDTO.java +++ b/src/main/java/SuMoC/backend/routing/dtos/RoutingAlternativeRequestDTO.java @@ -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 diff --git a/src/main/java/SuMoC/backend/routing/dtos/RoutingPreferencesDTO.java b/src/main/java/SuMoC/backend/routing/dtos/RoutingPreferencesDTO.java index 92c2777..5d17f4a 100644 --- a/src/main/java/SuMoC/backend/routing/dtos/RoutingPreferencesDTO.java +++ b/src/main/java/SuMoC/backend/routing/dtos/RoutingPreferencesDTO.java @@ -15,6 +15,6 @@ public class RoutingPreferencesDTO { private boolean preferPhysicalActivity = false; private boolean considerWeatherConditions = true; private List 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) ); } diff --git a/src/main/java/SuMoC/backend/routing/dtos/StepDTO.java b/src/main/java/SuMoC/backend/routing/dtos/StepDTO.java index 6dad149..583ef28 100644 --- a/src/main/java/SuMoC/backend/routing/dtos/StepDTO.java +++ b/src/main/java/SuMoC/backend/routing/dtos/StepDTO.java @@ -15,5 +15,5 @@ import lombok.Setter; public class StepDTO { private Modality modality; private String lineNumber; - private float distanceMeters; + private double distanceMeters; } diff --git a/src/main/java/SuMoC/backend/routing/exceptions/NoCarRouteFoundException.java b/src/main/java/SuMoC/backend/routing/exceptions/NoCarRouteFoundException.java new file mode 100644 index 0000000..af9e681 --- /dev/null +++ b/src/main/java/SuMoC/backend/routing/exceptions/NoCarRouteFoundException.java @@ -0,0 +1,7 @@ +package SuMoC.backend.routing.exceptions; + +public class NoCarRouteFoundException extends RuntimeException { + public NoCarRouteFoundException(String message) { + super(message); + } +} diff --git a/src/main/java/SuMoC/backend/routing/exceptions/NoCarbonEmissionFoundException.java b/src/main/java/SuMoC/backend/routing/exceptions/NoCarbonEmissionFoundException.java new file mode 100644 index 0000000..b11c331 --- /dev/null +++ b/src/main/java/SuMoC/backend/routing/exceptions/NoCarbonEmissionFoundException.java @@ -0,0 +1,7 @@ +package SuMoC.backend.routing.exceptions; + +public class NoCarbonEmissionFoundException extends RuntimeException { + public NoCarbonEmissionFoundException(String message) { + super(message); + } +} diff --git a/src/main/java/SuMoC/backend/security/dtos/UserRegistrationDTO.java b/src/main/java/SuMoC/backend/security/dtos/UserRegistrationDTO.java index 8c08968..2dbad57 100644 --- a/src/main/java/SuMoC/backend/security/dtos/UserRegistrationDTO.java +++ b/src/main/java/SuMoC/backend/security/dtos/UserRegistrationDTO.java @@ -1,7 +1,9 @@ package SuMoC.backend.security.dtos; import jakarta.validation.constraints.NotNull; +import lombok.Builder; +@Builder public class UserRegistrationDTO { @NotNull diff --git a/src/main/java/SuMoC/backend/seed/trip/DevTripSeeder.java b/src/main/java/SuMoC/backend/seed/trip/DevTripSeeder.java new file mode 100644 index 0000000..659664c --- /dev/null +++ b/src/main/java/SuMoC/backend/seed/trip/DevTripSeeder.java @@ -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); + } + }); + } +} diff --git a/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java b/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java new file mode 100644 index 0000000..54b0e6e --- /dev/null +++ b/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java @@ -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); + } +} diff --git a/src/main/java/SuMoC/backend/trip/Modality.java b/src/main/java/SuMoC/backend/trip/Modality.java index 7f2301b..915956f 100644 --- a/src/main/java/SuMoC/backend/trip/Modality.java +++ b/src/main/java/SuMoC/backend/trip/Modality.java @@ -2,11 +2,13 @@ package SuMoC.backend.trip; public enum Modality { IDLE, - WALK, - BIKE, + WALKING, + BICYCLE, ESCOOTER, BUS, TRAM, TRAIN, - CAR + CAR, + MOTORCYCLE, + TAXI } diff --git a/src/main/java/SuMoC/backend/trip/TripFactory.java b/src/main/java/SuMoC/backend/trip/TripFactory.java new file mode 100644 index 0000000..895389f --- /dev/null +++ b/src/main/java/SuMoC/backend/trip/TripFactory.java @@ -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 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 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(); + } +} diff --git a/src/main/java/SuMoC/backend/trip/dtos/NewTripDTO.java b/src/main/java/SuMoC/backend/trip/dtos/NewTripDTO.java index 7a9dfac..6013f36 100644 --- a/src/main/java/SuMoC/backend/trip/dtos/NewTripDTO.java +++ b/src/main/java/SuMoC/backend/trip/dtos/NewTripDTO.java @@ -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 tripSegments; - - public NewTripDTO() {} - - public NewTripDTO (String startPlace, String endPlace, LocalDateTime startTime, LocalDateTime endTime, float mobilityScore, Set 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 getTripSegments() { - return tripSegments; - } - - public void setTripSegments(Set tripSegments) { - this.tripSegments = tripSegments; - } } diff --git a/src/main/java/SuMoC/backend/trip/dtos/NewTripSegmentDTO.java b/src/main/java/SuMoC/backend/trip/dtos/NewTripSegmentDTO.java index ae11ae5..4e1ab8f 100644 --- a/src/main/java/SuMoC/backend/trip/dtos/NewTripSegmentDTO.java +++ b/src/main/java/SuMoC/backend/trip/dtos/NewTripSegmentDTO.java @@ -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; diff --git a/src/main/java/SuMoC/backend/trip/dtos/TripDTO.java b/src/main/java/SuMoC/backend/trip/dtos/TripDTO.java index 71589e1..b48cd3b 100644 --- a/src/main/java/SuMoC/backend/trip/dtos/TripDTO.java +++ b/src/main/java/SuMoC/backend/trip/dtos/TripDTO.java @@ -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 tripSegments; private boolean invalidated; - - public TripDTO() { - } - - public TripDTO(int userId, String startPlace, String endPlace, LocalDateTime startTime, LocalDateTime endTime, float mobilityScore, List 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 getTripSegments() { - return tripSegments; - } - - public void setTripSegments(List tripSegments) { - this.tripSegments = tripSegments; - } - - public boolean isInvalidated() { - return invalidated; - } - - public void setInvalidated(boolean invalidated) { - this.invalidated = invalidated; - } } diff --git a/src/main/java/SuMoC/backend/trip/dtos/TripSegmentDTO.java b/src/main/java/SuMoC/backend/trip/dtos/TripSegmentDTO.java index 182f119..e13aa76 100644 --- a/src/main/java/SuMoC/backend/trip/dtos/TripSegmentDTO.java +++ b/src/main/java/SuMoC/backend/trip/dtos/TripSegmentDTO.java @@ -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; - } } diff --git a/src/main/java/SuMoC/backend/trip/models/Trip.java b/src/main/java/SuMoC/backend/trip/models/Trip.java index 28c61d1..abc13ce 100644 --- a/src/main/java/SuMoC/backend/trip/models/Trip.java +++ b/src/main/java/SuMoC/backend/trip/models/Trip.java @@ -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 tripSegments = new HashSet<>(); - - - public Trip() { - } - - public Trip(Long id, User user, String startPlace, String endPlace, LocalDateTime startTime, LocalDateTime endTime, float mobilityScore, float cost, Set 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 getTripSegments() { - return tripSegments; - } - - public void setTripSegments(Set segments) { - this.tripSegments = segments; - } - - public boolean isInvalidated() { - return invalidated; - } - - public void setInvalidated(boolean invalidated) { - this.invalidated = invalidated; - } } diff --git a/src/main/java/SuMoC/backend/trip/models/TripSegment.java b/src/main/java/SuMoC/backend/trip/models/TripSegment.java index a90bc35..fb2b77f 100644 --- a/src/main/java/SuMoC/backend/trip/models/TripSegment.java +++ b/src/main/java/SuMoC/backend/trip/models/TripSegment.java @@ -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; - } } \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 945d525..58ec430 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -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 \ No newline at end of file