MenuItemsLoader.java

1
package edu.ucsb.cs156.dining.services;
2
3
import com.fasterxml.jackson.databind.JsonNode;
4
import com.fasterxml.jackson.databind.ObjectMapper;
5
import edu.ucsb.cs156.dining.models.DiningCommons;
6
import edu.ucsb.cs156.dining.models.Entree;
7
import java.time.Clock;
8
import java.time.LocalDate;
9
import java.time.YearMonth;
10
import java.time.ZoneId;
11
import java.util.List;
12
import lombok.extern.slf4j.Slf4j;
13
import org.springframework.beans.factory.annotation.Value;
14
import org.springframework.http.HttpHeaders;
15
import org.springframework.stereotype.Service;
16
import org.springframework.web.client.HttpClientErrorException;
17
18
/**
19
 * Downloads every MenuItem for the current month from the UCSB Dining API and stores them in the
20
 * database. Intended to be called once at startup, so that users don't depend on someone having
21
 * visited a given day's menu for its items to exist.
22
 *
23
 * <p>Requests that get an HTTP 429 (Too Many Requests) are retried with exponential backoff
24
 * (honoring a {@code Retry-After} header when present). If the retries are exhausted, the whole
25
 * load stops rather than continuing to hammer the API. If the API key is not configured, no
26
 * requests are sent at all.
27
 */
