com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler Java Examples

The following examples show how to use com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RetryHttpInitializerWrapper.java    From deployment-examples with MIT License 6 votes vote down vote up
/** Initializes the given request. */
@Override
public final void initialize(final HttpRequest request) {
  request.setReadTimeout(2 * ONEMINITUES); // 2 minutes read timeout
  final HttpUnsuccessfulResponseHandler backoffHandler =
      new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff()).setSleeper(sleeper);
  request.setInterceptor(wrappedCredential);
  request.setUnsuccessfulResponseHandler(
      (request1, response, supportsRetry) -> {
        if (wrappedCredential.handleResponse(request1, response, supportsRetry)) {
          // If credential decides it can handle it, the return code or message indicated
          // something specific to authentication, and no backoff is desired.
          return true;
        } else if (backoffHandler.handleResponse(request1, response, supportsRetry)) {
          // Otherwise, we defer to the judgement of our internal backoff handler.
          LOG.info("Retrying " + request1.getUrl().toString());
          return true;
        } else {
          return false;
        }
      });
  request.setIOExceptionHandler(
      new HttpBackOffIOExceptionHandler(new ExponentialBackOff()).setSleeper(sleeper));
}
 
Example #2
Source File: RetryHttpInitializerWrapper.java    From beam with Apache License 2.0 6 votes vote down vote up
/** Initializes the given request. */
@Override
public final void initialize(final HttpRequest request) {
  request.setReadTimeout(2 * ONEMINITUES); // 2 minutes read timeout
  final HttpUnsuccessfulResponseHandler backoffHandler =
      new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff()).setSleeper(sleeper);
  request.setInterceptor(wrappedCredential);
  request.setUnsuccessfulResponseHandler(
      (request1, response, supportsRetry) -> {
        if (wrappedCredential.handleResponse(request1, response, supportsRetry)) {
          // If credential decides it can handle it, the return code or message indicated
          // something specific to authentication, and no backoff is desired.
          return true;
        } else if (backoffHandler.handleResponse(request1, response, supportsRetry)) {
          // Otherwise, we defer to the judgement of our internal backoff handler.
          LOG.info("Retrying " + request1.getUrl().toString());
          return true;
        } else {
          return false;
        }
      });
  request.setIOExceptionHandler(
      new HttpBackOffIOExceptionHandler(new ExponentialBackOff()).setSleeper(sleeper));
}
 
Example #3
Source File: GoogleCredentials.java    From halyard with Apache License 2.0 5 votes vote down vote up
public static HttpRequestInitializer retryRequestInitializer() {
  return request -> {
    request.setConnectTimeout((int) TimeUnit.MINUTES.toMillis(2));
    request.setReadTimeout((int) TimeUnit.MINUTES.toMillis(2));
    request.setUnsuccessfulResponseHandler(
        new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff()));
  };
}
 
Example #4
Source File: GoogleCredentials.java    From halyard with Apache License 2.0 5 votes vote down vote up
public static HttpRequestInitializer setHttpTimeout(
    final com.google.auth.oauth2.GoogleCredentials credentials) {
  return new HttpCredentialsAdapter(credentials) {
    public void initialize(HttpRequest request) throws IOException {
      super.initialize(request);
      request.setConnectTimeout((int) TimeUnit.MINUTES.toMillis(2));
      request.setReadTimeout((int) TimeUnit.MINUTES.toMillis(2));
      request.setUnsuccessfulResponseHandler(
          new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff()));
    }
  };
}
 
Example #5
Source File: GmailService.java    From mail-importer with Apache License 2.0 5 votes vote down vote up
Gmail getServiceWithRetries() {
  HttpRequestInitializer httpRequestInitializer =
      request -> {
        credential.initialize(request);
        new UnsuccessfulResponseHandlerChainer().chain(
            request.getUnsuccessfulResponseHandler(),
            new HttpBackOffUnsuccessfulResponseHandler(
                backOffProvider.get()));
      };

  return new Gmail.Builder(httpTransport, jsonFactory, httpRequestInitializer)
      .setApplicationName(GmailServiceModule.APP_NAME)
      .build();
}
 
Example #6
Source File: GoogleUtils.java    From kork with Apache License 2.0 5 votes vote down vote up
static HttpRequestInitializer setTimeoutsAndRetryBehavior(final GoogleCredentials credentials) {
  return new HttpCredentialsAdapter(credentials) {
    public void initialize(HttpRequest request) throws IOException {
      super.initialize(request);
      request.setConnectTimeout(CONNECT_TIMEOUT);
      request.setReadTimeout(READ_TIMEOUT);
      HttpBackOffUnsuccessfulResponseHandler unsuccessfulResponseHandler =
          new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff());
      unsuccessfulResponseHandler.setBackOffRequired(
          HttpBackOffUnsuccessfulResponseHandler.BackOffRequired.ON_SERVER_ERROR);
      request.setUnsuccessfulResponseHandler(unsuccessfulResponseHandler);
    }
  };
}
 
Example #7
Source File: CredentialFactory.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(HttpRequest httpRequest) throws IOException {
  if (credential != null) {
    httpRequest.setInterceptor(credential);
  }
  httpRequest.setIOExceptionHandler(
      new HttpBackOffIOExceptionHandler(new ExponentialBackOff()));
  httpRequest.setUnsuccessfulResponseHandler(
      new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff()));
}
 
Example #8
Source File: RetryHttpInitializer.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
public CredentialOrBackoffResponseHandler() {
  HttpBackOffUnsuccessfulResponseHandler errorCodeHandler =
      new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff());
  errorCodeHandler.setBackOffRequired(
      response ->
          BASE_HTTP_BACKOFF_REQUIRED.isRequired(response)
              || response.getStatusCode() == HTTP_SC_TOO_MANY_REQUESTS);
  if (sleeperOverride != null) {
    errorCodeHandler.setSleeper(sleeperOverride);
  }
  this.delegateHandler = errorCodeHandler;
}
 
Example #9
Source File: BaseApiService.java    From connector-sdk with Apache License 2.0 4 votes vote down vote up
public LoggingResponseHandler(RetryPolicy retryPolicy, BackOff backOff) {
  delegate =
      new HttpBackOffUnsuccessfulResponseHandler(backOff)
          .setBackOffRequired(r -> retryPolicy.isRetryableStatusCode(r.getStatusCode()));
}
 
Example #10
Source File: HttpEventPublisher.java    From DataflowTemplates with Apache License 2.0 4 votes vote down vote up
/**
 * Executes a POST for the list of {@link SplunkEvent} objects into Splunk's Http Event Collector
 * endpoint.
 *
 * @param events List of {@link SplunkEvent}s
 * @return {@link HttpResponse} for the POST.
 */
public HttpResponse execute(List<SplunkEvent> events) throws IOException {

  HttpContent content = getContent(events);
  HttpRequest request = requestFactory().buildPostRequest(genericUrl(), content);

  HttpBackOffUnsuccessfulResponseHandler responseHandler =
      new HttpBackOffUnsuccessfulResponseHandler(getConfiguredBackOff());

  responseHandler.setBackOffRequired(BackOffRequired.ON_SERVER_ERROR);

  request.setUnsuccessfulResponseHandler(responseHandler);
  setHeaders(request, token());

  return request.execute();
}
 
Example #11
Source File: ForceOAuthClient.java    From salesforce-jdbc with MIT License 4 votes vote down vote up
private HttpBackOffUnsuccessfulResponseHandler buildUnsuccessfulResponseHandler() {
    return new HttpBackOffUnsuccessfulResponseHandler(getBackOff());
}
 
Example #12
Source File: DriveSession.java    From cyberduck with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void initialize(final HttpRequest request) {
    super.initialize(request);
    request.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff())
        .setBackOffRequired(HttpBackOffUnsuccessfulResponseHandler.BackOffRequired.ALWAYS));
}
 
Example #13
Source File: HttpEventPublisher.java    From beam with Apache License 2.0 4 votes vote down vote up
/**
 * Executes a POST for the list of {@link SplunkEvent} objects into Splunk's Http Event Collector
 * endpoint.
 *
 * @param events list of {@link SplunkEvent}s
 * @return {@link HttpResponse} for the POST
 */
HttpResponse execute(List<SplunkEvent> events) throws IOException {

  HttpContent content = getContent(events);
  HttpRequest request = requestFactory().buildPostRequest(genericUrl(), content);

  HttpBackOffUnsuccessfulResponseHandler responseHandler =
      new HttpBackOffUnsuccessfulResponseHandler(getConfiguredBackOff());

  responseHandler.setBackOffRequired(BackOffRequired.ON_SERVER_ERROR);

  request.setUnsuccessfulResponseHandler(responseHandler);
  setHeaders(request, token());

  return request.execute();
}
 
