1+ package com .michaelfotiadis .steam .net .client .interceptors ;
2+
3+ import java .io .IOException ;
4+ import java .net .SocketTimeoutException ;
5+
6+ import okhttp3 .Interceptor ;
7+ import okhttp3 .Request ;
8+ import okhttp3 .Response ;
9+
10+ public class RetryPolicyInterceptor implements Interceptor {
11+ private static final int HTTP_CODE_202 = 202 ;
12+ private static final long MAX_RETRY_TIME = 60 * 60 * 1000 ; // 1 minute
13+ private static final long SLEEP_TIME = 3 * 1000 ; // 3 seconds
14+
15+ @ Override
16+ public Response intercept (final Chain chain ) throws IOException {
17+
18+ final Request request = chain .request ();
19+ final Response response ;
20+ try {
21+ // try the call
22+ response = chain .proceed (request );
23+
24+ //noinspection IfStatementWithNegatedCondition
25+ if (response .code () != HTTP_CODE_202 ) {
26+ return response ;
27+ } else {
28+ response .body ().close ();
29+ return repeatRequest (chain , request );
30+ }
31+ } catch (final SocketTimeoutException e ) {
32+ throw e ;
33+ }
34+ }
35+
36+ @ SuppressWarnings ("MethodMayBeStatic" )
37+ private Response repeatRequest (final Chain chain , final Request authorisedRequest ) throws IOException {
38+
39+ Response repeatResponse = chain .proceed (authorisedRequest );
40+
41+ final long startTime = System .currentTimeMillis ();
42+ while (repeatResponse .code () == HTTP_CODE_202 ) {
43+ final long elapsedTime = System .currentTimeMillis () - startTime ;
44+ if (elapsedTime > MAX_RETRY_TIME ) {
45+ return chain .proceed (authorisedRequest );
46+ } else {
47+ try {
48+ Thread .sleep (SLEEP_TIME );
49+ } catch (final InterruptedException e ) {
50+ //Do nothing.
51+ }
52+ repeatResponse = chain .proceed (authorisedRequest );
53+ //noinspection IfStatementWithNegatedCondition
54+ if (repeatResponse .code () != HTTP_CODE_202 ) {
55+ return chain .proceed (authorisedRequest );
56+ } else {
57+ chain .proceed (authorisedRequest );
58+ }
59+ }
60+ }
61+
62+ return repeatResponse ;
63+ }
64+
65+ }
0 commit comments