28
@Slf4j
29
@Service
30
public class MenuItemsLoader {
31
32
  /** The default value of app.ucsb.api.consumer_key when UCSB_API_KEY has not been set. */
33
  public static final String PLACEHOLDER_API_KEY = "see-instructions-in-readme";
34
35
  public static final int MAX_ATTEMPTS = 5;
36
  public static final long BASE_BACKOFF_MS = 1000;
37
  public static final long MAX_BACKOFF_MS = 60_000;
38
39
  /** A call to the UCSB API that may throw. */
40
  @FunctionalInterface
41
  interface ApiCall<T> {
42
    T call() throws Exception;
43
  }
44
45
  /** Abstraction over Thread.sleep so tests don't really wait. */
46
  @FunctionalInterface
47
  interface Sleeper {
48
    void sleep(long millis) throws InterruptedException;
49
  }
50
51
  private final DiningCommonsService diningCommonsService;
52
  private final UCSBDiningMenuService menuService;
53
  private final UCSBDiningMenuItemsService menuItemsService;
54
  private final ObjectMapper objectMapper;
55
  private final String apiKey;
56
57
  Clock clock = Clock.system(ZoneId.of("America/Los_Angeles"));
58
  Sleeper sleeper = Thread::sleep;
59
60
  public MenuItemsLoader(
61
      DiningCommonsService diningCommonsService,
62
      UCSBDiningMenuService menuService,
63
      UCSBDiningMenuItemsService menuItemsService,
64
      ObjectMapper objectMapper,
65
      @Value("${app.ucsb.api.consumer_key}") String apiKey) {
66
    this.diningCommonsService = diningCommonsService;
67
    this.menuService = menuService;
68
    this.menuItemsService = menuItemsService;
69
    this.objectMapper = objectMapper;
70
    this.apiKey = apiKey;
71
  }
72
73
  boolean apiKeyMissing() {
74 4 1. apiKeyMissing : negated conditional → KILLED
2. apiKeyMissing : negated conditional → KILLED
3. apiKeyMissing : negated conditional → KILLED
4. apiKeyMissing : replaced boolean return with true for edu/ucsb/cs156/dining/services/MenuItemsLoader::apiKeyMissing → KILLED
    return apiKey == null || apiKey.isBlank() || PLACEHOLDER_API_KEY.equals(apiKey);
75
  }
76
77
  /**
78
   * Loads all MenuItems for every day of the current month, for every dining commons. Never throws:
79
   * problems are logged.
80
   */
81
  public void loadCurrentMonth() {
82 1 1. loadCurrentMonth : negated conditional → KILLED
    if (apiKeyMissing()) {
83
      log.warn("UCSB API key is not set; skipping startup load of current month's menu items");
84
      return;
85
    }
86
87
    try {
88
      YearMonth month = YearMonth.now(clock);
89
      log.info("Loading menu items for {}", month);
90
      List<DiningCommons> commons = withRetry(diningCommonsService::get);
91 2 1. loadCurrentMonth : changed conditional boundary → KILLED
2. loadCurrentMonth : negated conditional → KILLED
      for (int day = 1; day <= month.lengthOfMonth(); day++) {
92
        LocalDate date = month.atDay(day);
93
        for (DiningCommons dc : commons) {
94 1 1. loadCurrentMonth : removed call to edu/ucsb/cs156/dining/services/MenuItemsLoader::loadDay → KILLED
          loadDay(date, dc.getCode());
95
        }
96
      }
97
      log.info("Finished loading menu items for {}", month);
98
    } catch (InterruptedException e) {
99 1 1. loadCurrentMonth : removed call to java/lang/Thread::interrupt → KILLED
      Thread.currentThread().interrupt();
100
      log.warn("Startup load of menu items was interrupted");
101
    } catch (Exception e) {
102
      log.error("Startup load of menu items stopped early: {}", e.getMessage());
103
    }
104
  }
105
106
  private void loadDay(LocalDate date, String commonsCode) throws Exception {
107
    String dateString = date.toString();
108
    String mealsJson;
109
    try {
110 1 1. lambda$loadDay$0 : replaced return value with "" for edu/ucsb/cs156/dining/services/MenuItemsLoader::lambda$loadDay$0 → KILLED
      mealsJson = withRetry(() -> menuService.getJSON(dateString, commonsCode));
111
    } catch (HttpClientErrorException.TooManyRequests | InterruptedException e) {
112
      throw e;
113
    } catch (Exception e) {
114
      log.error("Could not get meals for {} on {}: {}", commonsCode, dateString, e.getMessage());
115
      return;
116
    }
117 2 1. loadDay : negated conditional → KILLED
2. loadDay : negated conditional → KILLED
    if (mealsJson == null || mealsJson.isBlank()) {
118
      return; // commons is closed that day
119
    }
120
121
    JsonNode meals;
122
    try {
123
      meals = objectMapper.readTree(mealsJson);
124
    } catch (Exception e) {
125
      log.error("Could not parse meals for {} on {}: {}", commonsCode, dateString, e.getMessage());
126
      return;
127
    }
128
    for (JsonNode meal : meals) {
129 1 1. loadDay : removed call to edu/ucsb/cs156/dining/services/MenuItemsLoader::loadMeal → KILLED
      loadMeal(dateString, commonsCode, meal.path("code").asText());
130
    }
131
  }
132
133
  private void loadMeal(String dateString, String commonsCode, String mealCode) throws Exception {
134
    try {
135
      List<Entree> entrees =
136 1 1. lambda$loadMeal$0 : replaced return value with Collections.emptyList for edu/ucsb/cs156/dining/services/MenuItemsLoader::lambda$loadMeal$0 → KILLED
          withRetry(() -> menuItemsService.get(dateString, commonsCode, mealCode));
137
      menuItemsService.getOrCreateMenuItems(commonsCode, mealCode, entrees);
138
    } catch (HttpClientErrorException.TooManyRequests | InterruptedException e) {
139
      throw e;
140
    } catch (Exception e) {
141
      log.error(
142
          "Could not load items for {} {} on {}: {}",
143
          commonsCode,
144
          mealCode,
145
          dateString,
146
          e.getMessage());
147
    }
148
  }
149
150
  /** Runs the call, retrying with backoff on HTTP 429 up to MAX_ATTEMPTS total attempts. */
151
  <T> T withRetry(ApiCall<T> call) throws Exception {
152 1 1. withRetry : Changed increment from 1 to -1 → TIMED_OUT
    for (int attempt = 1; ; attempt++) {
153
      try {
154 1 1. withRetry : replaced return value with null for edu/ucsb/cs156/dining/services/MenuItemsLoader::withRetry → KILLED
        return call.call();
155
      } catch (HttpClientErrorException.TooManyRequests e) {
156 2 1. withRetry : negated conditional → KILLED
2. withRetry : changed conditional boundary → KILLED
        if (attempt >= MAX_ATTEMPTS) {
157
          throw e;
158
        }
159
        long delay = backoffMillis(attempt, e);
160
        log.warn("Rate limited by UCSB API (attempt {}); waiting {} ms", attempt, delay);
161 1 1. withRetry : removed call to edu/ucsb/cs156/dining/services/MenuItemsLoader$Sleeper::sleep → KILLED
        sleeper.sleep(delay);
162
      }
163
    }
164
  }
165
166
  static long backoffMillis(int attempt, HttpClientErrorException e) {
167 2 1. backoffMillis : Replaced integer subtraction with addition → KILLED
2. backoffMillis : Replaced Shift Left with Shift Right → KILLED
    long millis = BASE_BACKOFF_MS << (attempt - 1);
168
    HttpHeaders headers = e.getResponseHeaders();
169 1 1. backoffMillis : negated conditional → KILLED
    String retryAfter = headers == null ? null : headers.getFirst(HttpHeaders.RETRY_AFTER);
170 1 1. backoffMillis : negated conditional → KILLED
    if (retryAfter != null) {
171
      try {
172 1 1. backoffMillis : Replaced long multiplication with division → KILLED
        millis = Long.parseLong(retryAfter.trim()) * 1000;
173
      } catch (NumberFormatException ignored) {
174
        // not a number of seconds (could be an HTTP date); use exponential backoff instead
175
      }
176
    }
177 1 1. backoffMillis : replaced long return with 0 for edu/ucsb/cs156/dining/services/MenuItemsLoader::backoffMillis → KILLED
    return Math.min(millis, MAX_BACKOFF_MS);
178
  }
179
}

