Skip to content

Instantly share code, notes, and snippets.

@richieforeman
Last active April 20, 2020 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richieforeman/b6017796464788c3d985 to your computer and use it in GitHub Desktop.
Save richieforeman/b6017796464788c3d985 to your computer and use it in GitHub Desktop.
exp.java
//// First, Implement an interface to intercept the HTTP Request before it goes out.
package com.google.java_scratch;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.http.HttpBackOffIOExceptionHandler;
import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler;
import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler.BackOffRequired;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpUnsuccessfulResponseHandler;
import com.google.api.client.util.ExponentialBackOff;
import java.io.IOException;
/**
* Google Java lib only allows for one HTTP Initializer per service.
* - Wrap credentials initializer
* - Handle retry
*/
public class ExponentialBackoffRequestInitializer implements HttpRequestInitializer {
private final Credential googleCredential;
private static final ExponentialBackOff backoff =
new ExponentialBackOff.Builder()
.setInitialIntervalMillis(500)
.setMaxElapsedTimeMillis(900000)
.setMaxIntervalMillis(6000)
.setMultiplier(1.5)
.setRandomizationFactor(0.5)
.build();
public ExponentialBackoffRequestInitializer(Credential googleCredential) {
this.googleCredential = googleCredential;
}
@Override
public void initialize(HttpRequest request) {
final HttpBackOffUnsuccessfulResponseHandler backoffHandler =
new HttpBackOffUnsuccessfulResponseHandler(backoff);
// Attach credentials to request.
request.setInterceptor(googleCredential);
backoffHandler.setBackOffRequired(new BackOffRequired() {
public boolean isRequired(HttpResponse response) {
return (response.getStatusCode() / 100 == 5)
|| (response.getStatusCode() == 403);
}
});
// Override unsuccessful response handler.
request.setUnsuccessfulResponseHandler(new HttpUnsuccessfulResponseHandler() {
@Override
public boolean handleResponse(
HttpRequest request, HttpResponse response, boolean supportsRetry) throws IOException {
if (googleCredential.handleResponse(request, response, supportsRetry)) {
// credentials returned success.
return true;
} else if (backoffHandler.handleResponse(request, response, supportsRetry)) {
return true;
} else {
return false;
}
}
});
request.setIOExceptionHandler(new HttpBackOffIOExceptionHandler(backoff));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment