From a401b9a6c16fe7594969b64f656c831c71ccfba8 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Mon, 9 Feb 2026 13:27:13 +0100 Subject: [PATCH 1/9] increase tolerated additinoal travel time for testing phase of app --- .../SuMoC/backend/routing/config/AdHocRoutingProperties.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/SuMoC/backend/routing/config/AdHocRoutingProperties.java b/src/main/java/SuMoC/backend/routing/config/AdHocRoutingProperties.java index d922668..d0289ca 100644 --- a/src/main/java/SuMoC/backend/routing/config/AdHocRoutingProperties.java +++ b/src/main/java/SuMoC/backend/routing/config/AdHocRoutingProperties.java @@ -16,8 +16,8 @@ public class AdHocRoutingProperties extends RoutingProperties { public AdHocRoutingProperties() { super(); - setAcceptableAdditionalMultiplierRegular(1.30); - setAcceptableAdditionalMultiplierPrefersPhysical(1.6); + setAcceptableAdditionalMultiplierRegular(2.0); + setAcceptableAdditionalMultiplierPrefersPhysical(2.0); setMinimumAcceptedAdditionalSecondsRegular(5 * 60); setMinimumAcceptedAdditionalSecondsPrefersPhysicalActivity(5 * 60); } From f7d7f6bc53a3e7bd19ea8915b8d4a7b5a675b0b0 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Mon, 9 Feb 2026 13:56:59 +0100 Subject: [PATCH 2/9] regular trip calculation: batch db writes for improved performance --- .../carrousel/service/CarrouselService.java | 10 +++-- .../interfaces/NotifieableWithTime.java | 9 ++++ .../NotificationSchedulerService.java | 28 ++++++++++++ .../backend/seed/user/DevUserSeeder.java | 33 ++++++++++++++ .../suggestion/dtos/RouteDTOtoBeNotified.java | 44 +++++++++++++++++++ .../RegularTripSuggestionService.java | 29 +++++++----- 6 files changed, 139 insertions(+), 14 deletions(-) create mode 100644 src/main/java/SuMoC/backend/notification/interfaces/NotifieableWithTime.java create mode 100644 src/main/java/SuMoC/backend/suggestion/dtos/RouteDTOtoBeNotified.java diff --git a/src/main/java/SuMoC/backend/carrousel/service/CarrouselService.java b/src/main/java/SuMoC/backend/carrousel/service/CarrouselService.java index 4369faf..aef48ca 100644 --- a/src/main/java/SuMoC/backend/carrousel/service/CarrouselService.java +++ b/src/main/java/SuMoC/backend/carrousel/service/CarrouselService.java @@ -21,6 +21,7 @@ import reactor.core.publisher.Mono; import java.time.Duration; import java.time.Instant; +import java.util.ArrayList; import java.util.List; @Service @@ -49,7 +50,9 @@ public class CarrouselService { } } - public void addRegularTripCandidates(Long userId, DetectedRegularTripDTO detectedRegularTrip, List suggestedAlternatives) { + public List getRegularTripCandidates(Long userId, DetectedRegularTripDTO detectedRegularTrip, List suggestedAlternatives) { + List candidates = new ArrayList<>(); + for (var alternative : suggestedAlternatives) { CarrouselCandidate candidate = CarrouselCandidate.builder() .userId(userId) @@ -58,9 +61,10 @@ public class CarrouselService { .suggestedAt(Instant.now()) .candidateType(CarrouselCandidateType.REGULAR_TRIP_ALTERNATIVE) .build(); - - carrouselCandidateRepository.save(candidate); + candidates.add(candidate); } + + return candidates; } public AlternativeCarrouselDTO getCarrouselForUser(Long userId) { diff --git a/src/main/java/SuMoC/backend/notification/interfaces/NotifieableWithTime.java b/src/main/java/SuMoC/backend/notification/interfaces/NotifieableWithTime.java new file mode 100644 index 0000000..3e266c2 --- /dev/null +++ b/src/main/java/SuMoC/backend/notification/interfaces/NotifieableWithTime.java @@ -0,0 +1,9 @@ +package SuMoC.backend.notification.interfaces; + +import java.time.LocalTime; + +public interface NotifieableWithTime { + Long getUserId(); + + LocalTime getEarliestTimeOfDayToSend(); +} diff --git a/src/main/java/SuMoC/backend/notification/services/NotificationSchedulerService.java b/src/main/java/SuMoC/backend/notification/services/NotificationSchedulerService.java index 7642a94..daa91e4 100644 --- a/src/main/java/SuMoC/backend/notification/services/NotificationSchedulerService.java +++ b/src/main/java/SuMoC/backend/notification/services/NotificationSchedulerService.java @@ -3,6 +3,7 @@ package SuMoC.backend.notification.services; import SuMoC.backend.notification.enums.NotificationStatus; import SuMoC.backend.notification.enums.NotificationType; import SuMoC.backend.notification.interfaces.Notifieable; +import SuMoC.backend.notification.interfaces.NotifieableWithTime; import SuMoC.backend.notification.models.Notification; import SuMoC.backend.notification.repositories.NotificationRepository; import SuMoC.backend.user.models.User; @@ -65,6 +66,33 @@ public class NotificationSchedulerService { notificationRepository.saveAll(notifications); } + public void scheduleAll(List dataBodies, + NotificationType notificationType + ) { + List notifications = dataBodies.stream().map(dataBody -> { + String dataBodyJson; + try { + dataBodyJson = objectMapper.writeValueAsString(dataBody); + } catch (Exception e) { + throw new RuntimeException("Failed to serialize notification data body", e); + } + + User userProxy = entityManager.getReference(User.class, dataBody.getUserId()); + + return Notification.builder() + .user(userProxy) + .type(notificationType) + .data(dataBodyJson) + .earliestTimeOfDayToSend(dataBody.getEarliestTimeOfDayToSend()) + .status(NotificationStatus.PENDING) + .createdAt(Instant.now()) + .failedSendAttempts(0) + .build(); + }).toList(); + + notificationRepository.saveAll(notifications); + } + /** * Schedules a notification to be sent to the specified user. * Data body needs to be serializable to JSON. diff --git a/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java b/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java index e50ac89..4017208 100644 --- a/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java +++ b/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java @@ -36,6 +36,36 @@ public class DevUserSeeder implements CommandLineRunner { @Override public void run(String... args) throws Exception { + seedPgMembers(); + seedDefaultTestUsers(); + //seedNtestUsers(1000); + } + + /** + * Useful for stress testing with a larger number of users. Seeds the specified number of users dummy users. + * + * @param numberOfUsers + */ + private void seedNtestUsers(int numberOfUsers) { + for (int i = 1; i <= numberOfUsers; i++) { + UserRegistrationDTO userDto = UserRegistrationDTO.builder() + .email("testuser" + i + "@email.com") + .publicName("Test User " + i) + .privateName("Test User " + i) + .password("password" + i) + .build(); + authenticationService.registerUser(userDto); + User user = userRepository.findByEmail("testuser" + i + "@email.com").orElseThrow(); + notificationTokenService.registerDeviceToken( + user, + NotificationProvider.FIREBASE, + devProperties.getFcmKey() + ); + } + + } + + private void seedDefaultTestUsers() { UserRegistrationDTO user1dto = UserRegistrationDTO.builder() .email("user1@email.com") .publicName("Nutzer 1 Public") @@ -62,6 +92,9 @@ public class DevUserSeeder implements CommandLineRunner { NotificationProvider.FIREBASE, devProperties.getFcmKey() ); + } + + private void seedPgMembers() { UserRegistrationDTO user3dto = UserRegistrationDTO.builder() .email("david@test.com") .publicName("David N. Public") diff --git a/src/main/java/SuMoC/backend/suggestion/dtos/RouteDTOtoBeNotified.java b/src/main/java/SuMoC/backend/suggestion/dtos/RouteDTOtoBeNotified.java new file mode 100644 index 0000000..2503e3a --- /dev/null +++ b/src/main/java/SuMoC/backend/suggestion/dtos/RouteDTOtoBeNotified.java @@ -0,0 +1,44 @@ +package SuMoC.backend.suggestion.dtos; + +import SuMoC.backend.notification.interfaces.NotifieableWithTime; +import SuMoC.backend.routing.dtos.RouteDTO; +import lombok.Getter; + +import java.time.LocalTime; + +/** + * This DTO extends RouteDTO and implements Notifieable to be used as the data body for notifications about route suggestions. + * This allows us to use the saveAll method in NotificationSchedulerService for better performance when scheduling multiple notifications at once. + */ +public class RouteDTOtoBeNotified extends RouteDTO implements NotifieableWithTime { + private Long userId; + @Getter + private LocalTime earliestTimeOfDayToSend; + + public RouteDTOtoBeNotified(RouteDTO routeDTO, Long userId, LocalTime earliestTimeOfDayToSend) { + super( + routeDTO.getStartAddress(), + routeDTO.getFirstStopName(), + routeDTO.getStartLat(), + routeDTO.getStartLon(), + routeDTO.getEndAddress(), + routeDTO.getLastStopName(), + routeDTO.getEndLat(), + routeDTO.getEndLon(), + routeDTO.getStartDateTime(), + routeDTO.getEndDateTime(), + routeDTO.getSteps(), + routeDTO.getCo2Savings(), + routeDTO.getTimeDifferenceSeconds(), + routeDTO.getCo2Emissions() + ); + this.userId = userId; + this.earliestTimeOfDayToSend = earliestTimeOfDayToSend; + } + + @Override + public Long getUserId() { + return this.userId; + } + +} diff --git a/src/main/java/SuMoC/backend/suggestion/services/RegularTripSuggestionService.java b/src/main/java/SuMoC/backend/suggestion/services/RegularTripSuggestionService.java index b462600..c9f6f78 100644 --- a/src/main/java/SuMoC/backend/suggestion/services/RegularTripSuggestionService.java +++ b/src/main/java/SuMoC/backend/suggestion/services/RegularTripSuggestionService.java @@ -1,8 +1,11 @@ package SuMoC.backend.suggestion.services; +import SuMoC.backend.carrousel.models.CarrouselCandidate; +import SuMoC.backend.carrousel.repository.CarrouselCandidateRepository; import SuMoC.backend.carrousel.service.CarrouselService; import SuMoC.backend.h3.H3Service; import SuMoC.backend.notification.enums.NotificationType; +import SuMoC.backend.notification.interfaces.NotifieableWithTime; import SuMoC.backend.notification.services.NotificationSchedulerService; import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO; import SuMoC.backend.regulartrip.services.RegularTripDetectionService; @@ -11,14 +14,13 @@ import SuMoC.backend.routing.dtos.RoutingPreferencesDTO; import SuMoC.backend.routing.services.AlternativeRoutingService; import SuMoC.backend.routing.services.RoutingPreferencesService; import SuMoC.backend.suggestion.config.RegularTripSuggestionProperties; +import SuMoC.backend.suggestion.dtos.RouteDTOtoBeNotified; import com.uber.h3core.util.LatLng; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; -import java.time.DayOfWeek; -import java.time.Instant; -import java.time.LocalDateTime; -import java.time.ZoneId; +import java.time.*; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -40,6 +42,8 @@ public class RegularTripSuggestionService { private final CarrouselService carrouselService; + private final CarrouselCandidateRepository carrouselCandidateRepository; + public void detectAndNotifyRegularTripsForTodaysDayOfWeek() { // detect DayOfWeek dayOfWeek = LocalDateTime.now().getDayOfWeek(); @@ -50,6 +54,10 @@ public class RegularTripSuggestionService { } public void checkAlternativesAndNotify(HashMap> detectedRegularTripsByUser) { + // We first gather all candidates to persist and then save them in batch at the end for better performance + List candidatesToPersist = new ArrayList<>(); + List alternativesToNotify = new ArrayList<>(); + for (Long userId : detectedRegularTripsByUser.keySet()) { var detectedRegularTrips = detectedRegularTripsByUser.get(userId); RoutingPreferencesDTO preferencesDTO = routingPreferencesService.getUserRoutingPreferences(userId); @@ -63,17 +71,16 @@ public class RegularTripSuggestionService { // if present, schedule notification if (bestAlternative != null) { // save the alternative in the carrousel candidates so that it can be shown in the carrousel as well - carrouselService.addRegularTripCandidates(userId, detectedRegularTrip, List.of(bestAlternative)); + candidatesToPersist.addAll(carrouselService.getRegularTripCandidates(userId, detectedRegularTrip, List.of(bestAlternative))); - notificationSchedulerService.schedule( - userId, - bestAlternative, - NotificationType.REGULAR_TRIP_ALTERNATIVE, - detectedRegularTrip.getDepartureWindowStart().minusMinutes(properties.getNotifyBeforeMinutes()) - ); + LocalTime earliestTimeToSend = detectedRegularTrip.getDepartureWindowStart().minusMinutes(properties.getNotifyBeforeMinutes()); + alternativesToNotify.add(new RouteDTOtoBeNotified(bestAlternative, userId, earliestTimeToSend)); } } } + + carrouselCandidateRepository.saveAll(candidatesToPersist); + notificationSchedulerService.scheduleAll(alternativesToNotify, NotificationType.REGULAR_TRIP_ALTERNATIVE); } private RoutingAlternativeRequestDTO createAlternativeRequest(DetectedRegularTripDTO trip) { From b95355c10f3104590541fb0b6e83ae6ddf72181c Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Mon, 9 Feb 2026 14:30:32 +0100 Subject: [PATCH 3/9] parallelize regular trip detection for massively improved performance --- .../backend/config/AsyncConfiguration.java | 39 +++++++++ .../backend/seed/user/DevUserSeeder.java | 2 +- .../RegularTripSuggestionProperties.java | 7 ++ .../RegularTripSuggestionService.java | 82 ++++++++++++++----- src/main/resources/application.properties | 4 +- 5 files changed, 113 insertions(+), 21 deletions(-) create mode 100644 src/main/java/SuMoC/backend/config/AsyncConfiguration.java diff --git a/src/main/java/SuMoC/backend/config/AsyncConfiguration.java b/src/main/java/SuMoC/backend/config/AsyncConfiguration.java new file mode 100644 index 0000000..068de11 --- /dev/null +++ b/src/main/java/SuMoC/backend/config/AsyncConfiguration.java @@ -0,0 +1,39 @@ +package SuMoC.backend.config; + +import SuMoC.backend.suggestion.config.RegularTripSuggestionProperties; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +import java.util.concurrent.Executor; + +@Configuration +@EnableAsync +@RequiredArgsConstructor +public class AsyncConfiguration { + + private final RegularTripSuggestionProperties regularTripSuggestionProperties; + + /** + * Custom thread pool executor for parallel processing of regular trip suggestions. + * Configured with parallelism setting from application properties. + */ + @Bean(name = "regularTripSuggestionExecutor") + public Executor regularTripSuggestionExecutor() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + int parallelism = regularTripSuggestionProperties.getParallelism(); + + executor.setCorePoolSize(parallelism); + executor.setMaxPoolSize(parallelism); + executor.setQueueCapacity(500); // Queue capacity for pending tasks + executor.setThreadNamePrefix("regular-trip-"); + executor.setWaitForTasksToCompleteOnShutdown(true); + executor.setAwaitTerminationSeconds(60); + executor.initialize(); + + return executor; + } +} + diff --git a/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java b/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java index 4017208..bf1a0c8 100644 --- a/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java +++ b/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java @@ -38,7 +38,7 @@ public class DevUserSeeder implements CommandLineRunner { public void run(String... args) throws Exception { seedPgMembers(); seedDefaultTestUsers(); - //seedNtestUsers(1000); + //seedNtestUsers(10); } /** diff --git a/src/main/java/SuMoC/backend/suggestion/config/RegularTripSuggestionProperties.java b/src/main/java/SuMoC/backend/suggestion/config/RegularTripSuggestionProperties.java index 5aed4f2..4259b34 100644 --- a/src/main/java/SuMoC/backend/suggestion/config/RegularTripSuggestionProperties.java +++ b/src/main/java/SuMoC/backend/suggestion/config/RegularTripSuggestionProperties.java @@ -14,4 +14,11 @@ public class RegularTripSuggestionProperties { * We keep it relatively short since regular trips have a time window. */ private Integer notifyBeforeMinutes = 15; + + /** + * Number of parallel threads to use for processing users concurrently when checking + * for regular trip alternatives. Higher values increase throughput but consume more + * resources (database connections, API rate limits, memory). + */ + private Integer parallelism = 10; } diff --git a/src/main/java/SuMoC/backend/suggestion/services/RegularTripSuggestionService.java b/src/main/java/SuMoC/backend/suggestion/services/RegularTripSuggestionService.java index c9f6f78..6625f2b 100644 --- a/src/main/java/SuMoC/backend/suggestion/services/RegularTripSuggestionService.java +++ b/src/main/java/SuMoC/backend/suggestion/services/RegularTripSuggestionService.java @@ -17,17 +17,25 @@ import SuMoC.backend.suggestion.config.RegularTripSuggestionProperties; import SuMoC.backend.suggestion.dtos.RouteDTOtoBeNotified; import com.uber.h3core.util.LatLng; import lombok.RequiredArgsConstructor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import java.time.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.Executor; @Service @RequiredArgsConstructor public class RegularTripSuggestionService { + private static final Logger logger = LoggerFactory.getLogger(RegularTripSuggestionService.class); + private final AlternativeRoutingService alternativeRoutingService; private final RoutingPreferencesService routingPreferencesService; @@ -44,6 +52,9 @@ public class RegularTripSuggestionService { private final CarrouselCandidateRepository carrouselCandidateRepository; + @Qualifier("regularTripSuggestionExecutor") + private final Executor executor; + public void detectAndNotifyRegularTripsForTodaysDayOfWeek() { // detect DayOfWeek dayOfWeek = LocalDateTime.now().getDayOfWeek(); @@ -54,35 +65,68 @@ public class RegularTripSuggestionService { } public void checkAlternativesAndNotify(HashMap> detectedRegularTripsByUser) { - // We first gather all candidates to persist and then save them in batch at the end for better performance - List candidatesToPersist = new ArrayList<>(); - List alternativesToNotify = new ArrayList<>(); + logger.info("Processing {} users for regular trip alternatives in parallel", detectedRegularTripsByUser.size()); + + // Use thread-safe collections for parallel processing + ConcurrentLinkedQueue candidatesToPersist = new ConcurrentLinkedQueue<>(); + ConcurrentLinkedQueue alternativesToNotify = new ConcurrentLinkedQueue<>(); + + // Create a CompletableFuture for each user to process in parallel + List> futures = new ArrayList<>(); for (Long userId : detectedRegularTripsByUser.keySet()) { var detectedRegularTrips = detectedRegularTripsByUser.get(userId); - RoutingPreferencesDTO preferencesDTO = routingPreferencesService.getUserRoutingPreferences(userId); - // For each detected regular trip, determine alternatives and notify the user if applicable - for (var detectedRegularTrip : detectedRegularTrips) { - var alternativeRequest = createAlternativeRequest(detectedRegularTrip); - alternativeRequest.setRoutingPreferencesDTO(preferencesDTO); - - var bestAlternative = alternativeRoutingService.determineBestAlternativeRouteForRegularTrip(alternativeRequest); - // if present, schedule notification - if (bestAlternative != null) { - // save the alternative in the carrousel candidates so that it can be shown in the carrousel as well - candidatesToPersist.addAll(carrouselService.getRegularTripCandidates(userId, detectedRegularTrip, List.of(bestAlternative))); - - LocalTime earliestTimeToSend = detectedRegularTrip.getDepartureWindowStart().minusMinutes(properties.getNotifyBeforeMinutes()); - alternativesToNotify.add(new RouteDTOtoBeNotified(bestAlternative, userId, earliestTimeToSend)); + CompletableFuture future = CompletableFuture.runAsync(() -> { + try { + processUserTrips(userId, detectedRegularTrips, candidatesToPersist, alternativesToNotify); + } catch (Exception e) { + logger.error("Error processing regular trips for user {}: {}", userId, e.getMessage(), e); } - } + }, executor); + + futures.add(future); } + // Wait for all user processing tasks to complete + CompletableFuture allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); + allFutures.join(); + + logger.info("Parallel processing completed. Persisting {} carrousel candidates and scheduling {} notifications", + candidatesToPersist.size(), alternativesToNotify.size()); + + // Batch save all results carrouselCandidateRepository.saveAll(candidatesToPersist); - notificationSchedulerService.scheduleAll(alternativesToNotify, NotificationType.REGULAR_TRIP_ALTERNATIVE); + notificationSchedulerService.scheduleAll(new ArrayList<>(alternativesToNotify), NotificationType.REGULAR_TRIP_ALTERNATIVE); } + /** + * Process all detected regular trips for a single user. + * This method is designed to be called in parallel for multiple users. + */ + private void processUserTrips(Long userId, List detectedRegularTrips, + ConcurrentLinkedQueue candidatesToPersist, + ConcurrentLinkedQueue alternativesToNotify) { + RoutingPreferencesDTO preferencesDTO = routingPreferencesService.getUserRoutingPreferences(userId); + + // For each detected regular trip, determine alternatives and notify the user if applicable + for (var detectedRegularTrip : detectedRegularTrips) { + var alternativeRequest = createAlternativeRequest(detectedRegularTrip); + alternativeRequest.setRoutingPreferencesDTO(preferencesDTO); + + var bestAlternative = alternativeRoutingService.determineBestAlternativeRouteForRegularTrip(alternativeRequest); + // if present, schedule notification + if (bestAlternative != null) { + // save the alternative in the carrousel candidates so that it can be shown in the carrousel as well + candidatesToPersist.addAll(carrouselService.getRegularTripCandidates(userId, detectedRegularTrip, List.of(bestAlternative))); + + LocalTime earliestTimeToSend = detectedRegularTrip.getDepartureWindowStart().minusMinutes(properties.getNotifyBeforeMinutes()); + alternativesToNotify.add(new RouteDTOtoBeNotified(bestAlternative, userId, earliestTimeToSend)); + } + } + } + + private RoutingAlternativeRequestDTO createAlternativeRequest(DetectedRegularTripDTO trip) { LatLng origin = h3Service.cellToLatLng(trip.getStartH3Center()); LatLng destination = h3Service.cellToLatLng(trip.getEndH3Center()); diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index aa3002b..0870e95 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -16,6 +16,9 @@ sumoc.scheduling.run-notification-worker=*/15 * * * * * sumoc.scheduling.notify-weekly-mobility-stats=1 30 0 * * 1 sumoc.scheduling.clean-up-old-notifications=0 0 3 * * * sumoc.scheduling.notify-regular-route-alternatives=0 0 4 * * * +# Regular trip suggestion settings +sumoc.regulartripsuggestion.parallelism=5 +sumoc.regulartripsuggestion.notify-before-minutes=15 # Trend detection settings sumoc.trenddetection.positive-threshold=-25.0 sumoc.trenddetection.negative-threshold=-25.0 @@ -36,7 +39,6 @@ geocoding.carta.base-url=https://mobydex.locoslab.com/carta meteo.base-url=https://api.open-meteo.com/v1 # Dev debug settings sumoc.dev.fcm-key=dmydW4a_RjKCDjcBLZ9Kl8:APA91bFjBIjw8NcjeMIsNkfPuW9jhMlK3n_LHoG5UBW0E_76nTp1yV6jkdiBIvle7Txj_mLY3W9e9gy_op6YWyxJksqZrJFgapruCdBdg9ACYDJAANGTWJk - # RSA key paths (file paths, not directories) security.rsa.private-key-path=${RSA_PRIVATE_KEY_PATH:${user.home}/.sumoc/keys/jwt-private.pem} security.rsa.public-key-path=${RSA_PUBLIC_KEY_PATH:${user.home}/.sumoc/keys/jwt-public.pem} From 18e8d10f6b46c988699da7646ac7c8633ec1127e Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Tue, 10 Feb 2026 13:34:49 +0100 Subject: [PATCH 4/9] allow geocoding from non logged in users --- src/main/java/SuMoC/backend/security/SecurityConfiguration.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/SuMoC/backend/security/SecurityConfiguration.java b/src/main/java/SuMoC/backend/security/SecurityConfiguration.java index b1ee73c..3db8ee1 100644 --- a/src/main/java/SuMoC/backend/security/SecurityConfiguration.java +++ b/src/main/java/SuMoC/backend/security/SecurityConfiguration.java @@ -95,11 +95,11 @@ public class SecurityConfiguration { auth.requestMatchers("/auth/user/**").permitAll(); auth.requestMatchers("/routing/directions/**").permitAll(); auth.requestMatchers("/routing/alternative/**").permitAll(); + auth.requestMatchers("/geocoding/**").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"); auth.requestMatchers("/trip/**").hasAnyRole("USER", "ADMIN"); - auth.requestMatchers("/geocoding/**").hasAnyRole("USER", "ADMIN"); auth.requestMatchers("/routing/alternative/carrousel/**").hasAnyRole("USER", "ADMIN"); auth.requestMatchers("/routing/preferences/**").hasAnyRole("USER", "ADMIN"); From 1b549cc5fc5d91f8e68d131a986df8ec293d9426 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Tue, 10 Feb 2026 13:39:30 +0100 Subject: [PATCH 5/9] remove unnecessary geocoding for regular trip centers -> we already have address of alternative route -> saves on geocoding calls --- .../dto/RegularTripAlternativeContext.java | 10 +------- .../carrousel/service/CarrouselService.java | 25 +------------------ 2 files changed, 2 insertions(+), 33 deletions(-) diff --git a/src/main/java/SuMoC/backend/carrousel/dto/RegularTripAlternativeContext.java b/src/main/java/SuMoC/backend/carrousel/dto/RegularTripAlternativeContext.java index e53134b..ea5f0c3 100644 --- a/src/main/java/SuMoC/backend/carrousel/dto/RegularTripAlternativeContext.java +++ b/src/main/java/SuMoC/backend/carrousel/dto/RegularTripAlternativeContext.java @@ -1,26 +1,18 @@ package SuMoC.backend.carrousel.dto; import SuMoC.backend.carrousel.enums.CarrouselCandidateType; -import SuMoC.backend.geocoding.AddressDTO; import SuMoC.backend.regulartrip.dtos.MinimalDetectedRegularTripDTO; import SuMoC.backend.routing.dtos.RouteDTO; -import io.swagger.v3.oas.annotations.media.Schema; import lombok.Getter; @Getter public class RegularTripAlternativeContext extends RouteAlternativeContext { private final MinimalDetectedRegularTripDTO detectedRegularTrip; - @Schema(description = "The address of the departure h3 center cell. Note that this is not necessarily the actual departure location of the user, but suburb etc. should match.") - private final AddressDTO departureCenter; - @Schema(description = "The address of the arrival h3 center cell. Note that this is not necessarily the actual arrival location of the user, but suburb etc. should match.") - private final AddressDTO arrivalCenter; - public RegularTripAlternativeContext(RouteDTO alternative, MinimalDetectedRegularTripDTO detectedRegularTrip, AddressDTO departureCenter, AddressDTO arrivalCenter) { + public RegularTripAlternativeContext(RouteDTO alternative, MinimalDetectedRegularTripDTO detectedRegularTrip) { super(alternative, CarrouselCandidateType.REGULAR_TRIP_ALTERNATIVE); this.detectedRegularTrip = detectedRegularTrip; - this.departureCenter = departureCenter; - this.arrivalCenter = arrivalCenter; } } diff --git a/src/main/java/SuMoC/backend/carrousel/service/CarrouselService.java b/src/main/java/SuMoC/backend/carrousel/service/CarrouselService.java index aef48ca..da96dc4 100644 --- a/src/main/java/SuMoC/backend/carrousel/service/CarrouselService.java +++ b/src/main/java/SuMoC/backend/carrousel/service/CarrouselService.java @@ -8,16 +8,12 @@ import SuMoC.backend.carrousel.dto.RouteAlternativeContext; import SuMoC.backend.carrousel.enums.CarrouselCandidateType; import SuMoC.backend.carrousel.models.CarrouselCandidate; import SuMoC.backend.carrousel.repository.CarrouselCandidateRepository; -import SuMoC.backend.geocoding.AddressDTO; -import SuMoC.backend.geocoding.GeoCodingService; -import SuMoC.backend.h3.H3Service; import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO; import SuMoC.backend.regulartrip.dtos.MinimalDetectedRegularTripDTO; import SuMoC.backend.routing.dtos.RouteDTO; import SuMoC.backend.trip.models.Trip; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; -import reactor.core.publisher.Mono; import java.time.Duration; import java.time.Instant; @@ -32,10 +28,6 @@ public class CarrouselService { private final CarrouselProperties carrouselProperties; - private final H3Service h3Service; - - private final GeoCodingService geoCodingService; - public void addAdHocTripCandidates(Trip trip, List suggestedAlternatives) { for (var alternative : suggestedAlternatives) { CarrouselCandidate candidate = CarrouselCandidate.builder() @@ -107,24 +99,9 @@ public class CarrouselService { private RouteAlternativeContext fromRegularTripCandidate(CarrouselCandidate candidate) { var minRegularTrip = candidate.getDetectedRegularTrip(); - var startLatLong = h3Service.cellToLatLng(minRegularTrip.getStartH3Center()); - var endLatLong = h3Service.cellToLatLng(minRegularTrip.getEndH3Center()); - - // TODO we might want to remove the center addresses, we already have the start and end place names from the original trip - could save compute time and API calls here - // Fetch origin and destination addresses concurrently - var addressesMono = Mono.zip( - geoCodingService.getAddress(startLatLong.lat, startLatLong.lng), - geoCodingService.getAddress(endLatLong.lat, endLatLong.lng) - ); - var addressesTuple = addressesMono.block(); - AddressDTO startCenterAddress = addressesTuple.getT1(); - AddressDTO endCenterAddress = addressesTuple.getT2(); - return new RegularTripAlternativeContext( candidate.getSuggestedAlternative(), - minRegularTrip, - startCenterAddress, - endCenterAddress + minRegularTrip ); } } From 20d948bcdf738f089c75709e94ccd27dd7c90946 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Tue, 10 Feb 2026 14:09:26 +0100 Subject: [PATCH 6/9] add endpoint to invalidate notification token --- .../backend/notification/NotificationController.java | 8 ++++++++ src/main/java/SuMoC/backend/notification/README.MD | 7 +++++++ .../notification/services/NotificationSender.java | 12 +++++++++--- .../services/NotificationTokenService.java | 10 ++++++++++ src/main/java/SuMoC/backend/user/models/User.java | 8 +++++--- 5 files changed, 39 insertions(+), 6 deletions(-) diff --git a/src/main/java/SuMoC/backend/notification/NotificationController.java b/src/main/java/SuMoC/backend/notification/NotificationController.java index 8571ae5..c3d0e51 100644 --- a/src/main/java/SuMoC/backend/notification/NotificationController.java +++ b/src/main/java/SuMoC/backend/notification/NotificationController.java @@ -37,6 +37,14 @@ public class NotificationController { return ResponseEntity.ok().build(); } + @PutMapping("/unregister-device-token") + @Operation(description = "Unregisters the device token for push notifications for the authenticated user.") + public ResponseEntity unregisterDeviceToken() { + User user = getAuthenticatedUser(); + notificationTokenService.unregisterDeviceToken(user); + return ResponseEntity.ok().build(); + } + // Simple record for request body public record RegisterDeviceTokenRequest(String token, NotificationProvider provider) { } diff --git a/src/main/java/SuMoC/backend/notification/README.MD b/src/main/java/SuMoC/backend/notification/README.MD index 3f92a34..0603687 100644 --- a/src/main/java/SuMoC/backend/notification/README.MD +++ b/src/main/java/SuMoC/backend/notification/README.MD @@ -37,6 +37,13 @@ Each notification type includes a data payload. The main DTOs in the notificatio To receive push notifications, clients must register their device token. Token registration is handled in the `NotificationController`. The backend stores or updates the token for the authenticated user. +### Unregistering Device Token + +When a user logs out, the client should call the device token unregistration endpoint to remove the device token from +the backend. This ensures the user will no longer receive push notifications on that device after logout. + +- **Endpoint:** `PUT /notifications/unregister-device-token` + --- ## For Backend Developers diff --git a/src/main/java/SuMoC/backend/notification/services/NotificationSender.java b/src/main/java/SuMoC/backend/notification/services/NotificationSender.java index e4d2b58..69bd5bb 100644 --- a/src/main/java/SuMoC/backend/notification/services/NotificationSender.java +++ b/src/main/java/SuMoC/backend/notification/services/NotificationSender.java @@ -46,6 +46,8 @@ public class NotificationSender { if (token == null) { logger.warning("No notification token found notification id: " + notification.getId()); notification.incrementFailedSendAttempts(); + notification.setLastFailureReason("No notification token found for user"); + setFailedIfLimitExceeded(notification); notificationRepository.save(notification); return; } @@ -77,13 +79,17 @@ public class NotificationSender { public void onFailure(Throwable t) { notification.incrementFailedSendAttempts(); notification.setLastFailureReason(t.getMessage()); - if (notification.getFailedSendAttempts() >= notificationProperties.getMaxFailedSendAttempts()) { - notification.setStatus(NotificationStatus.FAILED); - } + setFailedIfLimitExceeded(notification); notificationRepository.save(notification); logger.severe("Failed to send notification with id:" + notification.getId() + " " + t.getMessage()); } }, MoreExecutors.directExecutor()); } + + private void setFailedIfLimitExceeded(Notification notification) { + if (notification.getFailedSendAttempts() >= notificationProperties.getMaxFailedSendAttempts()) { + notification.setStatus(NotificationStatus.FAILED); + } + } } diff --git a/src/main/java/SuMoC/backend/notification/services/NotificationTokenService.java b/src/main/java/SuMoC/backend/notification/services/NotificationTokenService.java index 978791a..81ecae8 100644 --- a/src/main/java/SuMoC/backend/notification/services/NotificationTokenService.java +++ b/src/main/java/SuMoC/backend/notification/services/NotificationTokenService.java @@ -4,6 +4,7 @@ import SuMoC.backend.notification.enums.NotificationProvider; import SuMoC.backend.notification.models.NotificationToken; import SuMoC.backend.notification.repositories.NotificationTokenRepository; import SuMoC.backend.user.models.User; +import jakarta.transaction.Transactional; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @@ -27,4 +28,13 @@ public class NotificationTokenService { notificationTokenRepository.save(newToken); } } + + @Transactional + public void unregisterDeviceToken(User user) { + var existingToken = notificationTokenRepository.findByUserId(user.getId()); + existingToken.ifPresent(token -> { + user.setNotificationToken(null); + notificationTokenRepository.delete(token); + }); + } } diff --git a/src/main/java/SuMoC/backend/user/models/User.java b/src/main/java/SuMoC/backend/user/models/User.java index fde40ba..02357e8 100644 --- a/src/main/java/SuMoC/backend/user/models/User.java +++ b/src/main/java/SuMoC/backend/user/models/User.java @@ -59,7 +59,7 @@ public class User { @Column(name = "role") private Set roles = new HashSet<>(); - @OneToOne + @OneToOne(cascade = CascadeType.REMOVE, orphanRemoval = true) @JoinColumn(name = "id", referencedColumnName = "user_id") private NotificationToken notificationToken; @@ -76,7 +76,8 @@ public class User { @OneToOne(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true) private ProfileImageEntity profileImage; - public User() {} + public User() { + } // public User(Long id, String publicName, String privateName, String email, String password, VisibilityPrivacy visibilityPrivacy, String friendCode, Set trips, Set friendships, Set roles) { // this.id = id; @@ -103,7 +104,8 @@ public class User { this.statsList = new StatsList(this); this.profileImage = new ProfileImageEntity(); - this.profileImage.setUser(this); } + this.profileImage.setUser(this); + } @PrePersist private void ensureFriendCode() { From c165fce833c7257215f796497a1614f66e36a81a Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Tue, 10 Feb 2026 14:56:19 +0100 Subject: [PATCH 7/9] seed leaderboards with dummy data --- .../backend/seed/user/DevUserSeeder.java | 77 +++++++++++++++++-- 1 file changed, 70 insertions(+), 7 deletions(-) diff --git a/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java b/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java index bf1a0c8..47ffe7a 100644 --- a/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java +++ b/src/main/java/SuMoC/backend/seed/user/DevUserSeeder.java @@ -1,6 +1,7 @@ package SuMoC.backend.seed.user; import SuMoC.backend.dev.DevProperties; +import SuMoC.backend.gamification.Timeframe; import SuMoC.backend.notification.enums.NotificationProvider; import SuMoC.backend.notification.services.NotificationTokenService; import SuMoC.backend.security.dtos.UserRegistrationDTO; @@ -13,6 +14,9 @@ import org.springframework.context.annotation.Profile; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; +import java.util.ArrayList; +import java.util.List; + @Component @Profile("dev") @Order(1) @@ -36,17 +40,30 @@ public class DevUserSeeder implements CommandLineRunner { @Override public void run(String... args) throws Exception { - seedPgMembers(); - seedDefaultTestUsers(); - //seedNtestUsers(10); + List pgMembers = seedPgMembers(); + List defaultTestUsers = seedDefaultTestUsers(); + + Long positionIndex = 1L; + for (var user : pgMembers) { + addDummyStats(user, positionIndex); + positionIndex++; + } + for (var user : defaultTestUsers) { + addDummyStats(user, positionIndex); + positionIndex++; + } + //List nTestUsers = seedNtestUsers(10); + // Now you can do more stuff with the created users if needed } /** * Useful for stress testing with a larger number of users. Seeds the specified number of users dummy users. * * @param numberOfUsers + * @return List of created User objects */ - private void seedNtestUsers(int numberOfUsers) { + private List seedNtestUsers(int numberOfUsers) { + List createdUsers = new ArrayList<>(); for (int i = 1; i <= numberOfUsers; i++) { UserRegistrationDTO userDto = UserRegistrationDTO.builder() .email("testuser" + i + "@email.com") @@ -61,11 +78,13 @@ public class DevUserSeeder implements CommandLineRunner { NotificationProvider.FIREBASE, devProperties.getFcmKey() ); + createdUsers.add(user); } - + return createdUsers; } - private void seedDefaultTestUsers() { + private List seedDefaultTestUsers() { + List createdUsers = new ArrayList<>(); UserRegistrationDTO user1dto = UserRegistrationDTO.builder() .email("user1@email.com") .publicName("Nutzer 1 Public") @@ -79,6 +98,7 @@ public class DevUserSeeder implements CommandLineRunner { NotificationProvider.FIREBASE, devProperties.getFcmKey() ); + createdUsers.add(user1); UserRegistrationDTO user2dto = UserRegistrationDTO.builder() .email("user2@email.com") .publicName("Nutzer 2 Public") @@ -92,9 +112,12 @@ public class DevUserSeeder implements CommandLineRunner { NotificationProvider.FIREBASE, devProperties.getFcmKey() ); + createdUsers.add(user2); + return createdUsers; } - private void seedPgMembers() { + private List seedPgMembers() { + List createdUsers = new ArrayList<>(); UserRegistrationDTO user3dto = UserRegistrationDTO.builder() .email("david@test.com") .publicName("David N. Public") @@ -108,6 +131,7 @@ public class DevUserSeeder implements CommandLineRunner { NotificationProvider.FIREBASE, devProperties.getFcmKey() ); + createdUsers.add(user3); UserRegistrationDTO user4dto = UserRegistrationDTO.builder() .email("davidm@test.com") .publicName("David M Public") @@ -121,6 +145,7 @@ public class DevUserSeeder implements CommandLineRunner { NotificationProvider.FIREBASE, devProperties.getFcmKey() ); + createdUsers.add(user4); UserRegistrationDTO user5dto = UserRegistrationDTO.builder() .email("freddie@test.com") .publicName("Freddie Public") @@ -134,6 +159,7 @@ public class DevUserSeeder implements CommandLineRunner { NotificationProvider.FIREBASE, devProperties.getFcmKey() ); + createdUsers.add(user5); UserRegistrationDTO user6dto = UserRegistrationDTO.builder() .email("elias@test.com") .publicName("Elias Public") @@ -147,6 +173,7 @@ public class DevUserSeeder implements CommandLineRunner { NotificationProvider.FIREBASE, devProperties.getFcmKey() ); + createdUsers.add(user6); UserRegistrationDTO user7dto = UserRegistrationDTO.builder() .email("ibrahim@test.com") .publicName("Ibrahim Public") @@ -160,6 +187,7 @@ public class DevUserSeeder implements CommandLineRunner { NotificationProvider.FIREBASE, devProperties.getFcmKey() ); + createdUsers.add(user7); UserRegistrationDTO user8dto = UserRegistrationDTO.builder() .email("lukas@test.com") .publicName("Lukas Public") @@ -173,6 +201,7 @@ public class DevUserSeeder implements CommandLineRunner { NotificationProvider.FIREBASE, devProperties.getFcmKey() ); + createdUsers.add(user8); UserRegistrationDTO user9dto = UserRegistrationDTO.builder() .email("dennis@test.com") .publicName("Dennis Public") @@ -186,6 +215,7 @@ public class DevUserSeeder implements CommandLineRunner { NotificationProvider.FIREBASE, devProperties.getFcmKey() ); + createdUsers.add(user9); UserRegistrationDTO user10dto = UserRegistrationDTO.builder() .email("daniel@test.com") .publicName("Daniel Public") @@ -199,6 +229,7 @@ public class DevUserSeeder implements CommandLineRunner { NotificationProvider.FIREBASE, devProperties.getFcmKey() ); + createdUsers.add(user10); UserRegistrationDTO user11dto = UserRegistrationDTO.builder() .email("markus@test.com") .publicName("Markus Public") @@ -212,6 +243,7 @@ public class DevUserSeeder implements CommandLineRunner { NotificationProvider.FIREBASE, devProperties.getFcmKey() ); + createdUsers.add(user11); UserRegistrationDTO user12dto = UserRegistrationDTO.builder() .email("piet@test.com") .publicName("Piet Public") @@ -225,5 +257,36 @@ public class DevUserSeeder implements CommandLineRunner { NotificationProvider.FIREBASE, devProperties.getFcmKey() ); + createdUsers.add(user12); + return createdUsers; + } + + private void addDummyStats(User user, Long positionIndex) { + user.getStats().addToStat( + Timeframe.WEEKLY, + "XP", + 100L * positionIndex + ); + user.getStats().addToStat( + Timeframe.WEEKLY, + "CO2_SAVED", + 500L * positionIndex + ); + user.getStats().addToStat( + Timeframe.WEEKLY, + "KM_CYCLED", + 20L * positionIndex + ); + user.getStats().addToStat( + Timeframe.WEEKLY, + "KM_WALKED", + 10L * positionIndex + ); + user.getStats().addToStat( + Timeframe.WEEKLY, + "KM_PUBLIC_TRANSPORT", + 15L * positionIndex + ); + userRepository.save(user); } } From 8b2de7b9c342c4f1d936ef4039990a99ecb3c8aa Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Tue, 10 Feb 2026 15:28:33 +0100 Subject: [PATCH 8/9] filter out transit alternatives that make no sense to user when walking inside transit route is > direct walking --- .../services/AlternativeFilterService.java | 49 +++++++++++++++- .../services/AlternativeRoutingService.java | 4 ++ .../AlternativeFilterServiceTest.java | 57 ++++++++++++++++++- 3 files changed, 105 insertions(+), 5 deletions(-) diff --git a/src/main/java/SuMoC/backend/routing/services/AlternativeFilterService.java b/src/main/java/SuMoC/backend/routing/services/AlternativeFilterService.java index 9cf3d08..13e659b 100644 --- a/src/main/java/SuMoC/backend/routing/services/AlternativeFilterService.java +++ b/src/main/java/SuMoC/backend/routing/services/AlternativeFilterService.java @@ -6,6 +6,8 @@ import SuMoC.backend.meteo.WeatherCondition; 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.trip.Modality; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @@ -50,12 +52,12 @@ public class AlternativeFilterService { if (routeDTO.isPhysicalActivity() && alternativeRequestDTO.getRoutingPreferencesDTO().isPreferPhysicalActivity()) { if (travelTimeDeltaSeconds < routingProperties.getMinimumAcceptedAdditionalSecondsPrefersPhysicalActivity() - || (long) travelTimeDeltaSeconds < toleratedMaximumPhysical) { + || travelTimeDeltaSeconds < toleratedMaximumPhysical) { filteredAlternatives.add(routeDTO); } } else { if (travelTimeDeltaSeconds < routingProperties.getMinimumAcceptedAdditionalSecondsRegular() - || (long) travelTimeDeltaSeconds < toleratedMaximumRegular) { + || travelTimeDeltaSeconds < toleratedMaximumRegular) { filteredAlternatives.add(routeDTO); } } @@ -100,6 +102,49 @@ public class AlternativeFilterService { } } + /** + * This method is meant to filter out transit routes that would make no sense from the user perspective. + * + * @param alternatives + * @return + */ + public List filterForInefficientTransitRoutes( + List alternatives + ) { + List filteredAlternatives = new ArrayList<>(); + + var directWalkingRoute = findDirectWalkingRoute(alternatives); + for (var alternative : alternatives) { + // Case 1: Sum of walking is greater than direct walking route + if (directWalkingRoute != null) { + double alternativeWalkingDistance = alternative.getSteps().stream() + .filter(step -> step.getModality() == Modality.WALKING) + .map(StepDTO::getDistanceMeters) + .reduce(0d, Double::sum); + double directWalkingDistance = directWalkingRoute.getSteps().stream() + .filter(step -> step.getModality() == Modality.WALKING) + .map(StepDTO::getDistanceMeters) + .reduce(0d, Double::sum); + if (directWalkingDistance < alternativeWalkingDistance) { + continue; + } + } + + filteredAlternatives.add(alternative); + } + + return filteredAlternatives; + } + + private RouteDTO findDirectWalkingRoute(List alternatives) { + return alternatives.stream() + .filter(RouteDTO::isWalkingRoute) + .min((r1, r2) -> Long.compare( + r1.getDurationSeconds(), + r2.getDurationSeconds() + )).orElse(null); + } + private boolean allConditionsAcceptable(List conditions, List acceptableConditions) { return new HashSet<>(acceptableConditions).containsAll(conditions); } diff --git a/src/main/java/SuMoC/backend/routing/services/AlternativeRoutingService.java b/src/main/java/SuMoC/backend/routing/services/AlternativeRoutingService.java index a6c2f34..734b6ca 100644 --- a/src/main/java/SuMoC/backend/routing/services/AlternativeRoutingService.java +++ b/src/main/java/SuMoC/backend/routing/services/AlternativeRoutingService.java @@ -32,6 +32,7 @@ public class AlternativeRoutingService { public List determineAlternativeRoutesOnUserRequest(RoutingAlternativeRequestDTO requestDTO) { List routes = directionsService.getPossibleAlternativeRoutes(requestDTO); routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, onCallRoutingProperties); + routes = alternativeFilterService.filterForInefficientTransitRoutes(routes); return routes; } @@ -52,6 +53,7 @@ public class AlternativeRoutingService { routes = alternativeFilterService.filterForBadWeather(requestDTO, routes, adHocRoutingProperties); } + routes = alternativeFilterService.filterForInefficientTransitRoutes(routes); return routes; } @@ -65,6 +67,8 @@ public class AlternativeRoutingService { routes = alternativeFilterService.filterForBadWeather(requestDTO, routes, adHocRoutingProperties); } + routes = alternativeFilterService.filterForInefficientTransitRoutes(routes); + RouteDTO bestRoute = null; // if users wants physical activity, we pick the fastest physical activity route, if any if (requestDTO.getRoutingPreferencesDTO().isPreferPhysicalActivity()) { diff --git a/src/test/java/SuMoC/backend/routing/services/AlternativeFilterServiceTest.java b/src/test/java/SuMoC/backend/routing/services/AlternativeFilterServiceTest.java index baf6529..de4bb88 100644 --- a/src/test/java/SuMoC/backend/routing/services/AlternativeFilterServiceTest.java +++ b/src/test/java/SuMoC/backend/routing/services/AlternativeFilterServiceTest.java @@ -1,9 +1,8 @@ package SuMoC.backend.routing.services; import SuMoC.backend.routing.config.OnCallRoutingProperties; -import SuMoC.backend.routing.dtos.RouteDTO; -import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO; -import SuMoC.backend.routing.dtos.RoutingPreferencesDTO; +import SuMoC.backend.routing.dtos.*; +import SuMoC.backend.trip.Modality; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -12,6 +11,7 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.time.Instant; +import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -109,4 +109,55 @@ public class AlternativeFilterServiceTest { route.setEndDateTime(Instant.parse("2023-01-01T10:00:00Z").plusSeconds(durationSeconds)); return route; } + + @Test + void testFilterForInefficientTransitRoutes_FilterOutTransitWithMoreWalking() { + // Create a direct walking route (500 meters total) + RouteDTO walkingRoute = createRouteWithSteps(List.of( + new StepDTO(Modality.WALKING, 500.0) + )); + + // Create a transit route with more total walking distance (600 meters walking) + RouteDTO transitRoute = createRouteWithSteps(List.of( + new StepDTO(Modality.WALKING, 300.0), + new TransitStepDTO(Modality.BUS, 2000.0, "101", "City Center", "Main St", "5th Ave"), + new StepDTO(Modality.WALKING, 300.0) + )); + + List alternatives = List.of(walkingRoute, transitRoute); + + List result = alternativeFilterService.filterForInefficientTransitRoutes(alternatives); + + // Transit route should be filtered out because walking distance (600m) > direct walking route (500m) + assertEquals(1, result.size()); + assertEquals(walkingRoute, result.get(0)); + } + + @Test + void testFilterForInefficientTransitRoutes_KeepTransitWithLessWalking() { + // Create a direct walking route (1000 meters total) + RouteDTO walkingRoute = createRouteWithSteps(List.of( + new StepDTO(Modality.WALKING, 1000.0) + )); + + // Create a transit route with less total walking distance (400 meters walking) + RouteDTO transitRoute = createRouteWithSteps(List.of( + new StepDTO(Modality.WALKING, 200.0), + new TransitStepDTO(Modality.BUS, 3000.0, "102", "Downtown", "Park Ave", "Central Station"), + new StepDTO(Modality.WALKING, 200.0) + )); + + List alternatives = List.of(walkingRoute, transitRoute); + + List result = alternativeFilterService.filterForInefficientTransitRoutes(alternatives); + + // Both routes should be kept because transit walking (400m) < direct walking route (1000m) + assertEquals(2, result.size()); + } + + private RouteDTO createRouteWithSteps(List steps) { + RouteDTO route = RouteDTO.getMockRouteDTO(); + route.setSteps(new ArrayList<>(steps)); + return route; + } } From 8f62d853e4f1a21f6f23034cbbe8a6ea9beb7034 Mon Sep 17 00:00:00 2001 From: David Neuhauss Date: Tue, 10 Feb 2026 16:00:04 +0100 Subject: [PATCH 9/9] fix check if user is logged in --- .../routing/services/RoutingPreferencesService.java | 2 +- .../SuMoC/backend/user/service/CurrentUserService.java | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/SuMoC/backend/routing/services/RoutingPreferencesService.java b/src/main/java/SuMoC/backend/routing/services/RoutingPreferencesService.java index 558ac21..845517c 100644 --- a/src/main/java/SuMoC/backend/routing/services/RoutingPreferencesService.java +++ b/src/main/java/SuMoC/backend/routing/services/RoutingPreferencesService.java @@ -52,7 +52,7 @@ public class RoutingPreferencesService { * Gets routing preferences for the current user, if user is logged in returns his preferences, if not logged in returns default preferences. */ public RoutingPreferencesDTO getRoutingPreferencesForCurrentUser() { - if (currentUserService.isAuthenticated()) { + if (currentUserService.isLoggedInUser()) { var currentUser = currentUserService.get(); return getUserRoutingPreferences(currentUser.getId()); } else { diff --git a/src/main/java/SuMoC/backend/user/service/CurrentUserService.java b/src/main/java/SuMoC/backend/user/service/CurrentUserService.java index a25ffa0..fd51471 100644 --- a/src/main/java/SuMoC/backend/user/service/CurrentUserService.java +++ b/src/main/java/SuMoC/backend/user/service/CurrentUserService.java @@ -3,6 +3,7 @@ package SuMoC.backend.user.service; import SuMoC.backend.user.models.User; import SuMoC.backend.user.repository.UserRepository; import org.springframework.http.HttpStatus; +import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; @@ -32,9 +33,9 @@ public class CurrentUserService { "Der Nutzer existiert nicht")); } - public boolean isAuthenticated() { - // TODO request with auth no auth really result in not authenticated? + public boolean isLoggedInUser() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - return auth != null && auth.isAuthenticated(); + return auth != null && auth.isAuthenticated() && !(auth instanceof AnonymousAuthenticationToken); + } } \ No newline at end of file