From 73473afb925033e24081e86ff769c654c27cf47a Mon Sep 17 00:00:00 2001 From: bogdandina Date: Wed, 17 Sep 2025 09:43:50 +0300 Subject: [PATCH] feat(64982): integrate autoformatter --- .github/workflows/test-and-build.yml | 4 + eclipse-java-formatter.xml | 18 ++ pom.xml | 30 ++- .../tripupdate/application/MessageRouter.java | 56 +++-- .../tripupdate/application/MessageStats.java | 12 +- .../tripupdate/gtfsrt/GtfsRtFactory.java | 79 ++++--- .../tripupdate/gtfsrt/GtfsRtValidator.java | 84 ++++---- .../processing/AbstractMessageProcessor.java | 4 +- .../processing/StopEstimateProcessor.java | 10 +- .../processing/TripCancellationProcessor.java | 21 +- .../processing/TripUpdateProcessor.java | 132 ++++++------ .../validators/MissingEstimatesValidator.java | 4 +- .../PrematureDeparturesValidator.java | 24 ++- .../validators/TripUpdateMaxAgeValidator.java | 15 +- .../tripupdate/MockDataFactory.java | 41 ++-- .../gtfsrt/GtfsRtValidatorTest.java | 88 ++++---- .../processing/StopEstimateProcessorTest.java | 58 +++-- .../TripCancellationProcessorTest.java | 64 +++--- .../processing/TripUpdateProcessorTest.java | 204 +++++++----------- .../PrematureDeparturesValidatorTest.java | 15 +- .../TripUpdateMaxAgeValidatorTest.java | 6 +- 21 files changed, 490 insertions(+), 479 deletions(-) create mode 100644 eclipse-java-formatter.xml diff --git a/.github/workflows/test-and-build.yml b/.github/workflows/test-and-build.yml index b0c4bf9..9a7f844 100644 --- a/.github/workflows/test-and-build.yml +++ b/.github/workflows/test-and-build.yml @@ -13,6 +13,10 @@ jobs: distribution: 'adopt' java-version: '11' cache: 'maven' + - name: Run Spotless Apply + run: mvn spotless:apply + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Build with Maven run: mvn --file pom.xml clean install env: diff --git a/eclipse-java-formatter.xml b/eclipse-java-formatter.xml new file mode 100644 index 0000000..4ae144a --- /dev/null +++ b/eclipse-java-formatter.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index ab0acde..e075cb5 100644 --- a/pom.xml +++ b/pom.xml @@ -16,8 +16,10 @@ UTF-8 11 11 - 2.0.3-RC6 + 2.0.5 1.17.6 + 2.43.0 + 1.17.0 @@ -205,6 +207,32 @@ + + com.diffplug.spotless + spotless-maven-plugin + ${spotlessMavenPlugin.version} + + + + ${project.basedir}/eclipse-java-formatter.xml + + + + + + spotless-check + + check + + + + spotless-apply + + apply + + + + diff --git a/src/main/java/fi/hsl/transitdata/tripupdate/application/MessageRouter.java b/src/main/java/fi/hsl/transitdata/tripupdate/application/MessageRouter.java index d8c2715..faa29b9 100644 --- a/src/main/java/fi/hsl/transitdata/tripupdate/application/MessageRouter.java +++ b/src/main/java/fi/hsl/transitdata/tripupdate/application/MessageRouter.java @@ -57,18 +57,23 @@ private void registerHandlers(PulsarApplicationContext context) { final boolean filterTrainData = config.getBoolean("validator.filterTrainData"); - processors.put(ProtobufSchema.InternalMessagesStopEstimate, new StopEstimateProcessor(tripUpdateProcessor, filterTrainData)); - processors.put(ProtobufSchema.InternalMessagesTripCancellation, new TripCancellationProcessor(tripUpdateProcessor, filterTrainData)); + processors.put(ProtobufSchema.InternalMessagesStopEstimate, + new StopEstimateProcessor(tripUpdateProcessor, filterTrainData)); + processors.put(ProtobufSchema.InternalMessagesTripCancellation, + new TripCancellationProcessor(tripUpdateProcessor, filterTrainData)); } private List registerTripUpdateValidators() { List tripUpdateValidators = new ArrayList<>(); - tripUpdateValidators.add(new TripUpdateMaxAgeValidator(config.getDuration("validator.tripUpdateMaxAge", TimeUnit.SECONDS))); - tripUpdateValidators.add(new PrematureDeparturesValidator(config.getDuration("validator.tripUpdateMinTimeBeforeDeparture", TimeUnit.SECONDS), + tripUpdateValidators + .add(new TripUpdateMaxAgeValidator(config.getDuration("validator.tripUpdateMaxAge", TimeUnit.SECONDS))); + tripUpdateValidators.add(new PrematureDeparturesValidator( + config.getDuration("validator.tripUpdateMinTimeBeforeDeparture", TimeUnit.SECONDS), config.getString("validator.timezone"))); - tripUpdateValidators.add(new MissingEstimatesValidator(config.getInt("validator.tripUpdateMaxMissingEstimates"))); + tripUpdateValidators + .add(new MissingEstimatesValidator(config.getInt("validator.tripUpdateMaxMissingEstimates"))); return tripUpdateValidators; @@ -84,7 +89,8 @@ public void handleMessage(Message received) { if (processor != null) { if (processor.validateMessage(received.getData())) { - Optional maybeTripUpdate = processor.processMessage(received); + Optional maybeTripUpdate = processor + .processMessage(received); if (maybeTripUpdate.isPresent()) { final AbstractMessageProcessor.TripUpdateWithId pair = maybeTripUpdate.get(); final GtfsRealtime.TripUpdate tripUpdate = pair.getTripUpdate(); @@ -93,9 +99,13 @@ public void handleMessage(Message received) { final boolean isValid = validator.validate(tripUpdate); if (!isValid) { final GtfsRealtime.TripDescriptor trip = tripUpdate.getTrip(); - log.debug("Trip update for {} / {} / {} / {} failed validation when validating with {}", trip.getRouteId(), trip.getDirectionId(), trip.getStartDate(), trip.getStartTime(), validator.getClass().getName()); + log.debug( + "Trip update for {} / {} / {} / {} failed validation when validating with {}", + trip.getRouteId(), trip.getDirectionId(), trip.getStartDate(), + trip.getStartTime(), validator.getClass().getName()); - messageStats.incrementInvalidTripUpdates("validator-" + validator.getClass().getSimpleName()); + messageStats.incrementInvalidTripUpdates( + "validator-" + validator.getClass().getSimpleName()); } return isValid; }); @@ -118,12 +128,11 @@ public void handleMessage(Message received) { } }); - consumer.acknowledgeAsync(received) - .exceptionally(throwable -> { - log.error("Failed to ack Pulsar message", throwable); - return null; - }) - .thenRun(() -> {}); + consumer.acknowledgeAsync(received).exceptionally(throwable -> { + log.error("Failed to ack Pulsar message", throwable); + return null; + }).thenRun(() -> { + }); } catch (Exception e) { log.error("Exception while handling message", e); } @@ -133,22 +142,23 @@ public void handleMessage(Message received) { } } - private void sendTripUpdate(final AbstractMessageProcessor.TripUpdateWithId tuIdPair, final long pulsarEventTimestamp) { + private void sendTripUpdate(final AbstractMessageProcessor.TripUpdateWithId tuIdPair, + final long pulsarEventTimestamp) { messageStats.incrementMessagesSent(); final String tripId = tuIdPair.getTripId(); final GtfsRealtime.TripUpdate tripUpdate = tuIdPair.getTripUpdate(); debouncer.debounce(tripId, () -> { - GtfsRealtime.FeedMessage feedMessage = FeedMessageFactory.createDifferentialFeedMessage(tripId, tripUpdate, tripUpdate.getTimestamp()); - producer.newMessage() - .key(tripId) - .eventTime(pulsarEventTimestamp) - .property(TransitdataProperties.KEY_PROTOBUF_SCHEMA, TransitdataProperties.ProtobufSchema.GTFS_TripUpdate.toString()) - .value(feedMessage.toByteArray()) - .sendAsync() + GtfsRealtime.FeedMessage feedMessage = FeedMessageFactory.createDifferentialFeedMessage(tripId, tripUpdate, + tripUpdate.getTimestamp()); + producer.newMessage().key(tripId).eventTime(pulsarEventTimestamp) + .property(TransitdataProperties.KEY_PROTOBUF_SCHEMA, + TransitdataProperties.ProtobufSchema.GTFS_TripUpdate.toString()) + .value(feedMessage.toByteArray()).sendAsync() .thenRun(() -> log.debug("Sending TripUpdate for tripId {} with {} StopTimeUpdates and status {}", - tripId, tripUpdate.getStopTimeUpdateCount(), tripUpdate.getTrip().getScheduleRelationship())); + tripId, tripUpdate.getStopTimeUpdateCount(), + tripUpdate.getTrip().getScheduleRelationship())); }); } } diff --git a/src/main/java/fi/hsl/transitdata/tripupdate/application/MessageStats.java b/src/main/java/fi/hsl/transitdata/tripupdate/application/MessageStats.java index 1122699..770ba24 100644 --- a/src/main/java/fi/hsl/transitdata/tripupdate/application/MessageStats.java +++ b/src/main/java/fi/hsl/transitdata/tripupdate/application/MessageStats.java @@ -1,6 +1,5 @@ package fi.hsl.transitdata.tripupdate.application; - import org.slf4j.Logger; import java.util.HashMap; @@ -71,12 +70,11 @@ public void logAndReset(Logger logger) { @Override public String toString() { - final String reasonsText = invalidTripUpdateReasons.entrySet().stream().map(entry -> entry.getKey() + ": " + entry.getValue()).collect(Collectors.joining(", ")); + final String reasonsText = invalidTripUpdateReasons.entrySet().stream() + .map(entry -> entry.getKey() + ": " + entry.getValue()).collect(Collectors.joining(", ")); - return "Message stats:\n"+ - "\tStart time: " + getDurationSecs() + " seconds ago\n" + - "\tMessages received: " + messagesReceived + "\n" + - "\tMessages sent: " + messagesSent + "\n" + - "\tInvalid trip updates: " + invalidTripUpdates + "(" + reasonsText + ")"; + return "Message stats:\n" + "\tStart time: " + getDurationSecs() + " seconds ago\n" + "\tMessages received: " + + messagesReceived + "\n" + "\tMessages sent: " + messagesSent + "\n" + "\tInvalid trip updates: " + + invalidTripUpdates + "(" + reasonsText + ")"; } } diff --git a/src/main/java/fi/hsl/transitdata/tripupdate/gtfsrt/GtfsRtFactory.java b/src/main/java/fi/hsl/transitdata/tripupdate/gtfsrt/GtfsRtFactory.java index d336264..f19b61e 100644 --- a/src/main/java/fi/hsl/transitdata/tripupdate/gtfsrt/GtfsRtFactory.java +++ b/src/main/java/fi/hsl/transitdata/tripupdate/gtfsrt/GtfsRtFactory.java @@ -18,8 +18,7 @@ public static GtfsRealtime.TripUpdate.StopTimeUpdate newStopTimeUpdate(InternalM } public static GtfsRealtime.TripUpdate.StopTimeUpdate newStopTimeUpdateFromPrevious( - final InternalMessages.StopEstimate stopEstimate, - GtfsRealtime.TripUpdate.StopTimeUpdate previousUpdate) { + final InternalMessages.StopEstimate stopEstimate, GtfsRealtime.TripUpdate.StopTimeUpdate previousUpdate) { GtfsRealtime.TripUpdate.StopTimeUpdate.Builder stopTimeUpdateBuilder = null; if (previousUpdate != null) { @@ -27,23 +26,26 @@ public static GtfsRealtime.TripUpdate.StopTimeUpdate newStopTimeUpdateFromPrevio } else { String stopId = stopEstimate.getStopId(); int stopSequence = stopEstimate.getStopSequence(); - stopTimeUpdateBuilder = GtfsRealtime.TripUpdate.StopTimeUpdate.newBuilder() - .setStopId(stopId) + stopTimeUpdateBuilder = GtfsRealtime.TripUpdate.StopTimeUpdate.newBuilder().setStopId(stopId) .setStopSequence(stopSequence); } switch (stopEstimate.getStatus()) { - case SKIPPED: - stopTimeUpdateBuilder.setScheduleRelationship(GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.SKIPPED); + case SKIPPED : + stopTimeUpdateBuilder + .setScheduleRelationship(GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.SKIPPED); break; - case SCHEDULED: - stopTimeUpdateBuilder.setScheduleRelationship(GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.SCHEDULED); + case SCHEDULED : + stopTimeUpdateBuilder + .setScheduleRelationship(GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.SCHEDULED); break; - case NO_DATA: + case NO_DATA : //If there is no data for current or previous stop time update, set ScheduleRelationship to NO_DATA - if (previousUpdate == null || previousUpdate.getScheduleRelationship() == GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.NO_DATA) { - stopTimeUpdateBuilder.setScheduleRelationship(GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.NO_DATA); - //Otherwise use ScheduleRelationship of previous stop time update + if (previousUpdate == null || previousUpdate + .getScheduleRelationship() == GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.NO_DATA) { + stopTimeUpdateBuilder.setScheduleRelationship( + GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.NO_DATA); + //Otherwise use ScheduleRelationship of previous stop time update } else { stopTimeUpdateBuilder.setScheduleRelationship(previousUpdate.getScheduleRelationship()); } @@ -54,8 +56,8 @@ public static GtfsRealtime.TripUpdate.StopTimeUpdate newStopTimeUpdateFromPrevio // GTFS-RT treats times in seconds long stopEventTimeInSeconds = stopEstimate.getEstimatedTimeUtcMs() / 1000; - GtfsRealtime.TripUpdate.StopTimeEvent.Builder stopTimeEvent = GtfsRealtime.TripUpdate.StopTimeEvent.newBuilder() - .setTime(stopEventTimeInSeconds); + GtfsRealtime.TripUpdate.StopTimeEvent.Builder stopTimeEvent = GtfsRealtime.TripUpdate.StopTimeEvent + .newBuilder().setTime(stopEventTimeInSeconds); //Whether the event was observed in real world (i.e. not an estimate) final boolean observedTime = stopEstimate.hasObservedTime() && stopEstimate.getObservedTime(); @@ -64,10 +66,10 @@ public static GtfsRealtime.TripUpdate.StopTimeUpdate newStopTimeUpdateFromPrevio } switch (stopEstimate.getType()) { - case ARRIVAL: + case ARRIVAL : stopTimeUpdateBuilder.setArrival(stopTimeEvent); break; - case DEPARTURE: + case DEPARTURE : stopTimeUpdateBuilder.setDeparture(stopTimeEvent); break; } @@ -83,54 +85,50 @@ public static long lastModified(InternalMessages.StopEstimate estimate) { public static GtfsRealtime.TripUpdate newTripUpdate(InternalMessages.StopEstimate estimate) { final int direction = PubtransFactory.joreDirectionToGtfsDirection(estimate.getTripInfo().getDirectionId()); String routeId = RouteIdUtils.normalizeRouteId(estimate.getTripInfo().getRouteId()); - - GtfsRealtime.TripDescriptor.ScheduleRelationship scheduleType = mapInternalScheduleTypeToGtfsRt(estimate.getTripInfo().getScheduleType()); - + + GtfsRealtime.TripDescriptor.ScheduleRelationship scheduleType = mapInternalScheduleTypeToGtfsRt( + estimate.getTripInfo().getScheduleType()); + GtfsRealtime.TripDescriptor.Builder tripDescriptor = GtfsRealtime.TripDescriptor.newBuilder() - .setRouteId(routeId) - .setDirectionId(direction) - .setStartDate(estimate.getTripInfo().getOperatingDay()) // Local date as String + .setRouteId(routeId).setDirectionId(direction).setStartDate(estimate.getTripInfo().getOperatingDay()) // Local date as String .setStartTime(estimate.getTripInfo().getStartTime()) // Local time as String .setScheduleRelationship(scheduleType); - + //Trips outside of static schedule need trip ID to be accepted by OTP if (scheduleType != GtfsRealtime.TripDescriptor.ScheduleRelationship.SCHEDULED) { tripDescriptor.setTripId(generateTripId(estimate.getTripInfo())); } - GtfsRealtime.TripUpdate.Builder tripUpdateBuilder = GtfsRealtime.TripUpdate.newBuilder() - .setTrip(tripDescriptor) + GtfsRealtime.TripUpdate.Builder tripUpdateBuilder = GtfsRealtime.TripUpdate.newBuilder().setTrip(tripDescriptor) .setTimestamp(lastModified(estimate)); return tripUpdateBuilder.build(); } - private static GtfsRealtime.TripDescriptor.ScheduleRelationship mapInternalScheduleTypeToGtfsRt(InternalMessages.TripInfo.ScheduleType scheduleType) { + private static GtfsRealtime.TripDescriptor.ScheduleRelationship mapInternalScheduleTypeToGtfsRt( + InternalMessages.TripInfo.ScheduleType scheduleType) { switch (scheduleType) { - case ADDED: + case ADDED : return GtfsRealtime.TripDescriptor.ScheduleRelationship.ADDED; - case UNSCHEDULED: + case UNSCHEDULED : return GtfsRealtime.TripDescriptor.ScheduleRelationship.UNSCHEDULED; - case SCHEDULED: - default: + case SCHEDULED : + default : return GtfsRealtime.TripDescriptor.ScheduleRelationship.SCHEDULED; } } - public static GtfsRealtime.TripUpdate newTripUpdate(InternalMessages.TripCancellation cancellation, long timestampMs) { + public static GtfsRealtime.TripUpdate newTripUpdate(InternalMessages.TripCancellation cancellation, + long timestampMs) { final int gtfsRtDirection = PubtransFactory.joreDirectionToGtfsDirection(cancellation.getDirectionId()); String routeId = RouteIdUtils.normalizeRouteId(cancellation.getRouteId()); - GtfsRealtime.TripDescriptor tripDescriptor = GtfsRealtime.TripDescriptor.newBuilder() - .setRouteId(routeId) - .setDirectionId(gtfsRtDirection) - .setStartDate(cancellation.getStartDate()) + GtfsRealtime.TripDescriptor tripDescriptor = GtfsRealtime.TripDescriptor.newBuilder().setRouteId(routeId) + .setDirectionId(gtfsRtDirection).setStartDate(cancellation.getStartDate()) .setStartTime(cancellation.getStartTime()) - .setScheduleRelationship(GtfsRealtime.TripDescriptor.ScheduleRelationship.CANCELED) - .build(); + .setScheduleRelationship(GtfsRealtime.TripDescriptor.ScheduleRelationship.CANCELED).build(); - GtfsRealtime.TripUpdate.Builder tripUpdateBuilder = GtfsRealtime.TripUpdate.newBuilder() - .setTrip(tripDescriptor) + GtfsRealtime.TripUpdate.Builder tripUpdateBuilder = GtfsRealtime.TripUpdate.newBuilder().setTrip(tripDescriptor) .setTimestamp(timestampMs / 1000); return tripUpdateBuilder.build(); @@ -142,6 +140,7 @@ public static GtfsRealtime.TripUpdate newTripUpdate(InternalMessages.TripCancell * @return Trip ID */ private static String generateTripId(InternalMessages.TripInfo tripInfo) { - return tripInfo.getRouteId()+"_"+tripInfo.getOperatingDay()+"_"+tripInfo.getStartTime()+"_"+tripInfo.getDirectionId(); + return tripInfo.getRouteId() + "_" + tripInfo.getOperatingDay() + "_" + tripInfo.getStartTime() + "_" + + tripInfo.getDirectionId(); } } diff --git a/src/main/java/fi/hsl/transitdata/tripupdate/gtfsrt/GtfsRtValidator.java b/src/main/java/fi/hsl/transitdata/tripupdate/gtfsrt/GtfsRtValidator.java index 23b454c..0930d7e 100644 --- a/src/main/java/fi/hsl/transitdata/tripupdate/gtfsrt/GtfsRtValidator.java +++ b/src/main/java/fi/hsl/transitdata/tripupdate/gtfsrt/GtfsRtValidator.java @@ -8,7 +8,8 @@ import static com.google.transit.realtime.GtfsRealtime.TripUpdate.*; public class GtfsRtValidator { - private GtfsRtValidator() {} + private GtfsRtValidator() { + } public static List cleanStopTimeUpdates(List rawEstimates, StopTimeUpdate latest) { List fixedTimestamps = validateArrivalsAndDepartures(rawEstimates, latest); @@ -23,9 +24,8 @@ public static List cleanStopTimeUpdates(List raw * Our updates might have extra via-points there which can confuse the clients. */ static List removeStopSequences(List updates) { - return updates.stream().map(update -> - update.toBuilder().clearStopSequence().build() - ).collect(Collectors.toList()); + return updates.stream().map(update -> update.toBuilder().clearStopSequence().build()) + .collect(Collectors.toList()); } /** @@ -37,22 +37,12 @@ static List removeStopSequences(List updates) { static List fillMissingArrivalsAndDepartures(List updates) { return updates.stream().map(update -> { if (update.hasArrival() && !update.hasDeparture()) { - StopTimeEvent newDeparture = StopTimeEvent.newBuilder() - .setTime(update.getArrival().getTime()) - .build(); - return update.toBuilder() - .setDeparture(newDeparture) - .build(); - } - else if (update.hasDeparture() && !update.hasArrival()) { - StopTimeEvent newArrival = StopTimeEvent.newBuilder() - .setTime(update.getDeparture().getTime()) - .build(); - return update.toBuilder() - .setArrival(newArrival) - .build(); - } - else { + StopTimeEvent newDeparture = StopTimeEvent.newBuilder().setTime(update.getArrival().getTime()).build(); + return update.toBuilder().setDeparture(newDeparture).build(); + } else if (update.hasDeparture() && !update.hasArrival()) { + StopTimeEvent newArrival = StopTimeEvent.newBuilder().setTime(update.getDeparture().getTime()).build(); + return update.toBuilder().setArrival(newArrival).build(); + } else { return update; } }).collect(Collectors.toList()); @@ -63,10 +53,11 @@ else if (update.hasDeparture() && !update.hasArrival()) { * and also to running times (current arrival before previous departure). * OpenTripPlanner won't accept this, so we'll try to fix the timestamps by adjusting them appropriately. */ - static List validateArrivalsAndDepartures(List rawEstimates, StopTimeUpdate latest) { + static List validateArrivalsAndDepartures(List rawEstimates, + StopTimeUpdate latest) { LinkedList validList = new LinkedList<>(); StopTimeUpdate previous = null; - for (StopTimeUpdate unvalidated: rawEstimates) { + for (StopTimeUpdate unvalidated : rawEstimates) { // If this is the latest message and it happens to be arrival, we want to use that timestamp. // otherwise always use departure. OnConflict conflictBehavior = OnConflict.DepartureWins; @@ -82,8 +73,7 @@ static List validateArrivalsAndDepartures(List r } enum OnConflict { - DepartureWins, - ArrivalWins + DepartureWins, ArrivalWins } static StopTimeUpdate validateTimestamps(StopTimeUpdate prev, StopTimeUpdate cur, OnConflict conflictBehavior) { @@ -94,8 +84,7 @@ static StopTimeUpdate validateTimestamps(StopTimeUpdate prev, StopTimeUpdate cur if (prev != null) { if (prev.hasDeparture()) { maybePrevTimestamp = Optional.of(prev.getDeparture().getTime()); - } - else if (prev.hasArrival()) { + } else if (prev.hasArrival()) { maybePrevTimestamp = Optional.of(prev.getArrival().getTime()); } } @@ -103,7 +92,9 @@ else if (prev.hasArrival()) { final Optional curArrival = cur.hasArrival() ? Optional.of(cur.getArrival()) : Optional.empty(); Optional newArrival = validateMinTime(curArrival, maybePrevTimestamp); - final Optional curDeparture = cur.hasDeparture() ? Optional.of(cur.getDeparture()) : Optional.empty(); + final Optional curDeparture = cur.hasDeparture() + ? Optional.of(cur.getDeparture()) + : Optional.empty(); Optional newDeparture = validateMinTime(curDeparture, maybePrevTimestamp); // Now both are at least >= then previous timestamp. @@ -111,8 +102,7 @@ else if (prev.hasArrival()) { if (conflictBehavior == OnConflict.ArrivalWins) { Optional maybeArrivalTimestamp = newArrival.map(StopTimeEvent::getTime); newDeparture = validateMinTime(newDeparture, maybeArrivalTimestamp); - } - else if (conflictBehavior == OnConflict.DepartureWins) { + } else if (conflictBehavior == OnConflict.DepartureWins) { Optional maybeDepartureTimestamp = newDeparture.map(StopTimeEvent::getTime); newArrival = validateMaxTime(newArrival, maybeDepartureTimestamp); } @@ -127,29 +117,29 @@ else if (conflictBehavior == OnConflict.DepartureWins) { /** * Either return the same valid StopTimeEvent or create a copy with time adjusted to minimum */ - static Optional validateMinTime(final Optional maybeEvent, final Optional maybeMinTime) { - return maybeEvent.map(event -> - maybeMinTime.map(minTimestamp -> { - if (event.getTime() < minTimestamp) { - return event.toBuilder().setTime(minTimestamp).build(); - } else { - return event; - } - }).orElse(event)); + static Optional validateMinTime(final Optional maybeEvent, + final Optional maybeMinTime) { + return maybeEvent.map(event -> maybeMinTime.map(minTimestamp -> { + if (event.getTime() < minTimestamp) { + return event.toBuilder().setTime(minTimestamp).build(); + } else { + return event; + } + }).orElse(event)); } /** * Either return the same valid StopTimeEvent or create a copy with time adjusted to maximum */ - static Optional validateMaxTime(final Optional maybeEvent, final Optional maybeMaxTime) { - return maybeEvent.map(event -> - maybeMaxTime.map(maxTimestamp -> { - if (event.getTime() > maxTimestamp) { - return event.toBuilder().setTime(maxTimestamp).build(); - } else { - return event; - } - }).orElse(event)); + static Optional validateMaxTime(final Optional maybeEvent, + final Optional maybeMaxTime) { + return maybeEvent.map(event -> maybeMaxTime.map(maxTimestamp -> { + if (event.getTime() > maxTimestamp) { + return event.toBuilder().setTime(maxTimestamp).build(); + } else { + return event; + } + }).orElse(event)); } static List removeEstimatesFromNoDataUpdates(List stopTimeUpdates) { diff --git a/src/main/java/fi/hsl/transitdata/tripupdate/processing/AbstractMessageProcessor.java b/src/main/java/fi/hsl/transitdata/tripupdate/processing/AbstractMessageProcessor.java index c7fc3ef..cec5fef 100644 --- a/src/main/java/fi/hsl/transitdata/tripupdate/processing/AbstractMessageProcessor.java +++ b/src/main/java/fi/hsl/transitdata/tripupdate/processing/AbstractMessageProcessor.java @@ -52,7 +52,6 @@ public GtfsRealtime.TripUpdate getTripUpdate() { */ public abstract Optional processMessage(Message msg); - protected boolean validateTripData(String routeName, int direction) { //Normalize route ID before validation routeName = RouteIdUtils.normalizeRouteId(routeName); @@ -67,7 +66,8 @@ protected boolean validateTripData(String routeName, int direction) { return false; } - if (direction != PubtransFactory.JORE_DIRECTION_ID_INBOUND && direction != PubtransFactory.JORE_DIRECTION_ID_OUTBOUND) { + if (direction != PubtransFactory.JORE_DIRECTION_ID_INBOUND + && direction != PubtransFactory.JORE_DIRECTION_ID_OUTBOUND) { logger.info("Direction {} is not a valid JORE-direction, discarding message", direction); return false; } diff --git a/src/main/java/fi/hsl/transitdata/tripupdate/processing/StopEstimateProcessor.java b/src/main/java/fi/hsl/transitdata/tripupdate/processing/StopEstimateProcessor.java index 182383e..da2cd58 100644 --- a/src/main/java/fi/hsl/transitdata/tripupdate/processing/StopEstimateProcessor.java +++ b/src/main/java/fi/hsl/transitdata/tripupdate/processing/StopEstimateProcessor.java @@ -26,11 +26,8 @@ public Optional processMessage(Message msg) { final String tripId = data.getTripInfo().getTripId(); Optional maybeTripUpdate = tripProcessor.processStopEstimate(data); - return maybeTripUpdate.flatMap(tripUpdate -> - TripUpdateWithId.newInstance(tripId, tripUpdate) - ); - } - catch (Exception e) { + return maybeTripUpdate.flatMap(tripUpdate -> TripUpdateWithId.newInstance(tripId, tripUpdate)); + } catch (Exception e) { log.error("Failed to parse message payload", e); return Optional.empty(); } @@ -44,8 +41,7 @@ public boolean validateMessage(byte[] payload) { int direction = data.getTripInfo().getDirectionId(); return validateTripData(route, direction); - } - catch (InvalidProtocolBufferException e) { + } catch (InvalidProtocolBufferException e) { log.error("Failed to parse StopEstimate from message payload", e); return false; } diff --git a/src/main/java/fi/hsl/transitdata/tripupdate/processing/TripCancellationProcessor.java b/src/main/java/fi/hsl/transitdata/tripupdate/processing/TripCancellationProcessor.java index 744df14..192db4b 100644 --- a/src/main/java/fi/hsl/transitdata/tripupdate/processing/TripCancellationProcessor.java +++ b/src/main/java/fi/hsl/transitdata/tripupdate/processing/TripCancellationProcessor.java @@ -26,17 +26,20 @@ public boolean validateMessage(byte[] payload) { try { InternalMessages.TripCancellation tripCancellation = InternalMessages.TripCancellation.parseFrom(payload); - final boolean entireDepartureCancelled = - tripCancellation.getAffectedDeparturesType() == InternalMessages.TripCancellation.AffectedDeparturesType.CANCEL_ENTIRE_DEPARTURE && - tripCancellation.getDeviationCasesType() == InternalMessages.TripCancellation.DeviationCasesType.CANCEL_DEPARTURE; + final boolean entireDepartureCancelled = tripCancellation + .getAffectedDeparturesType() == InternalMessages.TripCancellation.AffectedDeparturesType.CANCEL_ENTIRE_DEPARTURE + && tripCancellation + .getDeviationCasesType() == InternalMessages.TripCancellation.DeviationCasesType.CANCEL_DEPARTURE; if (!entireDepartureCancelled) { //Produce cancellation messages only for full cancellations and not partial cancellations - log.debug("{} (dir: {}) at {} {} was not fully cancelled, ignoring cancellation message..", tripCancellation.getRouteId(), tripCancellation.getDirectionId(), tripCancellation.getStartDate(), tripCancellation.getStartTime()); + log.debug("{} (dir: {}) at {} {} was not fully cancelled, ignoring cancellation message..", + tripCancellation.getRouteId(), tripCancellation.getDirectionId(), + tripCancellation.getStartDate(), tripCancellation.getStartTime()); return false; } - if (tripCancellation.hasDirectionId() && tripCancellation.hasRouteId() && - tripCancellation.hasStartDate() && tripCancellation.hasStartTime()) { + if (tripCancellation.hasDirectionId() && tripCancellation.hasRouteId() && tripCancellation.hasStartDate() + && tripCancellation.hasStartTime()) { String route = tripCancellation.getRouteId(); int directionId = tripCancellation.getDirectionId(); @@ -52,10 +55,12 @@ public boolean validateMessage(byte[] payload) { @Override public Optional processMessage(Message msg) { try { - InternalMessages.TripCancellation tripCancellation = InternalMessages.TripCancellation.parseFrom(msg.getData()); + InternalMessages.TripCancellation tripCancellation = InternalMessages.TripCancellation + .parseFrom(msg.getData()); final String tripId = tripCancellation.getTripId(); - GtfsRealtime.TripUpdate tripUpdate = tripUpdateProcessor.processTripCancellation(msg.getKey(), msg.getEventTime(), tripCancellation); + GtfsRealtime.TripUpdate tripUpdate = tripUpdateProcessor.processTripCancellation(msg.getKey(), + msg.getEventTime(), tripCancellation); return TripUpdateWithId.newInstance(tripId, tripUpdate); } catch (Exception e) { log.error("Could not parse TripCancellation: " + e.getMessage(), e); diff --git a/src/main/java/fi/hsl/transitdata/tripupdate/processing/TripUpdateProcessor.java b/src/main/java/fi/hsl/transitdata/tripupdate/processing/TripUpdateProcessor.java index ee4d48c..c8135d7 100644 --- a/src/main/java/fi/hsl/transitdata/tripupdate/processing/TripUpdateProcessor.java +++ b/src/main/java/fi/hsl/transitdata/tripupdate/processing/TripUpdateProcessor.java @@ -36,24 +36,16 @@ public class TripUpdateProcessor { private final Cache>> cancellationsCache; public TripUpdateProcessor(Producer producer) { - this.tripUpdateCache = Caffeine.newBuilder() - .expireAfterAccess(CACHE_DURATION) - .build(); + this.tripUpdateCache = Caffeine.newBuilder().expireAfterAccess(CACHE_DURATION).build(); - this.stopTimeUpdateCache = Caffeine.newBuilder() - .expireAfterAccess(CACHE_DURATION) - .build(key -> { - //TreeMap keeps its entries sorted according to the natural ordering of its keys. - return new TreeMap<>(); - }); + this.stopTimeUpdateCache = Caffeine.newBuilder().expireAfterAccess(CACHE_DURATION).build(key -> { + //TreeMap keeps its entries sorted according to the natural ordering of its keys. + return new TreeMap<>(); + }); - this.scheduleRelationshipCache = Caffeine.newBuilder() - .expireAfterWrite(CACHE_DURATION) - .build(); + this.scheduleRelationshipCache = Caffeine.newBuilder().expireAfterWrite(CACHE_DURATION).build(); - this.cancellationsCache = Caffeine.newBuilder() - .expireAfterAccess(CACHE_DURATION) - .build(key -> new HashMap<>()); + this.cancellationsCache = Caffeine.newBuilder().expireAfterAccess(CACHE_DURATION).build(key -> new HashMap<>()); } public Optional processStopEstimate(InternalMessages.StopEstimate stopEstimate) { @@ -73,8 +65,7 @@ public Optional processStopEstimate(InternalMessages.StopEstimate st //We want to act only if the status is still scheduled, let's not send estimates on cancelled trips. return Optional.of(tripUpdate); - } - else { + } else { log.debug("Discarding cancelled stop estimate"); return Optional.empty(); } @@ -86,7 +77,8 @@ public Optional processStopEstimate(InternalMessages.StopEstimate st } - public TripUpdate processTripCancellation(final String messageKey, long messageTimestamp, InternalMessages.TripCancellation tripCancellation) { + public TripUpdate processTripCancellation(final String messageKey, long messageTimestamp, + InternalMessages.TripCancellation tripCancellation) { return updateTripUpdateCacheWithCancellation(messageKey, messageTimestamp, tripCancellation); } @@ -122,7 +114,8 @@ LinkedList getStopTimeUpdates(String key) { return new LinkedList<>(updates); } - private TripUpdate updateTripUpdateCacheWithStopTimes(final InternalMessages.StopEstimate latest, Collection stopTimeUpdates) { + private TripUpdate updateTripUpdateCacheWithStopTimes(final InternalMessages.StopEstimate latest, + Collection stopTimeUpdates) { final String tuCacheKey = cacheKey(latest); TripUpdate previousTripUpdate = tripUpdateCache.getIfPresent(tuCacheKey); @@ -131,40 +124,37 @@ private TripUpdate updateTripUpdateCacheWithStopTimes(final InternalMessages.Sto } final long timestamp = GtfsRtFactory.lastModified(latest); - TripUpdate tripUpdate = previousTripUpdate.toBuilder() - .clearStopTimeUpdate() - .addAllStopTimeUpdate(stopTimeUpdates) - .setTimestamp(timestamp) - .build(); - + TripUpdate tripUpdate = previousTripUpdate.toBuilder().clearStopTimeUpdate() + .addAllStopTimeUpdate(stopTimeUpdates).setTimestamp(timestamp).build(); + if (StringUtils.isNotBlank(latest.getTargetedStopId()) && !latest.getTargetedStopId().equals(latest.getStopId())) { tripUpdate = processTargetedStopIds(tripUpdate, latest); } - + tripUpdateCache.put(tuCacheKey, tripUpdate); return tripUpdate; } - + private TripUpdate processTargetedStopIds(TripUpdate tripUpdate, InternalMessages.StopEstimate stopEstimate) { - log.info("TargetedStopId has changed. TimetabledStopId={}, TargetedStopId={}, RouteId={}, DirectionId={}, Type={}, OperationDay={}, StartTime={}", + log.info( + "TargetedStopId has changed. TimetabledStopId={}, TargetedStopId={}, RouteId={}, DirectionId={}, Type={}, OperationDay={}, StartTime={}", stopEstimate.getStopId(), stopEstimate.getTargetedStopId(), stopEstimate.getTripInfo().getRouteId(), - stopEstimate.getTripInfo().getDirectionId(), stopEstimate.getType(), stopEstimate.getTripInfo().getOperatingDay(), - stopEstimate.getTripInfo().getStartTime()); - + stopEstimate.getTripInfo().getDirectionId(), stopEstimate.getType(), + stopEstimate.getTripInfo().getOperatingDay(), stopEstimate.getTripInfo().getStartTime()); + StopTimeProperties stopTimeProperties = GtfsRealtime.TripUpdate.StopTimeProperties.newBuilder() - .setAssignedStopId(stopEstimate.getTargetedStopId()) - .build(); - + .setAssignedStopId(stopEstimate.getTargetedStopId()).build(); + StopTimeUpdate.Builder stopTimeUpdate = GtfsRealtime.TripUpdate.StopTimeUpdate.newBuilder() .setStopSequence(stopEstimate.getStopSequence()) .setScheduleRelationship(GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.SCHEDULED) .setStopTimeProperties(stopTimeProperties); - + int stopTimeUpdateToBeRemovedIndex = -1; - - for (int i=0; i new HashMap<>()).compute(cancellation.getDeviationCaseId(), (deviationCaseId, tripCancellations) -> { - if (tripCancellations == null) { - tripCancellations = new HashMap<>(); - } - tripCancellations.put(cancellation.getStatus(), cancellation); + private TripUpdate updateTripUpdateCacheWithCancellation(final String cacheKey, final long messageTimestampMs, + InternalMessages.TripCancellation cancellation) { + cancellationsCache.get(cacheKey, k -> new HashMap<>()).compute(cancellation.getDeviationCaseId(), + (deviationCaseId, tripCancellations) -> { + if (tripCancellations == null) { + tripCancellations = new HashMap<>(); + } + + tripCancellations.put(cancellation.getStatus(), cancellation); + + return tripCancellations; + }); + final Map> cancellations = cancellationsCache + .getIfPresent(cacheKey); + + boolean isCancelled = cancellation.getStatus() == InternalMessages.TripCancellation.Status.CANCELED + ? true + : false; - return tripCancellations; - }); - final Map> cancellations = cancellationsCache.getIfPresent(cacheKey); - - boolean isCancelled = cancellation.getStatus() == InternalMessages.TripCancellation.Status.CANCELED ? true : false; - if (cancellation.getDeviationCaseId() > 0) { isCancelled = cancellations.values().stream().anyMatch(cancellationsForDeviationCase -> { final Set statuses = cancellationsForDeviationCase.keySet(); - return statuses.stream().filter(status -> status == InternalMessages.TripCancellation.Status.CANCELED).count() > statuses.stream().filter(status -> status != InternalMessages.TripCancellation.Status.CANCELED).count(); + return statuses.stream().filter(status -> status == InternalMessages.TripCancellation.Status.CANCELED) + .count() > statuses.stream() + .filter(status -> status != InternalMessages.TripCancellation.Status.CANCELED).count(); }); } @@ -216,19 +210,20 @@ private TripUpdate updateTripUpdateCacheWithCancellation(final String cacheKey, } //Assume that trip is scheduled if its schedule relationship is not found from the cache - final GtfsRealtime.TripDescriptor.ScheduleRelationship status = isCancelled ? GtfsRealtime.TripDescriptor.ScheduleRelationship.CANCELED : Optional.ofNullable(scheduleRelationshipCache.getIfPresent(cacheKey)).orElse(TripDescriptor.ScheduleRelationship.SCHEDULED); + final GtfsRealtime.TripDescriptor.ScheduleRelationship status = isCancelled + ? GtfsRealtime.TripDescriptor.ScheduleRelationship.CANCELED + : Optional.ofNullable(scheduleRelationshipCache.getIfPresent(cacheKey)) + .orElse(TripDescriptor.ScheduleRelationship.SCHEDULED); - TripDescriptor tripDescriptor = previousTripUpdate.getTrip().toBuilder() - .setScheduleRelationship(status) + TripDescriptor tripDescriptor = previousTripUpdate.getTrip().toBuilder().setScheduleRelationship(status) .build(); - TripUpdate.Builder builder = previousTripUpdate.toBuilder() - .setTrip(tripDescriptor) + TripUpdate.Builder builder = previousTripUpdate.toBuilder().setTrip(tripDescriptor) .setTimestamp(TimeUnit.SECONDS.convert(messageTimestampMs, TimeUnit.MILLISECONDS)) .clearStopTimeUpdate(); - - if (status == TripDescriptor.ScheduleRelationship.SCHEDULED || status == TripDescriptor.ScheduleRelationship.ADDED) { + if (status == TripDescriptor.ScheduleRelationship.SCHEDULED + || status == TripDescriptor.ScheduleRelationship.ADDED) { // We need to re-attach all the StopTimeUpdates to the payload List stopTimeUpdates = getStopTimeUpdates(cacheKey); @@ -237,7 +232,8 @@ private TripUpdate updateTripUpdateCacheWithCancellation(final String cacheKey, if (validated.isEmpty()) { // This is probably cancellation of cancellation (CANCELED -> SCHEDULED/ADDED) as no stop time updates were available // Gtfs-rt standard requires SCHEDULED (OR ADDED) trip update to contain at least one stop time update, thus let's add one - GtfsRealtime.TripUpdate.StopTimeUpdate.Builder stopTimeUpdateBuilder = GtfsRealtime.TripUpdate.StopTimeUpdate.newBuilder(); + GtfsRealtime.TripUpdate.StopTimeUpdate.Builder stopTimeUpdateBuilder = GtfsRealtime.TripUpdate.StopTimeUpdate + .newBuilder(); stopTimeUpdateBuilder.setStopSequence(1); stopTimeUpdateBuilder.setScheduleRelationship(StopTimeUpdate.ScheduleRelationship.NO_DATA); builder.addStopTimeUpdate(stopTimeUpdateBuilder.build()); diff --git a/src/main/java/fi/hsl/transitdata/tripupdate/validators/MissingEstimatesValidator.java b/src/main/java/fi/hsl/transitdata/tripupdate/validators/MissingEstimatesValidator.java index 13e8fa8..f6ce52c 100644 --- a/src/main/java/fi/hsl/transitdata/tripupdate/validators/MissingEstimatesValidator.java +++ b/src/main/java/fi/hsl/transitdata/tripupdate/validators/MissingEstimatesValidator.java @@ -17,9 +17,7 @@ public boolean validate(GtfsRealtime.TripUpdate tripUpdate) { for (GtfsRealtime.TripUpdate.StopTimeUpdate stopTimeUpdate : tripUpdate.getStopTimeUpdateList()) { if (previous != null) { - if (previous.hasDeparture() - && previous.getDeparture().hasTime() - && stopTimeUpdate.hasArrival() + if (previous.hasDeparture() && previous.getDeparture().hasTime() && stopTimeUpdate.hasArrival() && stopTimeUpdate.getArrival().hasTime() && previous.getDeparture().getTime() == stopTimeUpdate.getArrival().getTime()) { sameEstimate++; diff --git a/src/main/java/fi/hsl/transitdata/tripupdate/validators/PrematureDeparturesValidator.java b/src/main/java/fi/hsl/transitdata/tripupdate/validators/PrematureDeparturesValidator.java index 85bc4bb..30dac3b 100644 --- a/src/main/java/fi/hsl/transitdata/tripupdate/validators/PrematureDeparturesValidator.java +++ b/src/main/java/fi/hsl/transitdata/tripupdate/validators/PrematureDeparturesValidator.java @@ -24,8 +24,8 @@ public PrematureDeparturesValidator(long tripUpdateMinTimeBeforeDeparture, Strin public boolean validate(GtfsRealtime.TripUpdate tripUpdate) { //If a TripUpdate has no StopTimeUpdates, it is most likely represents a trip that has been cancelled //Current hypothesis is that these messages should always be relevant and thus routed through - boolean isCancellation = tripUpdate.getTrip().hasScheduleRelationship() && - tripUpdate.getTrip().getScheduleRelationship() == GtfsRealtime.TripDescriptor.ScheduleRelationship.CANCELED; + boolean isCancellation = tripUpdate.getTrip().hasScheduleRelationship() && tripUpdate.getTrip() + .getScheduleRelationship() == GtfsRealtime.TripDescriptor.ScheduleRelationship.CANCELED; if (isCancellation || tripUpdate.getStopTimeUpdateList().isEmpty()) { return true; @@ -38,8 +38,10 @@ public boolean validate(GtfsRealtime.TripUpdate tripUpdate) { return false; } - Optional firstStopTimeUpdate = tripUpdate.getStopTimeUpdateList().stream() - .filter(stu -> stu.getScheduleRelationship() != GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.NO_DATA) + Optional firstStopTimeUpdate = tripUpdate.getStopTimeUpdateList() + .stream() + .filter(stu -> stu + .getScheduleRelationship() != GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.NO_DATA) .findFirst(); //If stop time update is not present, all stop updates are NO_DATA -> trip update is valid @@ -47,7 +49,9 @@ public boolean validate(GtfsRealtime.TripUpdate tripUpdate) { return true; } - long firstStopTime = firstStopTimeUpdate.get().hasDeparture() ? firstStopTimeUpdate.get().getDeparture().getTime() : firstStopTimeUpdate.get().getArrival().getTime(); + long firstStopTime = firstStopTimeUpdate.get().hasDeparture() + ? firstStopTimeUpdate.get().getDeparture().getTime() + : firstStopTimeUpdate.get().getArrival().getTime(); long tripStartTimePosix = tripStartTimeToPosixTime(tripUpdate); //Filter out premature departures, where the departure time for the first StopTimeUpdate is more than the @@ -76,18 +80,20 @@ long tripStartTimeToPosixTime(GtfsRealtime.TripUpdate tripUpdate) { } else { hoursString = "0" + hours; } - tripStartTimeLocal = LocalTime.parse(hoursString + ":" + tripStartTimeArray[1] + ":" + tripStartTimeArray[2]); + tripStartTimeLocal = LocalTime + .parse(hoursString + ":" + tripStartTimeArray[1] + ":" + tripStartTimeArray[2]); } - LocalDate tripStartDateLocal = LocalDate.parse(tripUpdate.getTrip().getStartDate(), DateTimeFormatter.BASIC_ISO_DATE); + LocalDate tripStartDateLocal = LocalDate.parse(tripUpdate.getTrip().getStartDate(), + DateTimeFormatter.BASIC_ISO_DATE); if (over24Hours) { tripStartDateLocal = tripStartDateLocal.plusDays(1); } - long tripStartTimeEpoch = LocalDateTime.of(tripStartDateLocal, tripStartTimeLocal).atZone(zoneId).toInstant().getEpochSecond(); + long tripStartTimeEpoch = LocalDateTime.of(tripStartDateLocal, tripStartTimeLocal).atZone(zoneId).toInstant() + .getEpochSecond(); return tripStartTimeEpoch; } } - diff --git a/src/main/java/fi/hsl/transitdata/tripupdate/validators/TripUpdateMaxAgeValidator.java b/src/main/java/fi/hsl/transitdata/tripupdate/validators/TripUpdateMaxAgeValidator.java index 020e0e5..46283ed 100644 --- a/src/main/java/fi/hsl/transitdata/tripupdate/validators/TripUpdateMaxAgeValidator.java +++ b/src/main/java/fi/hsl/transitdata/tripupdate/validators/TripUpdateMaxAgeValidator.java @@ -22,19 +22,18 @@ boolean validateWithCurrentTime(GtfsRealtime.TripUpdate tripUpdate, long current //If a TripUpdate has no StopTimeUpdates, it is most likely represents a trip that has been cancelled //Current hypothesis is that these messages should always be relevant and thus routed through - boolean isCancellation = tripUpdate.getTrip().hasScheduleRelationship() && - tripUpdate.getTrip().getScheduleRelationship() == GtfsRealtime.TripDescriptor.ScheduleRelationship.CANCELED; + boolean isCancellation = tripUpdate.getTrip().hasScheduleRelationship() && tripUpdate.getTrip() + .getScheduleRelationship() == GtfsRealtime.TripDescriptor.ScheduleRelationship.CANCELED; if (isCancellation || tripUpdate.getStopTimeUpdateList().isEmpty()) { return true; } - OptionalLong maxStopTimeEventTime = tripUpdate.getStopTimeUpdateList().stream() - .flatMap(stu -> stu.getScheduleRelationship() == GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.NO_DATA ? - Stream.empty() : - Stream.of(stu.getArrival(), stu.getDeparture())) - .mapToLong(GtfsRealtime.TripUpdate.StopTimeEvent::getTime) - .max(); + OptionalLong maxStopTimeEventTime = tripUpdate.getStopTimeUpdateList().stream().flatMap(stu -> stu + .getScheduleRelationship() == GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.NO_DATA + ? Stream.empty() + : Stream.of(stu.getArrival(), stu.getDeparture())) + .mapToLong(GtfsRealtime.TripUpdate.StopTimeEvent::getTime).max(); //If maximum stop event time is not present, all stop updates are NO_DATA -> trip update is valid if (!maxStopTimeEventTime.isPresent()) { diff --git a/src/test/java/fi/hsl/transitdata/tripupdate/MockDataFactory.java b/src/test/java/fi/hsl/transitdata/tripupdate/MockDataFactory.java index 6ccf4fe..8c4ca07 100644 --- a/src/test/java/fi/hsl/transitdata/tripupdate/MockDataFactory.java +++ b/src/test/java/fi/hsl/transitdata/tripupdate/MockDataFactory.java @@ -7,7 +7,8 @@ public class MockDataFactory { - public static GtfsRealtime.TripUpdate.StopTimeEvent mockStopTimeEvent(InternalMessages.StopEstimate.Type eventType, long startTimeEpoch) throws Exception { + public static GtfsRealtime.TripUpdate.StopTimeEvent mockStopTimeEvent(InternalMessages.StopEstimate.Type eventType, + long startTimeEpoch) throws Exception { GtfsRealtime.TripUpdate.StopTimeUpdate update = mockStopTimeUpdate(eventType, startTimeEpoch); if (eventType == InternalMessages.StopEstimate.Type.ARRIVAL) return update.getArrival(); @@ -15,13 +16,14 @@ public static GtfsRealtime.TripUpdate.StopTimeEvent mockStopTimeEvent(InternalMe return update.getDeparture(); } - - public static GtfsRealtime.TripUpdate.StopTimeUpdate mockStopTimeUpdate(InternalMessages.StopEstimate.Type eventType, long startTimeEpoch) throws Exception { + public static GtfsRealtime.TripUpdate.StopTimeUpdate mockStopTimeUpdate( + InternalMessages.StopEstimate.Type eventType, long startTimeEpoch) throws Exception { InternalMessages.StopEstimate estimate = MockDataUtils.mockStopEstimate(eventType, startTimeEpoch); return GtfsRtFactory.newStopTimeUpdate(estimate); } - public static GtfsRealtime.TripUpdate.StopTimeUpdate mockStopTimeUpdate(InternalMessages.StopEstimate arrival, InternalMessages.StopEstimate departure) { + public static GtfsRealtime.TripUpdate.StopTimeUpdate mockStopTimeUpdate(InternalMessages.StopEstimate arrival, + InternalMessages.StopEstimate departure) { GtfsRealtime.TripUpdate.StopTimeUpdate arrivalUpdate = GtfsRtFactory.newStopTimeUpdate(arrival); GtfsRealtime.TripUpdate.StopTimeUpdate departureUpdate = GtfsRtFactory.newStopTimeUpdate(departure); //Merge these two @@ -29,17 +31,16 @@ public static GtfsRealtime.TripUpdate.StopTimeUpdate mockStopTimeUpdate(Internal } public static GtfsRealtime.TripUpdate.StopTimeUpdate mockStopTimeUpdate(String stopId, long arrivalTime, - long departureTime) { + long departureTime) { GtfsRealtime.TripUpdate.StopTimeEvent arrival = GtfsRealtime.TripUpdate.StopTimeEvent.newBuilder() - .setTime(arrivalTime) - .build(); + .setTime(arrivalTime).build(); GtfsRealtime.TripUpdate.StopTimeEvent departure = GtfsRealtime.TripUpdate.StopTimeEvent.newBuilder() - .setTime(departureTime) - .build(); + .setTime(departureTime).build(); - GtfsRealtime.TripUpdate.StopTimeUpdate.Builder stopTimeUpdateBuilder = GtfsRealtime.TripUpdate.StopTimeUpdate.newBuilder(); + GtfsRealtime.TripUpdate.StopTimeUpdate.Builder stopTimeUpdateBuilder = GtfsRealtime.TripUpdate.StopTimeUpdate + .newBuilder(); if (arrivalTime != 0) { stopTimeUpdateBuilder.setArrival(arrival); @@ -51,19 +52,14 @@ public static GtfsRealtime.TripUpdate.StopTimeUpdate mockStopTimeUpdate(String s return stopTimeUpdateBuilder.setStopId(stopId).build(); } + public static GtfsRealtime.TripUpdate mockTripUpdate(String routeId, int directionId, String startDate, + String startTime, Iterable stopTimeUpdateList) { - public static GtfsRealtime.TripUpdate mockTripUpdate(String routeId, int directionId, - String startDate, String startTime, - Iterable stopTimeUpdateList) { - - GtfsRealtime.TripDescriptor tripDescriptor = GtfsRealtime.TripDescriptor.newBuilder() - .setRouteId(routeId) - .setDirectionId(directionId) - .setStartDate(startDate) - .setStartTime(startTime) - .build(); + GtfsRealtime.TripDescriptor tripDescriptor = GtfsRealtime.TripDescriptor.newBuilder().setRouteId(routeId) + .setDirectionId(directionId).setStartDate(startDate).setStartTime(startTime).build(); - GtfsRealtime.TripUpdate.Builder tripUpdateBuilder = GtfsRealtime.TripUpdate.newBuilder().setTrip(tripDescriptor); + GtfsRealtime.TripUpdate.Builder tripUpdateBuilder = GtfsRealtime.TripUpdate.newBuilder() + .setTrip(tripDescriptor); if (stopTimeUpdateList != null) { tripUpdateBuilder.addAllStopTimeUpdate(stopTimeUpdateList); @@ -72,7 +68,8 @@ public static GtfsRealtime.TripUpdate mockTripUpdate(String routeId, int directi return tripUpdateBuilder.build(); } - public static GtfsRealtime.TripUpdate mockTripUpdate(String routeId, int directionId, String startDate, String startTime) { + public static GtfsRealtime.TripUpdate mockTripUpdate(String routeId, int directionId, String startDate, + String startTime) { return mockTripUpdate(routeId, directionId, startDate, startTime, null); } } diff --git a/src/test/java/fi/hsl/transitdata/tripupdate/gtfsrt/GtfsRtValidatorTest.java b/src/test/java/fi/hsl/transitdata/tripupdate/gtfsrt/GtfsRtValidatorTest.java index 088b761..c30558e 100644 --- a/src/test/java/fi/hsl/transitdata/tripupdate/gtfsrt/GtfsRtValidatorTest.java +++ b/src/test/java/fi/hsl/transitdata/tripupdate/gtfsrt/GtfsRtValidatorTest.java @@ -19,13 +19,12 @@ import static org.junit.Assert.assertFalse; public class GtfsRtValidatorTest { - final static long[] SRC_ARRIVALS_MS = new long[] { 1545674400000L, 1545674500000L, 1545674600000L }; - final static long[] SRC_DEPARTURES_MS = new long[] { 1545674450000L, 1545674550000L, 1545674650000L }; + final static long[] SRC_ARRIVALS_MS = new long[]{1545674400000L, 1545674500000L, 1545674600000L}; + final static long[] SRC_DEPARTURES_MS = new long[]{1545674450000L, 1545674550000L, 1545674650000L}; final static long[] DST_ARRIVALS = Arrays.stream(SRC_ARRIVALS_MS).map(ms -> ms / 1000).toArray(); final static long[] DST_DEPARTURES = Arrays.stream(SRC_DEPARTURES_MS).map(ms -> ms / 1000).toArray(); - final static long DVI_ID = 1234567890L; final static long JPP_ID = 9876543210L; @@ -33,7 +32,8 @@ public class GtfsRtValidatorTest { public void testValidateTime() throws Exception { long epoch = SRC_ARRIVALS_MS[1]; - final Optional stopTimeEvent = Optional.of(MockDataFactory.mockStopTimeEvent(InternalMessages.StopEstimate.Type.ARRIVAL, epoch)); + final Optional stopTimeEvent = Optional + .of(MockDataFactory.mockStopTimeEvent(InternalMessages.StopEstimate.Type.ARRIVAL, epoch)); Optional laterMinTime = Optional.of(DST_ARRIVALS[2]); Optional shouldBeChanged = GtfsRtValidator.validateMinTime(stopTimeEvent, laterMinTime); @@ -53,7 +53,8 @@ public void testValidateTime() throws Exception { assertTrue(stopTimeEvent.get().getTime() == shouldBeOriginal.get().getTime()); //If event is empty we should get nothing - Optional nothing = GtfsRtValidator.validateMinTime(Optional.empty(), Optional.of(DST_ARRIVALS[0])); + Optional nothing = GtfsRtValidator.validateMinTime(Optional.empty(), + Optional.of(DST_ARRIVALS[0])); assertTrue(!nothing.isPresent()); Optional stillNothing = GtfsRtValidator.validateMinTime(Optional.empty(), Optional.empty()); assertTrue(!stillNothing.isPresent()); @@ -61,8 +62,10 @@ public void testValidateTime() throws Exception { @Test public void testValidateTimestampsOnlyArrival() throws Exception { - final StopTimeUpdate firstArrival = MockDataFactory.mockStopTimeUpdate(InternalMessages.StopEstimate.Type.ARRIVAL, SRC_ARRIVALS_MS[0]); - final StopTimeUpdate secondArrival = MockDataFactory.mockStopTimeUpdate(InternalMessages.StopEstimate.Type.ARRIVAL, SRC_ARRIVALS_MS[1]); + final StopTimeUpdate firstArrival = MockDataFactory + .mockStopTimeUpdate(InternalMessages.StopEstimate.Type.ARRIVAL, SRC_ARRIVALS_MS[0]); + final StopTimeUpdate secondArrival = MockDataFactory + .mockStopTimeUpdate(InternalMessages.StopEstimate.Type.ARRIVAL, SRC_ARRIVALS_MS[1]); validateTimestamps(firstArrival, secondArrival, GtfsRtValidator.OnConflict.ArrivalWins, DST_ARRIVALS[1], 0); validateTimestamps(secondArrival, firstArrival, GtfsRtValidator.OnConflict.ArrivalWins, DST_ARRIVALS[1], 0); @@ -86,8 +89,8 @@ public void testValidateTimestampsBothArrivalAndDeparture() throws Exception { } - - void validateTimestamps(StopTimeUpdate prev, StopTimeUpdate cur, GtfsRtValidator.OnConflict onConflict, long expectedArrival, long expectedDeparture) { + void validateTimestamps(StopTimeUpdate prev, StopTimeUpdate cur, GtfsRtValidator.OnConflict onConflict, + long expectedArrival, long expectedDeparture) { StopTimeUpdate validated = GtfsRtValidator.validateTimestamps(prev, cur, onConflict); assertTrue(validated.hasArrival() == cur.hasArrival()); @@ -126,15 +129,15 @@ public void testArrivalAndDepartureSequences() throws Exception { StopTimeUpdate updatedFirst = updated.get(0); assertEquals(DST_ARRIVALS[1], updatedFirst.getArrival().getTime()); - assertEquals(DST_DEPARTURES[1], updatedFirst.getDeparture().getTime() ); + assertEquals(DST_DEPARTURES[1], updatedFirst.getDeparture().getTime()); StopTimeUpdate updatedSecond = updated.get(1); assertEquals(DST_DEPARTURES[1], updatedSecond.getArrival().getTime()); - assertEquals(DST_DEPARTURES[1], updatedSecond.getDeparture().getTime() ); + assertEquals(DST_DEPARTURES[1], updatedSecond.getDeparture().getTime()); StopTimeUpdate updatedThird = updated.get(2); assertEquals(DST_ARRIVALS[2], updatedThird.getArrival().getTime()); - assertEquals(DST_DEPARTURES[2], updatedThird.getDeparture().getTime() ); + assertEquals(DST_DEPARTURES[2], updatedThird.getDeparture().getTime()); } { //Swap timestamps between first and last timestamp. all previous should be raised to the last departure @@ -147,15 +150,15 @@ public void testArrivalAndDepartureSequences() throws Exception { StopTimeUpdate updatedFirst = updated.get(0); assertEquals(DST_ARRIVALS[2], updatedFirst.getArrival().getTime()); - assertEquals(DST_DEPARTURES[2], updatedFirst.getDeparture().getTime() ); + assertEquals(DST_DEPARTURES[2], updatedFirst.getDeparture().getTime()); StopTimeUpdate updatedSecond = updated.get(1); assertEquals(DST_DEPARTURES[2], updatedSecond.getArrival().getTime()); - assertEquals(DST_DEPARTURES[2], updatedSecond.getDeparture().getTime() ); + assertEquals(DST_DEPARTURES[2], updatedSecond.getDeparture().getTime()); StopTimeUpdate updatedThird = updated.get(2); assertEquals(DST_DEPARTURES[2], updatedThird.getArrival().getTime()); - assertEquals(DST_DEPARTURES[2], updatedThird.getDeparture().getTime() ); + assertEquals(DST_DEPARTURES[2], updatedThird.getDeparture().getTime()); } { // First departure to delay after second arrival so second arrival needs to be moved @@ -170,15 +173,15 @@ public void testArrivalAndDepartureSequences() throws Exception { StopTimeUpdate updatedFirst = updated.get(0); assertEquals(DST_ARRIVALS[0], updatedFirst.getArrival().getTime()); - assertEquals(newDeparturesSecs[0], updatedFirst.getDeparture().getTime() ); + assertEquals(newDeparturesSecs[0], updatedFirst.getDeparture().getTime()); StopTimeUpdate updatedSecond = updated.get(1); assertEquals(newDeparturesSecs[0], updatedSecond.getArrival().getTime()); - assertEquals(newDeparturesSecs[1], updatedSecond.getDeparture().getTime() ); + assertEquals(newDeparturesSecs[1], updatedSecond.getDeparture().getTime()); StopTimeUpdate updatedThird = updated.get(2); assertEquals(DST_ARRIVALS[2], updatedThird.getArrival().getTime()); - assertEquals(newDeparturesSecs[2], updatedThird.getDeparture().getTime() ); + assertEquals(newDeparturesSecs[2], updatedThird.getDeparture().getTime()); } } @@ -207,9 +210,12 @@ public void testStopSequences() throws Exception { List updates = new LinkedList<>(); for (int stopSequence = 1; stopSequence < 100; stopSequence++) { //Let's switch types to make sure both work - InternalMessages.StopEstimate.Type type = stopSequence % 2 == 0 ? InternalMessages.StopEstimate.Type.ARRIVAL : InternalMessages.StopEstimate.Type.DEPARTURE; + InternalMessages.StopEstimate.Type type = stopSequence % 2 == 0 + ? InternalMessages.StopEstimate.Type.ARRIVAL + : InternalMessages.StopEstimate.Type.DEPARTURE; long targetTime = startTime++; //Let's modify this a bit - InternalMessages.StopEstimate event = MockDataUtils.mockStopEstimate(DVI_ID, type, 0L, stopSequence, targetTime); //MockDataFactory.mockStopEvent(MockDataUtils.generateValidCommon(DVI_ID, stopSequence).build(), null, type); + InternalMessages.StopEstimate event = MockDataUtils.mockStopEstimate(DVI_ID, type, 0L, stopSequence, + targetTime); //MockDataFactory.mockStopEvent(MockDataUtils.generateValidCommon(DVI_ID, stopSequence).build(), null, type); StopTimeUpdate update = GtfsRtFactory.newStopTimeUpdate(event); updates.add(update); } @@ -235,8 +241,7 @@ private void checkStopSequences(List stopSeqRemoved) { assertTrue(update.hasArrival() | update.hasDeparture()); if (update.hasArrival()) { assertTrue(update.getArrival().hasTime()); - } - else if (update.hasDeparture()) { + } else if (update.hasDeparture()) { assertTrue(update.getDeparture().hasTime()); } }); @@ -264,8 +269,8 @@ public void testArrivalAndDepartureFilling() throws Exception { LinkedList onlyDepartures = new LinkedList<>(); for (int n = 0; n < SRC_DEPARTURES_MS.length; n++) { - final GtfsRealtime.TripUpdate.StopTimeUpdate update = MockDataFactory.mockStopTimeUpdate( - InternalMessages.StopEstimate.Type.DEPARTURE, SRC_DEPARTURES_MS[n]); + final GtfsRealtime.TripUpdate.StopTimeUpdate update = MockDataFactory + .mockStopTimeUpdate(InternalMessages.StopEstimate.Type.DEPARTURE, SRC_DEPARTURES_MS[n]); onlyDepartures.add(update); } List filledArrivals = GtfsRtValidator.fillMissingArrivalsAndDepartures(onlyDepartures); @@ -273,8 +278,8 @@ public void testArrivalAndDepartureFilling() throws Exception { LinkedList onlyArrivals = new LinkedList<>(); for (int n = 0; n < SRC_ARRIVALS_MS.length; n++) { - final GtfsRealtime.TripUpdate.StopTimeUpdate update = MockDataFactory.mockStopTimeUpdate( - InternalMessages.StopEstimate.Type.ARRIVAL, SRC_ARRIVALS_MS[n]); + final GtfsRealtime.TripUpdate.StopTimeUpdate update = MockDataFactory + .mockStopTimeUpdate(InternalMessages.StopEstimate.Type.ARRIVAL, SRC_ARRIVALS_MS[n]); onlyArrivals.add(update); } List filledDepartures = GtfsRtValidator.fillMissingArrivalsAndDepartures(onlyArrivals); @@ -284,34 +289,25 @@ public void testArrivalAndDepartureFilling() throws Exception { @Test public void testRemoveEstimatesFromNoData() { List stopTimeUpdates = Arrays.asList( - StopTimeUpdate.newBuilder() - .setScheduleRelationship(StopTimeUpdate.ScheduleRelationship.NO_DATA) - .setArrival(StopTimeEvent.newBuilder() - .setTime(0) - .build()) - .setDeparture(StopTimeEvent.newBuilder() - .setTime(0) - .build()) - .build(), - StopTimeUpdate.newBuilder() - .setScheduleRelationship(StopTimeUpdate.ScheduleRelationship.SCHEDULED) - .setArrival(StopTimeEvent.newBuilder() - .setTime(0) - .build()) - .setDeparture(StopTimeEvent.newBuilder() - .setTime(0) - .build()) - .build()); + StopTimeUpdate.newBuilder().setScheduleRelationship(StopTimeUpdate.ScheduleRelationship.NO_DATA) + .setArrival(StopTimeEvent.newBuilder().setTime(0).build()) + .setDeparture(StopTimeEvent.newBuilder().setTime(0).build()).build(), + StopTimeUpdate.newBuilder().setScheduleRelationship(StopTimeUpdate.ScheduleRelationship.SCHEDULED) + .setArrival(StopTimeEvent.newBuilder().setTime(0).build()) + .setDeparture(StopTimeEvent.newBuilder().setTime(0).build()).build()); List fixed = GtfsRtValidator.removeEstimatesFromNoDataUpdates(stopTimeUpdates); - Optional noData = fixed.stream().filter(stu -> stu.getScheduleRelationship() == StopTimeUpdate.ScheduleRelationship.NO_DATA).findAny(); + Optional noData = fixed.stream() + .filter(stu -> stu.getScheduleRelationship() == StopTimeUpdate.ScheduleRelationship.NO_DATA).findAny(); assertTrue(noData.isPresent()); assertFalse(noData.get().hasArrival()); assertFalse(noData.get().hasDeparture()); - Optional scheduled = fixed.stream().filter(stu -> stu.getScheduleRelationship() == StopTimeUpdate.ScheduleRelationship.SCHEDULED).findAny(); + Optional scheduled = fixed.stream() + .filter(stu -> stu.getScheduleRelationship() == StopTimeUpdate.ScheduleRelationship.SCHEDULED) + .findAny(); assertTrue(scheduled.isPresent()); assertTrue(scheduled.get().hasArrival()); diff --git a/src/test/java/fi/hsl/transitdata/tripupdate/processing/StopEstimateProcessorTest.java b/src/test/java/fi/hsl/transitdata/tripupdate/processing/StopEstimateProcessorTest.java index a549846..1bd142b 100644 --- a/src/test/java/fi/hsl/transitdata/tripupdate/processing/StopEstimateProcessorTest.java +++ b/src/test/java/fi/hsl/transitdata/tripupdate/processing/StopEstimateProcessorTest.java @@ -14,27 +14,29 @@ public class StopEstimateProcessorTest { @Test public void messageWithWrongPayloadIsDiscarded() throws Exception { PubtransTableProtos.ROIArrival arrival = MockDataUtils.mockROIArrival(MockDataUtils.generateValidJoreId(), - MockDataUtils.generateValidRouteName(), - System.currentTimeMillis()); + MockDataUtils.generateValidRouteName(), System.currentTimeMillis()); StopEstimateProcessor proc = new StopEstimateProcessor(null, true); assertFalse(proc.validateMessage(arrival.toByteArray())); } - @Test public void messageWithValidPayloadIsAccepted() throws Exception { final boolean shouldPass = true; final String routeName = "1014"; - testValidationForStopEstimate(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, InternalMessages.StopEstimate.Type.ARRIVAL); - testValidationForStopEstimate(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, InternalMessages.StopEstimate.Type.DEPARTURE); - testValidationForStopEstimate(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, InternalMessages.StopEstimate.Type.ARRIVAL); - testValidationForStopEstimate(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, InternalMessages.StopEstimate.Type.DEPARTURE); + testValidationForStopEstimate(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, + InternalMessages.StopEstimate.Type.ARRIVAL); + testValidationForStopEstimate(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, + InternalMessages.StopEstimate.Type.DEPARTURE); + testValidationForStopEstimate(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, + InternalMessages.StopEstimate.Type.ARRIVAL); + testValidationForStopEstimate(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, + InternalMessages.StopEstimate.Type.DEPARTURE); } - - private void testValidationForStopEstimate(boolean shouldPass, String routeName, int direction, InternalMessages.StopEstimate.Type eventType) throws Exception { + private void testValidationForStopEstimate(boolean shouldPass, String routeName, int direction, + InternalMessages.StopEstimate.Type eventType) throws Exception { long dvjId = MockDataUtils.generateValidJoreId(); PubtransTableProtos.Common common = MockDataUtils.mockCommon(dvjId).build(); PubtransTableProtos.DOITripInfo mockTripInfo = MockDataUtils.mockDOITripInfo(dvjId, routeName, direction); @@ -51,27 +53,33 @@ public void messageForTrainRouteKIsDiscarded() throws Exception { final boolean shouldPass = false; final String routeName = "3001K"; - testValidationForStopEstimate(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, InternalMessages.StopEstimate.Type.ARRIVAL); - testValidationForStopEstimate(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, InternalMessages.StopEstimate.Type.DEPARTURE); - testValidationForStopEstimate(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, InternalMessages.StopEstimate.Type.ARRIVAL); - testValidationForStopEstimate(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, InternalMessages.StopEstimate.Type.DEPARTURE); + testValidationForStopEstimate(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, + InternalMessages.StopEstimate.Type.ARRIVAL); + testValidationForStopEstimate(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, + InternalMessages.StopEstimate.Type.DEPARTURE); + testValidationForStopEstimate(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, + InternalMessages.StopEstimate.Type.ARRIVAL); + testValidationForStopEstimate(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, + InternalMessages.StopEstimate.Type.DEPARTURE); } - @Test public void messageForTrainRouteUIsDiscarded() throws Exception { final boolean shouldPass = false; final String routeName = "3002U"; - testValidationForStopEstimate(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, InternalMessages.StopEstimate.Type.ARRIVAL); - testValidationForStopEstimate(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, InternalMessages.StopEstimate.Type.DEPARTURE); - testValidationForStopEstimate(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, InternalMessages.StopEstimate.Type.ARRIVAL); - testValidationForStopEstimate(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, InternalMessages.StopEstimate.Type.DEPARTURE); + testValidationForStopEstimate(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, + InternalMessages.StopEstimate.Type.ARRIVAL); + testValidationForStopEstimate(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, + InternalMessages.StopEstimate.Type.DEPARTURE); + testValidationForStopEstimate(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, + InternalMessages.StopEstimate.Type.ARRIVAL); + testValidationForStopEstimate(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, + InternalMessages.StopEstimate.Type.DEPARTURE); } - @Test public void messageWithJoreDirectionShouldPassAndOthersBeDiscarded() throws Exception { @@ -81,11 +89,15 @@ public void messageWithJoreDirectionShouldPassAndOthersBeDiscarded() throws Exce testValidationForStopEstimate(false, routeName, gtfsRtDir, InternalMessages.StopEstimate.Type.ARRIVAL); testValidationForStopEstimate(false, routeName, gtfsRtDir, InternalMessages.StopEstimate.Type.DEPARTURE); - testValidationForStopEstimate(true, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, InternalMessages.StopEstimate.Type.ARRIVAL); - testValidationForStopEstimate(true, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, InternalMessages.StopEstimate.Type.DEPARTURE); + testValidationForStopEstimate(true, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, + InternalMessages.StopEstimate.Type.ARRIVAL); + testValidationForStopEstimate(true, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, + InternalMessages.StopEstimate.Type.DEPARTURE); - testValidationForStopEstimate(true, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, InternalMessages.StopEstimate.Type.ARRIVAL); - testValidationForStopEstimate(true, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, InternalMessages.StopEstimate.Type.DEPARTURE); + testValidationForStopEstimate(true, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, + InternalMessages.StopEstimate.Type.ARRIVAL); + testValidationForStopEstimate(true, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, + InternalMessages.StopEstimate.Type.DEPARTURE); final int tooLargeDir = 3; testValidationForStopEstimate(false, routeName, tooLargeDir, InternalMessages.StopEstimate.Type.ARRIVAL); diff --git a/src/test/java/fi/hsl/transitdata/tripupdate/processing/TripCancellationProcessorTest.java b/src/test/java/fi/hsl/transitdata/tripupdate/processing/TripCancellationProcessorTest.java index cac3fc0..4a62473 100644 --- a/src/test/java/fi/hsl/transitdata/tripupdate/processing/TripCancellationProcessorTest.java +++ b/src/test/java/fi/hsl/transitdata/tripupdate/processing/TripCancellationProcessorTest.java @@ -19,31 +19,35 @@ public class TripCancellationProcessorTest { @Test public void messageWithWrongPayloadIsDiscarded() throws Exception { PubtransTableProtos.ROIArrival arrival = MockDataUtils.mockROIArrival(MockDataUtils.generateValidJoreId(), - MockDataUtils.generateValidRouteName(), - System.currentTimeMillis()); + MockDataUtils.generateValidRouteName(), System.currentTimeMillis()); TripCancellationProcessor proc = new TripCancellationProcessor(null, true); assertFalse(proc.validateMessage(arrival.toByteArray())); } - @Test public void messageWithValidPayloadIsAccepted() throws Exception { final boolean shouldPass = true; final String routeName = "1014"; - testValidationForTripCancellation(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, InternalMessages.StopEstimate.Type.ARRIVAL); - testValidationForTripCancellation(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, InternalMessages.StopEstimate.Type.DEPARTURE); - testValidationForTripCancellation(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, InternalMessages.StopEstimate.Type.ARRIVAL); - testValidationForTripCancellation(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, InternalMessages.StopEstimate.Type.DEPARTURE); + testValidationForTripCancellation(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, + InternalMessages.StopEstimate.Type.ARRIVAL); + testValidationForTripCancellation(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, + InternalMessages.StopEstimate.Type.DEPARTURE); + testValidationForTripCancellation(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, + InternalMessages.StopEstimate.Type.ARRIVAL); + testValidationForTripCancellation(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, + InternalMessages.StopEstimate.Type.DEPARTURE); } - - private void testValidationForTripCancellation(boolean shouldPass, String routeName, int direction, InternalMessages.StopEstimate.Type eventType) throws Exception { + private void testValidationForTripCancellation(boolean shouldPass, String routeName, int direction, + InternalMessages.StopEstimate.Type eventType) throws Exception { long dvjId = MockDataUtils.generateValidJoreId(); - LocalDateTime someOperatingTime = Instant.now().plus(Duration.ofHours(5)).atOffset(ZoneOffset.UTC).toLocalDateTime(); - InternalMessages.TripCancellation cancellation = MockDataUtils.mockTripCancellation(dvjId, routeName, direction, someOperatingTime); + LocalDateTime someOperatingTime = Instant.now().plus(Duration.ofHours(5)).atOffset(ZoneOffset.UTC) + .toLocalDateTime(); + InternalMessages.TripCancellation cancellation = MockDataUtils.mockTripCancellation(dvjId, routeName, direction, + someOperatingTime); TripCancellationProcessor proc = new TripCancellationProcessor(null, true); @@ -56,27 +60,33 @@ public void messageForTrainRouteKIsDiscarded() throws Exception { final boolean shouldPass = false; final String routeName = "3001K"; - testValidationForTripCancellation(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, InternalMessages.StopEstimate.Type.ARRIVAL); - testValidationForTripCancellation(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, InternalMessages.StopEstimate.Type.DEPARTURE); - testValidationForTripCancellation(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, InternalMessages.StopEstimate.Type.ARRIVAL); - testValidationForTripCancellation(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, InternalMessages.StopEstimate.Type.DEPARTURE); + testValidationForTripCancellation(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, + InternalMessages.StopEstimate.Type.ARRIVAL); + testValidationForTripCancellation(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, + InternalMessages.StopEstimate.Type.DEPARTURE); + testValidationForTripCancellation(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, + InternalMessages.StopEstimate.Type.ARRIVAL); + testValidationForTripCancellation(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, + InternalMessages.StopEstimate.Type.DEPARTURE); } - @Test public void messageForTrainRouteUIsDiscarded() throws Exception { final boolean shouldPass = false; final String routeName = "3002U"; - testValidationForTripCancellation(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, InternalMessages.StopEstimate.Type.ARRIVAL); - testValidationForTripCancellation(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, InternalMessages.StopEstimate.Type.DEPARTURE); - testValidationForTripCancellation(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, InternalMessages.StopEstimate.Type.ARRIVAL); - testValidationForTripCancellation(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, InternalMessages.StopEstimate.Type.DEPARTURE); + testValidationForTripCancellation(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, + InternalMessages.StopEstimate.Type.ARRIVAL); + testValidationForTripCancellation(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, + InternalMessages.StopEstimate.Type.DEPARTURE); + testValidationForTripCancellation(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, + InternalMessages.StopEstimate.Type.ARRIVAL); + testValidationForTripCancellation(shouldPass, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, + InternalMessages.StopEstimate.Type.DEPARTURE); } - @Test public void messageWithJoreDirectionShouldPassAndOthersBeDiscarded() throws Exception { @@ -86,11 +96,15 @@ public void messageWithJoreDirectionShouldPassAndOthersBeDiscarded() throws Exce testValidationForTripCancellation(false, routeName, gtfsRtDir, InternalMessages.StopEstimate.Type.ARRIVAL); testValidationForTripCancellation(false, routeName, gtfsRtDir, InternalMessages.StopEstimate.Type.DEPARTURE); - testValidationForTripCancellation(true, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, InternalMessages.StopEstimate.Type.ARRIVAL); - testValidationForTripCancellation(true, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, InternalMessages.StopEstimate.Type.DEPARTURE); + testValidationForTripCancellation(true, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, + InternalMessages.StopEstimate.Type.ARRIVAL); + testValidationForTripCancellation(true, routeName, PubtransFactory.JORE_DIRECTION_ID_INBOUND, + InternalMessages.StopEstimate.Type.DEPARTURE); - testValidationForTripCancellation(true, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, InternalMessages.StopEstimate.Type.ARRIVAL); - testValidationForTripCancellation(true, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, InternalMessages.StopEstimate.Type.DEPARTURE); + testValidationForTripCancellation(true, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, + InternalMessages.StopEstimate.Type.ARRIVAL); + testValidationForTripCancellation(true, routeName, PubtransFactory.JORE_DIRECTION_ID_OUTBOUND, + InternalMessages.StopEstimate.Type.DEPARTURE); final int tooLargeDir = 3; testValidationForTripCancellation(false, routeName, tooLargeDir, InternalMessages.StopEstimate.Type.ARRIVAL); diff --git a/src/test/java/fi/hsl/transitdata/tripupdate/processing/TripUpdateProcessorTest.java b/src/test/java/fi/hsl/transitdata/tripupdate/processing/TripUpdateProcessorTest.java index e16f629..b39e3ae 100644 --- a/src/test/java/fi/hsl/transitdata/tripupdate/processing/TripUpdateProcessorTest.java +++ b/src/test/java/fi/hsl/transitdata/tripupdate/processing/TripUpdateProcessorTest.java @@ -44,7 +44,7 @@ public void testStopTimeUpdateCache() throws Exception { private void addStops(final long dvjId, final int amount, TripUpdateProcessor processor) throws Exception { int counter = 0; - while(counter < amount) { + while (counter < amount) { final int stopSequence = counter; final int stopId = stopSequence; // we can just use the same id here counter++; @@ -66,14 +66,15 @@ private void addStop(long dvjId, long stopId, int stopSequence, TripUpdateProces processor.updateStopTimeUpdateCache(estimate); } - private void validateStops(final long dvjId, final int correctAmount, TripUpdateProcessor processor) throws Exception { + private void validateStops(final long dvjId, final int correctAmount, TripUpdateProcessor processor) + throws Exception { final String cacheKey = Long.toString(dvjId); List updates = processor.getStopTimeUpdates(cacheKey); assertEquals(updates.size(), correctAmount); //Validate that stopIds and seqIds match and the sorting order is correct, by seqId int index = 0; - for (GtfsRealtime.TripUpdate.StopTimeUpdate update: updates) { + for (GtfsRealtime.TripUpdate.StopTimeUpdate update : updates) { assertEquals(Integer.toString(update.getStopSequence()), update.getStopId()); assertEquals(update.getStopSequence(), index); @@ -85,82 +86,51 @@ private void validateStops(final long dvjId, final int correctAmount, TripUpdate public void testCorrectScheduleTypeIsRestoredAfterCancellationOfCancellation() { TripUpdateProcessor processor = new TripUpdateProcessor(null); - InternalMessages.TripInfo tripInfo = InternalMessages.TripInfo.newBuilder() - .setTripId("trip_1") - .setDirectionId(1) - .setOperatingDay("20200101") - .setStartTime("00:00:00") - .setRouteId("2550") - .setScheduleType(InternalMessages.TripInfo.ScheduleType.ADDED) - .build(); - - Optional tripUpdate = processor.processStopEstimate(InternalMessages.StopEstimate.newBuilder() - .setSchemaVersion(1) - .setStopId("1") - .setStopSequence(1) - .setEstimatedTimeUtcMs(0) - .setScheduledTimeUtcMs(0) - .setLastModifiedUtcMs(0) - .setType(InternalMessages.StopEstimate.Type.ARRIVAL) - .setStatus(InternalMessages.StopEstimate.Status.SCHEDULED) - .setTripInfo(tripInfo) - .build()); + InternalMessages.TripInfo tripInfo = InternalMessages.TripInfo.newBuilder().setTripId("trip_1") + .setDirectionId(1).setOperatingDay("20200101").setStartTime("00:00:00").setRouteId("2550") + .setScheduleType(InternalMessages.TripInfo.ScheduleType.ADDED).build(); + + Optional tripUpdate = processor.processStopEstimate(InternalMessages.StopEstimate + .newBuilder().setSchemaVersion(1).setStopId("1").setStopSequence(1).setEstimatedTimeUtcMs(0) + .setScheduledTimeUtcMs(0).setLastModifiedUtcMs(0).setType(InternalMessages.StopEstimate.Type.ARRIVAL) + .setStatus(InternalMessages.StopEstimate.Status.SCHEDULED).setTripInfo(tripInfo).build()); assertTrue(tripUpdate.isPresent()); - assertEquals(GtfsRealtime.TripDescriptor.ScheduleRelationship.ADDED, tripUpdate.get().getTrip().getScheduleRelationship()); + assertEquals(GtfsRealtime.TripDescriptor.ScheduleRelationship.ADDED, + tripUpdate.get().getTrip().getScheduleRelationship()); // 'messageKey' is trip ID - GtfsRealtime.TripUpdate tripCancellation = processor.processTripCancellation("trip_1", 0, InternalMessages.TripCancellation.newBuilder() - .setSchemaVersion(1) - .setTripId("trip_1") - .setDirectionId(1) - .setRouteId("2550") - .setStartDate("20200101") - .setStartTime("00:00:00") - .setStatus(InternalMessages.TripCancellation.Status.CANCELED) - .build()); - - assertEquals(GtfsRealtime.TripDescriptor.ScheduleRelationship.CANCELED, tripCancellation.getTrip().getScheduleRelationship()); - - GtfsRealtime.TripUpdate cancellationOfCancellation = processor.processTripCancellation("trip_1", 0, InternalMessages.TripCancellation.newBuilder() - .setSchemaVersion(1) - .setTripId("trip_1") - .setDirectionId(1) - .setRouteId("2550") - .setStartDate("20200101") - .setStartTime("00:00:00") - .setStatus(InternalMessages.TripCancellation.Status.RUNNING) - .build()); - - assertEquals(GtfsRealtime.TripDescriptor.ScheduleRelationship.ADDED, cancellationOfCancellation.getTrip().getScheduleRelationship()); + GtfsRealtime.TripUpdate tripCancellation = processor.processTripCancellation("trip_1", 0, + InternalMessages.TripCancellation.newBuilder().setSchemaVersion(1).setTripId("trip_1").setDirectionId(1) + .setRouteId("2550").setStartDate("20200101").setStartTime("00:00:00") + .setStatus(InternalMessages.TripCancellation.Status.CANCELED).build()); + + assertEquals(GtfsRealtime.TripDescriptor.ScheduleRelationship.CANCELED, + tripCancellation.getTrip().getScheduleRelationship()); + + GtfsRealtime.TripUpdate cancellationOfCancellation = processor.processTripCancellation("trip_1", 0, + InternalMessages.TripCancellation.newBuilder().setSchemaVersion(1).setTripId("trip_1").setDirectionId(1) + .setRouteId("2550").setStartDate("20200101").setStartTime("00:00:00") + .setStatus(InternalMessages.TripCancellation.Status.RUNNING).build()); + + assertEquals(GtfsRealtime.TripDescriptor.ScheduleRelationship.ADDED, + cancellationOfCancellation.getTrip().getScheduleRelationship()); } - + @Test public void testAssignedStopIdIsSet() { TripUpdateProcessor processor = new TripUpdateProcessor(null); - - InternalMessages.TripInfo tripInfo = InternalMessages.TripInfo.newBuilder() - .setTripId("trip_1") - .setDirectionId(1) - .setOperatingDay("20240315") - .setStartTime("13:43:00") - .setRouteId("2015") - .setScheduleType(InternalMessages.TripInfo.ScheduleType.ADDED) - .build(); - - Optional tripUpdate = processor.processStopEstimate(InternalMessages.StopEstimate.newBuilder() - .setSchemaVersion(1) - .setStopId("1") - .setTargetedStopId("2") - .setStopSequence(1) - .setEstimatedTimeUtcMs(0) - .setScheduledTimeUtcMs(0) - .setLastModifiedUtcMs(0) - .setType(InternalMessages.StopEstimate.Type.DEPARTURE) - .setStatus(InternalMessages.StopEstimate.Status.SCHEDULED) - .setTripInfo(tripInfo) - .build()); - + + InternalMessages.TripInfo tripInfo = InternalMessages.TripInfo.newBuilder().setTripId("trip_1") + .setDirectionId(1).setOperatingDay("20240315").setStartTime("13:43:00").setRouteId("2015") + .setScheduleType(InternalMessages.TripInfo.ScheduleType.ADDED).build(); + + Optional tripUpdate = processor + .processStopEstimate(InternalMessages.StopEstimate.newBuilder().setSchemaVersion(1).setStopId("1") + .setTargetedStopId("2").setStopSequence(1).setEstimatedTimeUtcMs(0).setScheduledTimeUtcMs(0) + .setLastModifiedUtcMs(0).setType(InternalMessages.StopEstimate.Type.DEPARTURE) + .setStatus(InternalMessages.StopEstimate.Status.SCHEDULED).setTripInfo(tripInfo).build()); + assertTrue(tripUpdate.isPresent()); assertEquals(1, tripUpdate.get().getStopTimeUpdate(0).getStopSequence()); assertEquals("2", tripUpdate.get().getStopTimeUpdate(0).getStopTimeProperties().getAssignedStopId()); @@ -171,32 +141,24 @@ public void testCancellationOfCancellationWithoutPreviousStopTimeUpdates() { TripUpdateProcessor processor = new TripUpdateProcessor(null); // first, cancel a trip - GtfsRealtime.TripUpdate tripCancellation = processor.processTripCancellation("trip_1", 0, InternalMessages.TripCancellation.newBuilder() - .setSchemaVersion(1) - .setTripId("trip_1") - .setDirectionId(1) - .setRouteId("2550") - .setStartDate("20200101") - .setStartTime("00:00:00") - .setStatus(InternalMessages.TripCancellation.Status.CANCELED) - .build()); + GtfsRealtime.TripUpdate tripCancellation = processor.processTripCancellation("trip_1", 0, + InternalMessages.TripCancellation.newBuilder().setSchemaVersion(1).setTripId("trip_1").setDirectionId(1) + .setRouteId("2550").setStartDate("20200101").setStartTime("00:00:00") + .setStatus(InternalMessages.TripCancellation.Status.CANCELED).build()); // then, cancel the cancellation - GtfsRealtime.TripUpdate tu = processor.processTripCancellation("trip_1", 0, InternalMessages.TripCancellation.newBuilder() - .setSchemaVersion(1) - .setTripId("trip_1") - .setDirectionId(1) - .setRouteId("2550") - .setStartDate("20200101") - .setStartTime("00:00:00") - .setStatus(InternalMessages.TripCancellation.Status.RUNNING) - .build()); + GtfsRealtime.TripUpdate tu = processor.processTripCancellation("trip_1", 0, + InternalMessages.TripCancellation.newBuilder().setSchemaVersion(1).setTripId("trip_1").setDirectionId(1) + .setRouteId("2550").setStartDate("20200101").setStartTime("00:00:00") + .setStatus(InternalMessages.TripCancellation.Status.RUNNING).build()); // check that cancellation was cancelled - assertEquals(GtfsRealtime.TripDescriptor.ScheduleRelationship.SCHEDULED, tu.getTrip().getScheduleRelationship()); + assertEquals(GtfsRealtime.TripDescriptor.ScheduleRelationship.SCHEDULED, + tu.getTrip().getScheduleRelationship()); // check that one stopTimeUpdate was added to the cancellation of cancellation assertEquals(1, tu.getStopTimeUpdateCount()); - assertEquals(GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.NO_DATA, tu.getStopTimeUpdate(0).getScheduleRelationship()); + assertEquals(GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.NO_DATA, + tu.getStopTimeUpdate(0).getScheduleRelationship()); assertEquals(1, tu.getStopTimeUpdate(0).getStopSequence()); assertEquals(false, tu.getStopTimeUpdate(0).hasArrival()); assertEquals(false, tu.getStopTimeUpdate(0).hasDeparture()); @@ -208,53 +170,33 @@ public void testCancellationOfCancellationWithPreviousStopTimeUpdates() { TripUpdateProcessor processor = new TripUpdateProcessor(null); // first, add trip with a stop time update - InternalMessages.TripInfo tripInfo = InternalMessages.TripInfo.newBuilder() - .setTripId("trip_1") - .setDirectionId(1) - .setOperatingDay("20200101") - .setStartTime("00:00:00") - .setRouteId("2550") - .setScheduleType(InternalMessages.TripInfo.ScheduleType.SCHEDULED) - .build(); - - Optional tripUpdate = processor.processStopEstimate(InternalMessages.StopEstimate.newBuilder() - .setSchemaVersion(1) - .setStopId("1") - .setStopSequence(1) - .setEstimatedTimeUtcMs(0) - .setScheduledTimeUtcMs(0) - .setLastModifiedUtcMs(0) - .setType(InternalMessages.StopEstimate.Type.ARRIVAL) - .setStatus(InternalMessages.StopEstimate.Status.SCHEDULED) - .setTripInfo(tripInfo) - .build()); + InternalMessages.TripInfo tripInfo = InternalMessages.TripInfo.newBuilder().setTripId("trip_1") + .setDirectionId(1).setOperatingDay("20200101").setStartTime("00:00:00").setRouteId("2550") + .setScheduleType(InternalMessages.TripInfo.ScheduleType.SCHEDULED).build(); + + Optional tripUpdate = processor.processStopEstimate(InternalMessages.StopEstimate + .newBuilder().setSchemaVersion(1).setStopId("1").setStopSequence(1).setEstimatedTimeUtcMs(0) + .setScheduledTimeUtcMs(0).setLastModifiedUtcMs(0).setType(InternalMessages.StopEstimate.Type.ARRIVAL) + .setStatus(InternalMessages.StopEstimate.Status.SCHEDULED).setTripInfo(tripInfo).build()); // then, cancel the trip - GtfsRealtime.TripUpdate tripCancellation = processor.processTripCancellation("trip_1", 0, InternalMessages.TripCancellation.newBuilder() - .setSchemaVersion(1) - .setTripId("trip_1") - .setDirectionId(1) - .setStartDate("20200101") - .setStartTime("00:00:00") - .setRouteId("2550") - .setStatus(InternalMessages.TripCancellation.Status.CANCELED) - .build()); + GtfsRealtime.TripUpdate tripCancellation = processor.processTripCancellation("trip_1", 0, + InternalMessages.TripCancellation.newBuilder().setSchemaVersion(1).setTripId("trip_1").setDirectionId(1) + .setStartDate("20200101").setStartTime("00:00:00").setRouteId("2550") + .setStatus(InternalMessages.TripCancellation.Status.CANCELED).build()); // cancel the cancellation - GtfsRealtime.TripUpdate tu = processor.processTripCancellation("trip_1", 0, InternalMessages.TripCancellation.newBuilder() - .setSchemaVersion(1) - .setTripId("trip_1") - .setDirectionId(1) - .setStartDate("20200101") - .setStartTime("00:00:00") - .setRouteId("2550") - .setStatus(InternalMessages.TripCancellation.Status.RUNNING) - .build()); + GtfsRealtime.TripUpdate tu = processor.processTripCancellation("trip_1", 0, + InternalMessages.TripCancellation.newBuilder().setSchemaVersion(1).setTripId("trip_1").setDirectionId(1) + .setStartDate("20200101").setStartTime("00:00:00").setRouteId("2550") + .setStatus(InternalMessages.TripCancellation.Status.RUNNING).build()); // check that the cancellation has one stopTimeUpdate and its the one that was added before the first cancellation - assertEquals(GtfsRealtime.TripDescriptor.ScheduleRelationship.SCHEDULED, tu.getTrip().getScheduleRelationship()); + assertEquals(GtfsRealtime.TripDescriptor.ScheduleRelationship.SCHEDULED, + tu.getTrip().getScheduleRelationship()); assertEquals(1, tu.getStopTimeUpdateCount()); - assertEquals(GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.SCHEDULED, tu.getStopTimeUpdate(0).getScheduleRelationship()); + assertEquals(GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.SCHEDULED, + tu.getStopTimeUpdate(0).getScheduleRelationship()); assertEquals(true, tu.getStopTimeUpdate(0).hasStopId()); assertEquals(true, tu.getStopTimeUpdate(0).hasArrival()); assertEquals(true, tu.getStopTimeUpdate(0).hasDeparture()); diff --git a/src/test/java/fi/hsl/transitdata/tripupdate/validators/PrematureDeparturesValidatorTest.java b/src/test/java/fi/hsl/transitdata/tripupdate/validators/PrematureDeparturesValidatorTest.java index 5c64eae..ae1e105 100644 --- a/src/test/java/fi/hsl/transitdata/tripupdate/validators/PrematureDeparturesValidatorTest.java +++ b/src/test/java/fi/hsl/transitdata/tripupdate/validators/PrematureDeparturesValidatorTest.java @@ -23,8 +23,8 @@ public void tripUpdateWithPrematureDepartureIsDiscarded() { Collection stopTimeUpdates = new ArrayList<>(); stopTimeUpdates.add(MockDataFactory.mockStopTimeUpdate("A", 0, 1541603400)); - GtfsRealtime.TripUpdate tripUpdate = MockDataFactory.mockTripUpdate("1010", 0, "20181107", - "17:14:00", stopTimeUpdates); + GtfsRealtime.TripUpdate tripUpdate = MockDataFactory.mockTripUpdate("1010", 0, "20181107", "17:14:00", + stopTimeUpdates); assertEquals(false, validator.validate(tripUpdate)); @@ -40,8 +40,8 @@ public void tripUpdateWithPrematureArrivalIsDiscarded() { Collection stopTimeUpdates = new ArrayList<>(); stopTimeUpdates.add(MockDataFactory.mockStopTimeUpdate("A", 1541603400, 0)); - GtfsRealtime.TripUpdate tripUpdate = MockDataFactory.mockTripUpdate("1010", 0, "20181107", - "17:14:00", stopTimeUpdates); + GtfsRealtime.TripUpdate tripUpdate = MockDataFactory.mockTripUpdate("1010", 0, "20181107", "17:14:00", + stopTimeUpdates); assertEquals(false, validator.validate(tripUpdate)); @@ -57,7 +57,8 @@ public void tripUpdateWithValidDepartureIsAccepted() { Collection stopTimeUpdates = new ArrayList<>(); stopTimeUpdates.add(MockDataFactory.mockStopTimeUpdate("A", 0, 1541603400)); - GtfsRealtime.TripUpdate tripUpdate = MockDataFactory.mockTripUpdate("1010", 0, "20181107", "17:11:00", stopTimeUpdates); + GtfsRealtime.TripUpdate tripUpdate = MockDataFactory.mockTripUpdate("1010", 0, "20181107", "17:11:00", + stopTimeUpdates); assertEquals(true, validator.validate(tripUpdate)); @@ -73,7 +74,8 @@ public void tripUpdateValidInEuropeHelsinkiIsDiscardedWhenTimezoneIsUTC() { Collection stopTimeUpdates = new ArrayList<>(); stopTimeUpdates.add(MockDataFactory.mockStopTimeUpdate("A", 0, 1541603400)); - GtfsRealtime.TripUpdate tripUpdate = MockDataFactory.mockTripUpdate("1010", 0, "20181107", "17:11:00", stopTimeUpdates); + GtfsRealtime.TripUpdate tripUpdate = MockDataFactory.mockTripUpdate("1010", 0, "20181107", "17:11:00", + stopTimeUpdates); assertEquals(false, validator.validate(tripUpdate)); @@ -113,5 +115,4 @@ public void tripUpdateStartTimeJustAfterMidnightIsParsedCorrectly() { assertEquals(1541628060, validator.tripStartTimeToPosixTime(tripUpdate)); } - } diff --git a/src/test/java/fi/hsl/transitdata/tripupdate/validators/TripUpdateMaxAgeValidatorTest.java b/src/test/java/fi/hsl/transitdata/tripupdate/validators/TripUpdateMaxAgeValidatorTest.java index 0e15af1..423d4af 100644 --- a/src/test/java/fi/hsl/transitdata/tripupdate/validators/TripUpdateMaxAgeValidatorTest.java +++ b/src/test/java/fi/hsl/transitdata/tripupdate/validators/TripUpdateMaxAgeValidatorTest.java @@ -36,7 +36,8 @@ public void tripUpdateWithOveragedLastStopDepartureTimeIsDiscarded() { //2018-11-07T17:30:00 in Helsinki/Europe stopTimeUpdates.add(MockDataFactory.mockStopTimeUpdate("B", 0, 1541604600)); - GtfsRealtime.TripUpdate tripUpdate = MockDataFactory.mockTripUpdate("1010", 0, "20181107", "17:14:00", stopTimeUpdates); + GtfsRealtime.TripUpdate tripUpdate = MockDataFactory.mockTripUpdate("1010", 0, "20181107", "17:14:00", + stopTimeUpdates); //Validate with 2018-11-07T19:31:00 assertEquals(false, validator.validateWithCurrentTime(tripUpdate, 1541611860)); @@ -55,7 +56,8 @@ public void tripUpdateWithValidLastStopDepartureTimeIsAccepted() { //2018-11-07T17:30:00 in Helsinki/Europe stopTimeUpdates.add(MockDataFactory.mockStopTimeUpdate("B", 0, 1541604600)); - GtfsRealtime.TripUpdate tripUpdate = MockDataFactory.mockTripUpdate("1010", 0, "20181107", "17:14:00", stopTimeUpdates); + GtfsRealtime.TripUpdate tripUpdate = MockDataFactory.mockTripUpdate("1010", 0, "20181107", "17:14:00", + stopTimeUpdates); //Validate with 2018-11-07T19:31:00 assertEquals(true, validator.validateWithCurrentTime(tripUpdate, 1541611740));