| 25 | import java.util.logging.Logger; |
| 26 | |
| 27 | public class RetryRequest implements Filter { |
| 28 | |
| 29 | private static final Logger LOG = Logger.getLogger(RetryRequest.class.getName()); |
| 30 | |
| 31 | private static final int RETRIES_ON_CONNECTION_FAILURE = 3; |
| 32 | private static final int RETRIES_ON_SERVER_ERROR = 2; |
| 33 | private static final int NEEDED_ATTEMPTS = |
| 34 | Math.max(RETRIES_ON_CONNECTION_FAILURE, RETRIES_ON_SERVER_ERROR) + 1; |
| 35 | |
| 36 | @Override |
| 37 | public HttpHandler apply(HttpHandler next) { |
| 38 | return req -> { |
| 39 | // start to perform the request in a loop, to allow retries |
| 40 | for (int i = 0; i < NEEDED_ATTEMPTS; i++) { |
| 41 | HttpResponse response; |
| 42 | |
| 43 | try { |
| 44 | response = next.execute(req); |
| 45 | } catch (RuntimeException ex) { |
| 46 | // detect a connection failure we would like to retry |
| 47 | boolean isConnectionFailure = ex.getCause() instanceof ConnectException; |
| 48 | |
| 49 | // must be a connection failure and check whether we have retries left for this |
| 50 | if (isConnectionFailure && i < RETRIES_ON_CONNECTION_FAILURE) { |
| 51 | LOG.log(Level.FINE, "Retry #" + (i + 1) + " on ConnectException", ex); |
| 52 | continue; |
| 53 | } |
| 54 | |
| 55 | // not a connection failure or retries exceeded, rethrow and let the caller handle this |
| 56 | throw ex; |
| 57 | } |
| 58 | |
| 59 | // detect a server error we would like to retry |
| 60 | boolean isServerError = |
| 61 | (response.getStatus() == HTTP_INTERNAL_ERROR && response.getContent().length() == 0) |
| 62 | || response.getStatus() == HTTP_UNAVAILABLE; |
| 63 | |
| 64 | // must be a server error and check whether we have retries left for this |
| 65 | if (isServerError && i < RETRIES_ON_SERVER_ERROR) { |
| 66 | LOG.fine("Retry #" + (i + 1) + " on ServerError: " + response.getStatus()); |
| 67 | continue; |
| 68 | } |
| 69 | |
| 70 | // not a server error or retries exceeded, return the result to the caller |
| 71 | return response; |
| 72 | } |
| 73 | |
| 74 | // This should not be reachable, we either retry or fail before. The only way to get here |
| 75 | // is to set the static final int fields above to inconsistent values. |
| 76 | throw new IllegalStateException("Effective unreachable code reached, check constants."); |
| 77 | }; |
| 78 | } |
| 79 | } |