001package org.hl7.fhir.utilities.http.okhttpimpl;
002
003import lombok.extern.slf4j.Slf4j;
004import okhttp3.Interceptor;
005import okhttp3.Request;
006import okhttp3.Response;
007
008import java.io.IOException;
009
010/**
011 * An {@link Interceptor} for {@link okhttp3.OkHttpClient} that controls the number of times we retry a to execute a
012 * given request, before reporting a failure. This includes unsuccessful return codes and timeouts.
013 */
014@Slf4j
015public class RetryInterceptor implements Interceptor {
016
017  // Delay between retying failed requests, in millis
018  private final long RETRY_TIME = 2000;
019
020  // Maximum number of times to retry the request before failing
021  private final int maxRetry;
022
023  // Internal counter for tracking the number of times we've tried this request
024  private int retryCounter = 0;
025
026  public RetryInterceptor(int maxRetry) {
027    this.maxRetry = maxRetry;
028  }
029
030  @Override
031  public Response intercept(Chain chain) throws IOException {
032    Request request = chain.request();
033    Response response = null;
034
035    do {
036      try {
037        // If we are retrying a failed request that failed due to a bad response from the server, we must close it first
038        if (response != null) {
039          response.close();
040        }
041        response = chain.proceed(request);
042      } catch (IOException e) {
043        try {
044          // Include a small break in between requests.
045          Thread.sleep(RETRY_TIME);
046        } catch (InterruptedException e1) {
047          log.info(chain.request().method() + " to url -> " + chain.request().url() + " interrupted on try <" + retryCounter + ">");
048        }
049      } finally {
050        retryCounter++;
051      }
052    } while ((response == null || !response.isSuccessful()) && (retryCounter <= maxRetry + 1));
053
054    /*
055     * if something has gone wrong, and we are unable to complete the request, we still need to initialize the return
056     * response so we don't get a null pointer exception.
057     */
058    return response != null ? response : chain.proceed(request);
059  }
060
061}