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

The following examples show how to use com.google.api.client.http.HttpUnsuccessfulResponseHandler. 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: TestApiClientUtils.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
/**
 * Checks whther the given HttpRequestFactory has been configured for authorization and
 * automatic retries.
 *
 * @param requestFactory The HttpRequestFactory to check.
 */
public static void assertAuthAndRetrySupport(HttpRequestFactory requestFactory) {
  assertTrue(requestFactory.getInitializer() instanceof FirebaseRequestInitializer);
  HttpRequest request;
  try {
    request = requestFactory.buildGetRequest(TEST_URL);
  } catch (IOException e) {
    throw new RuntimeException("Failed to initialize request", e);
  }

  // Verify authorization
  assertTrue(request.getHeaders().getAuthorization().startsWith("Bearer "));

  // Verify retry support
  HttpUnsuccessfulResponseHandler retryHandler = request.getUnsuccessfulResponseHandler();
  assertTrue(retryHandler instanceof RetryHandlerDecorator);
  RetryConfig retryConfig = ((RetryHandlerDecorator) retryHandler).getRetryHandler()
      .getRetryConfig();
  assertEquals(DEFAULT_RETRY_CONFIG.getMaxRetries(), retryConfig.getMaxRetries());
  assertEquals(DEFAULT_RETRY_CONFIG.getMaxIntervalMillis(), retryConfig.getMaxIntervalMillis());
  assertFalse(retryConfig.isRetryOnIOExceptions());
  assertEquals(DEFAULT_RETRY_CONFIG.getRetryStatusCodes(), retryConfig.getRetryStatusCodes());
}
 
Example #3
Source File: RetryInitializerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testRetryOnIOException() throws IOException {
  MockSleeper sleeper = new MockSleeper();
  RetryInitializer initializer = new RetryInitializer(
      retryOnIOAndServiceUnavailableErrors(sleeper));

  CountingLowLevelHttpRequest failingRequest = CountingLowLevelHttpRequest.fromException(
      new IOException("test error"));
  HttpRequest request = TestUtils.createRequest(failingRequest);
  initializer.initialize(request);
  final HttpUnsuccessfulResponseHandler retryHandler = request.getUnsuccessfulResponseHandler();

  try {
    request.execute();
    fail("No exception thrown for HTTP error");
  } catch (IOException e) {
    assertEquals("test error", e.getMessage());
  }

  assertEquals(MAX_RETRIES, sleeper.getCount());
  assertEquals(MAX_RETRIES + 1, failingRequest.getCount());
  assertSame(retryHandler, request.getUnsuccessfulResponseHandler());
}
 
Example #4
Source File: RetryInitializerTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testRetryOnHttpError() throws IOException {
  MockSleeper sleeper = new MockSleeper();
  RetryInitializer initializer = new RetryInitializer(
      retryOnIOAndServiceUnavailableErrors(sleeper));
  CountingLowLevelHttpRequest failingRequest = CountingLowLevelHttpRequest.fromStatus(503);
  HttpRequest request = TestUtils.createRequest(failingRequest);
  initializer.initialize(request);
  final HttpUnsuccessfulResponseHandler retryHandler = request.getUnsuccessfulResponseHandler();

  try {
    request.execute();
    fail("No exception thrown for HTTP error");
  } catch (HttpResponseException e) {
    assertEquals(503, e.getStatusCode());
  }

  assertEquals(MAX_RETRIES, sleeper.getCount());
  assertEquals(MAX_RETRIES + 1, failingRequest.getCount());
  assertSame(retryHandler, request.getUnsuccessfulResponseHandler());
}
 
Example #5
Source File: ApiClientUtilsTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthorizedHttpClient() throws IOException {
  FirebaseApp app = FirebaseApp.initializeApp(TEST_OPTIONS);

  HttpRequestFactory requestFactory = ApiClientUtils.newAuthorizedRequestFactory(app);

  assertTrue(requestFactory.getInitializer() instanceof FirebaseRequestInitializer);
  HttpRequest request = requestFactory.buildGetRequest(TEST_URL);
  assertEquals("Bearer test-token", request.getHeaders().getAuthorization());
  HttpUnsuccessfulResponseHandler retryHandler = request.getUnsuccessfulResponseHandler();
  assertTrue(retryHandler instanceof RetryHandlerDecorator);
  RetryConfig retryConfig = ((RetryHandlerDecorator) retryHandler).getRetryHandler()
      .getRetryConfig();
  assertEquals(4, retryConfig.getMaxRetries());
  assertEquals(60 * 1000, retryConfig.getMaxIntervalMillis());
  assertFalse(retryConfig.isRetryOnIOExceptions());
  assertEquals(retryConfig.getRetryStatusCodes(), ImmutableList.of(500, 503));
}
 
Example #6
Source File: UnsuccessfulResponseHandlerChainerTest.java    From mail-importer with Apache License 2.0 6 votes vote down vote up
@Test
public void testChainOnlyCallsUntilTrue() throws Exception {
  HttpUnsuccessfulResponseHandler handler1 =
      mock(HttpUnsuccessfulResponseHandler.class);
  HttpUnsuccessfulResponseHandler handler2 =
      mock(HttpUnsuccessfulResponseHandler.class);

  when(handler1.handleResponse(
      any(HttpRequest.class), any(HttpResponse.class), anyBoolean()))
      .thenReturn(true);

  chainer.chain(handler1, handler2)
      .handleResponse(httpRequest, httpResponse, SUPPORTS_RETRY);

  verify(handler1)
      .handleResponse(
          any(HttpRequest.class),
          any(HttpResponse.class),
          any(Boolean.TYPE));

  verify(handler2, never())
      .handleResponse(
          any(HttpRequest.class),
          any(HttpResponse.class),
          any(Boolean.TYPE));
}
 
Example #7
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 #8
Source File: UnsuccessfulResponseHandlerChainerTest.java    From mail-importer with Apache License 2.0 6 votes vote down vote up
@Test
public void testChainOfTwo() throws Exception {
  HttpUnsuccessfulResponseHandler handler1 =
      mock(HttpUnsuccessfulResponseHandler.class);
  HttpUnsuccessfulResponseHandler handler2 =
      mock(HttpUnsuccessfulResponseHandler.class);

  chainer.chain(handler1, handler2)
      .handleResponse(httpRequest, httpResponse, SUPPORTS_RETRY);

  verify(handler1)
      .handleResponse(
          any(HttpRequest.class),
          any(HttpResponse.class),
          any(Boolean.TYPE));

  verify(handler2)
      .handleResponse(
          any(HttpRequest.class),
          any(HttpResponse.class),
          any(Boolean.TYPE));
}
 
Example #9
Source File: RetryHttpInitializer.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
/**
 * @param delegateResponseHandler The HttpUnsuccessfulResponseHandler to invoke to really handle
 *     errors.
 * @param delegateIOExceptionHandler The HttpIOExceptionResponseHandler to delegate to.
 * @param responseCodesToLog The set of response codes to log URLs for.
 * @param responseCodesToLogWithRateLimit The set of response codes to log URLs for with reate
 *     limit.
 */
public LoggingResponseHandler(
    HttpUnsuccessfulResponseHandler delegateResponseHandler,
    HttpIOExceptionHandler delegateIOExceptionHandler,
    Set<Integer> responseCodesToLog,
    Set<Integer> responseCodesToLogWithRateLimit) {
  this.delegateResponseHandler = delegateResponseHandler;
  this.delegateIOExceptionHandler = delegateIOExceptionHandler;
  this.responseCodesToLog = ImmutableSet.copyOf(responseCodesToLog);
  this.responseCodesToLogWithRateLimit = ImmutableSet.copyOf(responseCodesToLogWithRateLimit);
}
 
Example #10
Source File: ChainingHttpRequestInitializer.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
private HttpUnsuccessfulResponseHandler makeUnsuccessfulResponseHandler(
    final Iterable<HttpUnsuccessfulResponseHandler> unsuccessfulResponseHandlers) {
  return new HttpUnsuccessfulResponseHandler() {
    @Override
    public boolean handleResponse(HttpRequest request, HttpResponse response,
        boolean supportsRetry) throws IOException {
      for (HttpUnsuccessfulResponseHandler handler : unsuccessfulResponseHandlers) {
        if (handler.handleResponse(request, response, supportsRetry)) {
          return true;
        }
      }
      return false;
    }
  };
}
 
Example #11
Source File: ChainingHttpRequestInitializer.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(HttpRequest request) throws IOException {
  List<HttpIOExceptionHandler> ioExceptionHandlers = new ArrayList<>();
  List<HttpUnsuccessfulResponseHandler> unsuccessfulResponseHandlers = new ArrayList<>();
  List<HttpExecuteInterceptor> interceptors = new ArrayList<>();
  List<HttpResponseInterceptor> responseInterceptors = new ArrayList<>();
  for (HttpRequestInitializer initializer : initializers) {
    initializer.initialize(request);
    if (request.getIOExceptionHandler() != null) {
      ioExceptionHandlers.add(request.getIOExceptionHandler());
      request.setIOExceptionHandler(null);
    }
    if (request.getUnsuccessfulResponseHandler() != null) {
      unsuccessfulResponseHandlers.add(request.getUnsuccessfulResponseHandler());
      request.setUnsuccessfulResponseHandler(null);
    }
    if (request.getInterceptor() != null) {
      interceptors.add(request.getInterceptor());
      request.setInterceptor(null);
    }
    if (request.getResponseInterceptor() != null) {
      responseInterceptors.add(request.getResponseInterceptor());
      request.setResponseInterceptor(null);
    }
  }
  request.setIOExceptionHandler(
      makeIoExceptionHandler(ioExceptionHandlers));
  request.setUnsuccessfulResponseHandler(
      makeUnsuccessfulResponseHandler(unsuccessfulResponseHandlers));
  request.setInterceptor(
      makeInterceptor(interceptors));
  request.setResponseInterceptor(
      makeResponseInterceptor(responseInterceptors));
}
 