Example #14
Source File: HttpExample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/** Publish an event or state message using Cloud IoT Core via the HTTP API. */
protected static void getConfig(
    String urlPath,
    String token,
    String projectId,
    String cloudRegion,
    String registryId,
    String deviceId,
    String version)
    throws IOException {
  // Build the resource path of the device that is going to be authenticated.
  String devicePath =
      String.format(
          "projects/%s/locations/%s/registries/%s/devices/%s",
          projectId, cloudRegion, registryId, deviceId);
  urlPath = urlPath + devicePath + "/config?local_version=" + version;

  HttpRequestFactory requestFactory =
      HTTP_TRANSPORT.createRequestFactory(
          new HttpRequestInitializer() {
            @Override
            public void initialize(HttpRequest request) {
              request.setParser(new JsonObjectParser(JSON_FACTORY));
            }
          });

  final HttpRequest req = requestFactory.buildGetRequest(new GenericUrl(urlPath));
  HttpHeaders heads = new HttpHeaders();

  heads.setAuthorization(String.format("Bearer %s", token));
  heads.setContentType("application/json; charset=UTF-8");
  heads.setCacheControl("no-cache");

  req.setHeaders(heads);
  ExponentialBackOff backoff =
      new ExponentialBackOff.Builder()
          .setInitialIntervalMillis(500)
          .setMaxElapsedTimeMillis(900000)
          .setMaxIntervalMillis(6000)
          .setMultiplier(1.5)
          .setRandomizationFactor(0.5)
          .build();
  req.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));
  HttpResponse res = req.execute();
  System.out.println(res.getStatusCode());
  System.out.println(res.getStatusMessage());
  InputStream in = res.getContent();

  System.out.println(CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8.name())));
}
 
Example #15
Source File: HttpExample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/** Publish an event or state message using Cloud IoT Core via the HTTP API. */
protected static void publishMessage(
    String payload,
    String urlPath,
    String messageType,
    String token,
    String projectId,
    String cloudRegion,
    String registryId,
    String deviceId)
    throws IOException, JSONException {
  // Build the resource path of the device that is going to be authenticated.
  String devicePath =
      String.format(
          "projects/%s/locations/%s/registries/%s/devices/%s",
          projectId, cloudRegion, registryId, deviceId);
  String urlSuffix = "event".equals(messageType) ? "publishEvent" : "setState";

  // Data sent through the wire has to be base64 encoded.
  Base64.Encoder encoder = Base64.getEncoder();

  String encPayload = encoder.encodeToString(payload.getBytes(StandardCharsets.UTF_8.name()));

  urlPath = urlPath + devicePath + ":" + urlSuffix;

  final HttpRequestFactory requestFactory =
      HTTP_TRANSPORT.createRequestFactory(
          new HttpRequestInitializer() {
            @Override
            public void initialize(HttpRequest request) {
              request.setParser(new JsonObjectParser(JSON_FACTORY));
            }
          });

  HttpHeaders heads = new HttpHeaders();
  heads.setAuthorization(String.format("Bearer %s", token));
  heads.setContentType("application/json; charset=UTF-8");
  heads.setCacheControl("no-cache");

  // Add post data. The data sent depends on whether we're updating state or publishing events.
  JSONObject data = new JSONObject();
  if ("event".equals(messageType)) {
    data.put("binary_data", encPayload);
  } else {
    JSONObject state = new JSONObject();
    state.put("binary_data", encPayload);
    data.put("state", state);
  }

  ByteArrayContent content =
      new ByteArrayContent(
          "application/json", data.toString().getBytes(StandardCharsets.UTF_8.name()));

  final HttpRequest req = requestFactory.buildGetRequest(new GenericUrl(urlPath));
  req.setHeaders(heads);
  req.setContent(content);
  req.setRequestMethod("POST");
  ExponentialBackOff backoff =
      new ExponentialBackOff.Builder()
          .setInitialIntervalMillis(500)
          .setMaxElapsedTimeMillis(900000)
          .setMaxIntervalMillis(6000)
          .setMultiplier(1.5)
          .setRandomizationFactor(0.5)
          .build();
  req.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));

  HttpResponse res = req.execute();
  System.out.println(res.getStatusCode());
  System.out.println(res.getStatusMessage());
}
 
Example #16
Source File: MediaHttpUploaderTest.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
public void initialize(HttpRequest request) {
  request.setIOExceptionHandler(new HttpBackOffIOExceptionHandler(BackOff.ZERO_BACKOFF));
  request.setUnsuccessfulResponseHandler(
      new HttpBackOffUnsuccessfulResponseHandler(BackOff.ZERO_BACKOFF));
}