UCSBDiningMenuService.java

package edu.ucsb.cs156.dining.services;

import java.time.Duration;
import java.util.Arrays;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;

/** Service object that wraps the UCSB Dining Menu API */
@Service
@Slf4j
public class UCSBDiningMenuService {

  @Value("${app.ucsb.api.consumer_key}")
  private String apiKey;

  @Value("${app.ucsb.api.host}")
  private String apiHost;

  @Value("${app.name}")
  private String appName;

  @Value("${app.hostname}")
  private String appHostname;

  /*
   * A RestTemplate built with no timeout blocks its calling thread forever on a hung external
   * call. That's a real incident lib-jobs' single-threaded jobsExecutor hit on another app
   * (proj-scaffold): a job stuck this way permanently wedged the executor, with no way to recover
   * short of restarting the app (see lib-jobs DESIGN.md 9 -- cooperative job cancellation only
   * helps a job that reaches another checkpoint, which a truly hung thread never will). Generous
   * but finite: long enough to never trip on legitimate slowness, short enough to guarantee a job
   * can't hang forever.
   */
  private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(10);
  private static final Duration READ_TIMEOUT = Duration.ofSeconds(60);

  private RestTemplate restTemplate = new RestTemplate();

  public UCSBDiningMenuService(RestTemplateBuilder restTemplateBuilder) throws Exception {
    restTemplate =
        restTemplateBuilder.connectTimeout(CONNECT_TIMEOUT).readTimeout(READ_TIMEOUT).build();
  }

  public static final String ALL_MEAL_TIMES_AT_A_DINING_COMMON_ENDPOINT =
      "{apiHost}/dining/menu/v1/{date-time}/{dining-common-code}";

  @Cacheable("menu")
  public String getJSON(String dateTime, String diningCommonCode) throws Exception {

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("ucsb-api-version", "1.0");
    headers.set("ucsb-api-key", this.apiKey);
    headers.set("X-Requesting-App", this.appName + "." + this.appHostname);

    HttpEntity<String> entity = new HttpEntity<>("body", headers);

    String url = ALL_MEAL_TIMES_AT_A_DINING_COMMON_ENDPOINT;
    url = url.replace("{apiHost}", apiHost);
    url = url.replace("{date-time}", dateTime);
    url = url.replace("{dining-common-code}", diningCommonCode);

    log.info("url=" + url);

    String retVal = "";
    MediaType contentType = null;
    HttpStatus statusCode = null;

    try {
      ResponseEntity<String> re = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
      contentType = re.getHeaders().getContentType();
      statusCode = (HttpStatus) re.getStatusCode();
      retVal = re.getBody();

      log.info("json: {} contentType: {} statusCode: {}", retVal, contentType, statusCode);
    } catch (HttpClientErrorException.TooManyRequests e) {
      // A rate limit is not a closed dining commons; let callers back off and retry.
      throw e;
    } catch (HttpClientErrorException | HttpServerErrorException e) {
      log.info("Dining commons {} closed on {}: {}", diningCommonCode, dateTime, e.getMessage());
      return null;
    }

    return retVal;
  }
}