Skip to content

Instantly share code, notes, and snippets.

@AndrewReitz
Created February 22, 2016 16:32
Show Gist options
  • Save AndrewReitz/7d8fbdcdb8a14f4315f9 to your computer and use it in GitHub Desktop.
Save AndrewReitz/7d8fbdcdb8a14f4315f9 to your computer and use it in GitHub Desktop.
package com.smartthings.android.common.http;
import com.inkapplications.preferences.IntPreference;
import com.smartthings.android.di.annotation.HttpDisasterRate;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Protocol;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.ResponseBody;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.io.IOException;
import java.util.Random;
/**
* Causes HTTP requests to fail with a 500 error randomly.
*
* This is an OkHTTP interceptor that will return fake 500 responses for http
* requests based on a random chance constrained to a failure rate.
* Ex. If the failure rate is set to 100% then ALL requests will fail. However,
* if the rate is set to 20% then the requests will fail 20% of the time.
*
* This is intended to be enabled during debug builds in order to test how the
* app responds to server outages.
*/
public class RandomDisasters implements Interceptor {
private int failureRate;
private Random random = new Random();
public RandomDisasters(int failureRate) {
this.failureRate = failureRate;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (getRandomPercent() < failureRate) {
chain.proceed(request); // throw this away.
return this.createFailedRequest(request);
}
return chain.proceed(request);
}
/**
* Create a fake "internal server error" response to return to the client.
*/
private Response createFailedRequest(Request request) {
Response.Builder responseBuilder = new Response.Builder();
responseBuilder.code(500);
responseBuilder.request(request);
responseBuilder.protocol(Protocol.HTTP_1_1);
responseBuilder.message("Fake failure for request " + request.urlString());
responseBuilder.body(ResponseBody.create(MediaType.parse("text"), "Fake Failure"));
return responseBuilder.build();
}
/**
* Get a random number between 0 and 100 in order to determin if the request
* should fail.
*/
private int getRandomPercent() {
int max = 100;
int min = 0;
return this.random.nextInt((max - min) + 1) + min;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment