1+ package com .microsoft .graph .httpcore ;
2+
3+ import java .io .IOException ;
4+ import java .util .concurrent .ThreadLocalRandom ;
5+
6+ import com .microsoft .graph .httpcore .middlewareoption .MiddlewareType ;
7+ import com .microsoft .graph .httpcore .middlewareoption .TelemetryOptions ;
8+
9+ import okhttp3 .Interceptor ;
10+ import okhttp3 .MediaType ;
11+ import okhttp3 .Protocol ;
12+ import okhttp3 .Request ;
13+ import okhttp3 .Response ;
14+ import okhttp3 .ResponseBody ;
15+
16+ public class ChaosHttpHandler implements Interceptor {
17+
18+ public final MiddlewareType MIDDLEWARE_TYPE = MiddlewareType .RETRY ;
19+
20+ /*
21+ * constant string being used
22+ */
23+ private final String RETRY_AFTER = "Retry-After" ;
24+
25+ public static final int MSClientErrorCodeTooManyRequests = 429 ;
26+
27+ @ Override
28+ public Response intercept (Chain chain ) throws IOException {
29+ Request request = chain .request ();
30+
31+ if (request .tag (TelemetryOptions .class ) == null )
32+ request = request .newBuilder ().tag (TelemetryOptions .class , new TelemetryOptions ()).build ();
33+ request .tag (TelemetryOptions .class ).setFeatureUsage (TelemetryOptions .RETRY_HANDLER_ENABLED_FLAG );
34+
35+ final Integer dice = ThreadLocalRandom .current ().nextInt (1 , Integer .MAX_VALUE );
36+
37+ if (dice % 3 == 0 ) {
38+ return new Response
39+ .Builder ()
40+ .request (request )
41+ .protocol (Protocol .HTTP_1_1 )
42+ .code (MSClientErrorCodeTooManyRequests )
43+ .message ("Too Many Requests" )
44+ .addHeader (RETRY_AFTER , "10" )
45+ .body (ResponseBody .create (MediaType .get ("application/json" ), "{\" error\" : {\" code\" : \" TooManyRequests\" ,\" innerError\" : {\" code\" : \" 429\" ,\" date\" : \" 2020-08-18T12:51:51\" ,\" message\" : \" Please retry after\" ,\" request-id\" : \" 94fb3b52-452a-4535-a601-69e0a90e3aa2\" ,\" status\" : \" 429\" },\" message\" : \" Please retry again later.\" }}" ))
46+ .build ();
47+ } else {
48+ return chain .proceed (request );
49+ }
50+ }
51+
52+ }
0 commit comments