Mutations

74

1.1
Location : apiKeyMissing
Killed by : edu.ucsb.cs156.dining.services.MenuItemsLoaderTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.dining.services.MenuItemsLoaderTests]/[method:real_key_is_not_missing()]
negated conditional → KILLED

2.2
Location : apiKeyMissing
Killed by : edu.ucsb.cs156.dining.services.MenuItemsLoaderTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.dining.services.MenuItemsLoaderTests]/[method:real_key_is_not_missing()]
negated conditional → KILLED

3.3
Location : apiKeyMissing
Killed by : edu.ucsb.cs156.dining.services.MenuItemsLoaderTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.dining.services.MenuItemsLoaderTests]/[method:real_key_is_not_missing()]
negated conditional → KILLED

4.4
Location : apiKeyMissing
Killed by : edu.ucsb.cs156.dining.services.MenuItemsLoaderTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.dining.services.MenuItemsLoaderTests]/[method:real_key_is_not_missing()]
replaced boolean return with true for edu/ucsb/cs156/dining/services/MenuItemsLoader::apiKeyMissing → KILLED

82

1.1
Location : loadCurrentMonth
Killed by : edu.ucsb.cs156.dining.services.MenuItemsLoaderTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.dining.services.MenuItemsLoaderTests]/[method:blank_null_and_placeholder_keys_send_no_requests()]
negated conditional → KILLED

91

1.1
Location : loadCurrentMonth
Killed by : edu.ucsb.cs156.dining.services.MenuItemsLoaderTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.dining.services.MenuItemsLoaderTests]/[method:error_getting_meals_for_one_day_does_not_stop_the_load()]
changed conditional boundary → KILLED

2.2
Location : loadCurrentMonth
Killed by : edu.ucsb.cs156.dining.services.MenuItemsLoaderTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.dining.services.MenuItemsLoaderTests]/[method:gives_up_after_max_attempts_and_stops_the_whole_load()]
negated conditional → KILLED

94

1.1
Location : loadCurrentMonth
Killed by : edu.ucsb.cs156.dining.services.MenuItemsLoaderTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.dining.services.MenuItemsLoaderTests]/[method:gives_up_after_max_attempts_and_stops_the_whole_load()]
removed call to edu/ucsb/cs156/dining/services/MenuItemsLoader::loadDay → KILLED

99

1.1
Location : loadCurrentMonth
Killed by : edu.ucsb.cs156.dining.services.MenuItemsLoaderTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.dining.services.MenuItemsLoaderTests]/[method:interrupt_while_backing_off_stops_the_load_and_keeps_interrupt_flag()]
removed call to java/lang/Thread::interrupt → KILLED

110

1.1
Location : lambda$loadDay$0
Killed by : edu.ucsb.cs156.dining.services.MenuItemsLoaderTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.dining.services.MenuItemsLoaderTests]/[method:interrupt_while_backing_off_during_item_load_is_propagated()]
replaced return value with "" for edu/ucsb/cs156/dining/services/MenuItemsLoader::lambda$loadDay$0 → KILLED

117

