Skip to content

Commit

Permalink
Ensure null-safe lookup on immutable map
Browse files Browse the repository at this point in the history
  • Loading branch information
vpaturet committed Aug 20, 2024
1 parent 49f29b4 commit 9baf38b
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions src/main/java/org/opentripplanner/model/TimetableSnapshot.java
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ public boolean hasRealtimeAddedTripPatterns() {
*/
@Nullable
public Route getRealtimeAddedRoute(FeedScopedId id) {
return realtimeAddedRoutes.get(id);
return getByNullableKey(id, realtimeAddedRoutes);
}

public Collection<Route> getAllRealTimeAddedRoutes() {
Expand All @@ -235,7 +235,7 @@ public Collection<Route> getAllRealTimeAddedRoutes() {
*/
@Nullable
public Trip getRealTimeAddedTrip(FeedScopedId id) {
return realTimeAddedTrips.get(id);
return getByNullableKey(id, realTimeAddedTrips);
}

public Collection<Trip> getAllRealTimeAddedTrips() {
Expand All @@ -247,7 +247,7 @@ public Collection<Trip> getAllRealTimeAddedTrips() {
*/
@Nullable
public TripPattern getRealTimeAddedPatternForTrip(Trip trip) {
return realTimeAddedPatternForTrip.get(trip);
return getByNullableKey(trip, realTimeAddedPatternForTrip);
}

/**
Expand All @@ -262,7 +262,7 @@ public Collection<TripPattern> getRealTimeAddedPatternForRoute(Route route) {
*/
@Nullable
public TripOnServiceDate getRealTimeAddedTripOnServiceDateById(FeedScopedId id) {
return realTimeAddedTripOnServiceDateById.get(id);
return getByNullableKey(id, realTimeAddedTripOnServiceDateById);
}

/**
Expand All @@ -272,7 +272,7 @@ public TripOnServiceDate getRealTimeAddedTripOnServiceDateById(FeedScopedId id)
public TripOnServiceDate getRealTimeAddedTripOnServiceDateForTripAndDay(
TripIdAndServiceDate tripIdAndServiceDate
) {
return realTimeAddedTripOnServiceDateForTripAndDay.get(tripIdAndServiceDate);
return getByNullableKey(tripIdAndServiceDate, realTimeAddedTripOnServiceDateForTripAndDay);
}

public Collection<? extends TripOnServiceDate> getAllRealTimeAddedTripOnServiceDate() {
Expand Down Expand Up @@ -611,6 +611,20 @@ private Timetable copyTimetable(TripPattern pattern, LocalDate serviceDate, Time
return tt;
}

/**
* Look up the given key in a Map, return null if the key is null.
* This prevents a NullPointerException if the underlying implementation of the map does not
* accept querying with null keys (e.g. ImmutableMap).
*
**/
@Nullable
private static <K, V> V getByNullableKey(K key, Map<K, ? extends V> map) {
if (key == null) {
return null;
}
return map.get(key);
}

protected static class SortedTimetableComparator implements Comparator<Timetable> {

@Override
Expand Down

0 comments on commit 9baf38b

Please sign in to comment.