Example #12
Source File: UnsuccessfulResponseHandlerChainerTest.java    From mail-importer with Apache License 2.0 5 votes vote down vote up
@Test
public void testChainOfOne() throws Exception {
  HttpUnsuccessfulResponseHandler handler =
      mock(HttpUnsuccessfulResponseHandler.class);

  chainer.chain(handler)
      .handleResponse(httpRequest, httpResponse, SUPPORTS_RETRY);

  verify(handler)
      .handleResponse(
          any(HttpRequest.class),
          any(HttpResponse.class),
          any(Boolean.TYPE));
}
 
Example #13
Source File: UnsuccessfulResponseHandlerChainer.java    From mail-importer with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new {@link HttpUnsuccessfulResponseHandler} that runs all of
 * the given handlers in order until one of them returns {@code true}.
 *
 * @param handlers the handlers to run. Note that {@code null} values are
 *     skipped.
 */
public HttpUnsuccessfulResponseHandler chain(
    HttpUnsuccessfulResponseHandler... handlers) {
  return (unsuccessfulRequest, response, supportsRetry) -> {
    boolean retry = false;
    for (int i = 0; i < handlers.length && !retry; i++) {
      if (handlers[i] != null) {
        retry = handlers[i].handleResponse(
            unsuccessfulRequest, response, supportsRetry);
      }
    }

    return retry;
  };
}
 
Example #14
Source File: ApiClientUtilsTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnauthorizedHttpClient() throws IOException {
  FirebaseApp app = FirebaseApp.initializeApp(TEST_OPTIONS);

  HttpRequestFactory requestFactory = ApiClientUtils.newUnauthorizedRequestFactory(app);

  assertNull(requestFactory.getInitializer());
  HttpRequest request = requestFactory.buildGetRequest(TEST_URL);
  assertNull(request.getHeaders().getAuthorization());
  HttpUnsuccessfulResponseHandler retryHandler = request.getUnsuccessfulResponseHandler();
  assertNull(retryHandler);
}
 
Example #15
Source File: ApiClientUtilsTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthorizedHttpClientWithoutRetry() throws IOException {
  FirebaseApp app = FirebaseApp.initializeApp(TEST_OPTIONS);

  HttpRequestFactory requestFactory = ApiClientUtils.newAuthorizedRequestFactory(app, null);

  assertTrue(requestFactory.getInitializer() instanceof FirebaseRequestInitializer);
  HttpRequest request = requestFactory.buildGetRequest(TEST_URL);
  assertEquals("Bearer test-token", request.getHeaders().getAuthorization());
  HttpUnsuccessfulResponseHandler retryHandler = request.getUnsuccessfulResponseHandler();
  assertFalse(retryHandler instanceof RetryHandlerDecorator);
}
 
Example #16
Source File: RetryInitializerTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testMaxRetriesCountIsCumulative() throws IOException {
  MockSleeper sleeper = new MockSleeper();
  RetryInitializer initializer = new RetryInitializer(
      retryOnIOAndServiceUnavailableErrors(sleeper));

  final AtomicInteger counter = new AtomicInteger(0);
  MockLowLevelHttpRequest failingRequest = new MockLowLevelHttpRequest(){
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      if (counter.getAndIncrement() < 2) {
        throw new IOException("test error");
      } else {
        return new MockLowLevelHttpResponse().setStatusCode(503).setZeroContent();
      }
    }
  };
  HttpRequest request = TestUtils.createRequest(failingRequest);
  initializer.initialize(request);
  final HttpUnsuccessfulResponseHandler retryHandler = request.getUnsuccessfulResponseHandler();

  try {
    request.execute();
    fail("No exception thrown for HTTP error");
  } catch (HttpResponseException e) {
    assertEquals(503, e.getStatusCode());
  }

  assertEquals(MAX_RETRIES, sleeper.getCount());
  assertEquals(MAX_RETRIES + 1, counter.get());
  assertSame(retryHandler, request.getUnsuccessfulResponseHandler());
}
 
Example #17
Source File: UnsuccessfulResponseHandlerChainerTest.java    From mail-importer with Apache License 2.0 4 votes vote down vote up
@Test
public void testChainOfZero() throws Exception {
  HttpUnsuccessfulResponseHandler handler = chainer.chain();

  handler.handleResponse(httpRequest, httpResponse, SUPPORTS_RETRY);
}
 
Example #18
Source File: RetryInitializer.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
private HttpUnsuccessfulResponseHandler newUnsuccessfulResponseHandler(HttpRequest request) {
  RetryUnsuccessfulResponseHandler retryHandler = new RetryUnsuccessfulResponseHandler(
      retryConfig);
  return new RetryHandlerDecorator(retryHandler, request);
}