1.1
Location : loadDay
Killed by : edu.ucsb.cs156.dining.services.MenuItemsLoaderTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.dining.services.MenuItemsLoaderTests]/[method:interrupt_while_backing_off_during_item_load_is_propagated()]
negated conditional → KILLED

2.2
Location : loadDay
Killed by : edu.ucsb.cs156.dining.services.MenuItemsLoaderTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.dining.services.MenuItemsLoaderTests]/[method:closed_days_and_empty_meal_lists_are_skipped()]
negated conditional → KILLED

129

1.1
Location : loadDay
Killed by : edu.ucsb.cs156.dining.services.MenuItemsLoaderTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.dining.services.MenuItemsLoaderTests]/[method:interrupt_while_backing_off_during_item_load_is_propagated()]
removed call to edu/ucsb/cs156/dining/services/MenuItemsLoader::loadMeal → KILLED

136

1.1
Location : lambda$loadMeal$0
Killed by : edu.ucsb.cs156.dining.services.MenuItemsLoaderTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.dining.services.MenuItemsLoaderTests]/[method:loads_every_day_of_the_month_for_every_commons_and_meal()]
replaced return value with Collections.emptyList for edu/ucsb/cs156/dining/services/MenuItemsLoader::lambda$loadMeal$0 → KILLED

152

1.1
Location : withRetry
Killed by : none
Changed increment from 1 to -1 → TIMED_OUT

154

1.1
Location : withRetry
Killed by : edu.ucsb.cs156.dining.services.MenuItemsLoaderTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.dining.services.MenuItemsLoaderTests]/[method:gives_up_after_max_attempts_and_stops_the_whole_load()]
replaced return value with null for edu/ucsb/cs156/dining/services/MenuItemsLoader::withRetry → KILLED

156

1.1
Location : withRetry
Killed by : edu.ucsb.cs156.dining.services.MenuItemsLoaderTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.dining.services.MenuItemsLoaderTests]/[method:withRetry_rethrows_the_original_exception_after_max_attempts()]
negated conditional → KILLED

2.2
Location : withRetry
Killed by : edu.ucsb.cs156.dining.services.MenuItemsLoaderTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.dining.services.MenuItemsLoaderTests]/[method:withRetry_rethrows_the_original_exception_after_max_attempts()]
changed conditional boundary → KILLED

161

1.1
Location : withRetry
Killed by : edu.ucsb.cs156.dining.services.MenuItemsLoaderTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.dining.services.MenuItemsLoaderTests]/[method:interrupt_while_backing_off_stops_the_load_and_keeps_interrupt_flag()]
removed call to edu/ucsb/cs156/dining/services/MenuItemsLoader$Sleeper::sleep → KILLED

167

1.1
Location : backoffMillis
Killed by : edu.ucsb.cs156.dining.services.MenuItemsLoaderTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.dining.services.MenuItemsLoaderTests]/[method:backoff_handles_missing_headers()]
Replaced integer subtraction with addition → KILLED

2.2
Location : backoffMillis
Killed by : edu.ucsb.cs156.dining.services.MenuItemsLoaderTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.dining.services.MenuItemsLoaderTests]/[method:backoff_is_capped()]
Replaced Shift Left with Shift Right → KILLED

169

1.1
Location : backoffMillis
Killed by : edu.ucsb.cs156.dining.services.MenuItemsLoaderTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.dining.services.MenuItemsLoaderTests]/[method:backoff_handles_missing_headers()]
negated conditional → KILLED

170

1.1
Location : backoffMillis
Killed by : edu.ucsb.cs156.dining.services.MenuItemsLoaderTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.dining.services.MenuItemsLoaderTests]/[method:backoff_handles_missing_headers()]
negated conditional → KILLED

172

1.1
Location : backoffMillis
Killed by : edu.ucsb.cs156.dining.services.MenuItemsLoaderTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.dining.services.MenuItemsLoaderTests]/[method:backoff_honors_retry_after_seconds()]
Replaced long multiplication with division → KILLED

177

1.1
Location : backoffMillis
Killed by : edu.ucsb.cs156.dining.services.MenuItemsLoaderTests.[engine:junit-jupiter]/[class:edu.ucsb.cs156.dining.services.MenuItemsLoaderTests]/[method:backoff_handles_missing_headers()]
replaced long return with 0 for edu/ucsb/cs156/dining/services/MenuItemsLoader::backoffMillis → KILLED

Active mutators

Tests examined


Report generated by PIT 1.22.1