Java Code Examples for com.google.api.client.http.HttpRequest#setInterceptor()

The following examples show how to use com.google.api.client.http.HttpRequest#setInterceptor() . 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: SnapshotAPIRequest.java    From writelatex-git-bridge with MIT License 6 votes vote down vote up
@Override
protected void onBeforeRequest(
        HttpRequest request
) throws IOException {
    if (oauth2 != null) {
        request.setInterceptor(request1 -> {
            new BasicAuthentication(
                    USERNAME,
                    PASSWORD
            ).intercept(request1);
            oauth2.intercept(request1);
        });
    } else {
        request.setInterceptor(request1 -> {
            new BasicAuthentication(
                    USERNAME,
                    PASSWORD
            ).intercept(request1);
        });
    }
}
 
Example 3
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 4
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 5
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 6
Source File: TrackingHttpRequestInitializer.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(HttpRequest request) throws IOException {
  if (delegate != null) {
    delegate.initialize(request);
  }
  HttpExecuteInterceptor executeInterceptor = request.getInterceptor();
  request.setInterceptor(
      r -> {
        if (executeInterceptor != null) {
          executeInterceptor.intercept(r);
        }
        requests.add(r);
      });
}
 
Example 7
Source File: AbstractGoogleClientTest.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
public void initialize(HttpRequest request) {
  request.setInterceptor(new GZipCheckerInterceptor(gzipDisabled));
}
 
Example 8
Source File: BatchRequestService.java    From connector-sdk with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize(HttpRequest request) throws IOException {
  chainedRequestInitializer.initialize(request);
  request.setInterceptor(req -> eventList.stream().forEach(e -> e.onStart()));
}
 
Example 9
Source File: ClientParametersAuthentication.java    From google-oauth-java-client with Apache License 2.0 4 votes vote down vote up
public void initialize(HttpRequest request) throws IOException {
  request.setInterceptor(this);
}
 
Example 10
Source File: Credential.java    From google-oauth-java-client with Apache License 2.0 4 votes vote down vote up
public void initialize(HttpRequest request) throws IOException {
  request.setInterceptor(this);
  request.setUnsuccessfulResponseHandler(this);
}
 
Example 11
Source File: OAuthParameters.java    From google-oauth-java-client with Apache License 2.0 4 votes vote down vote up
public void initialize(HttpRequest request) throws IOException {
  request.setInterceptor(this);
}
 
Example 12
Source File: GoogleAccountCredential.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize(HttpRequest request) {
  RequestHandler handler = new RequestHandler();
  request.setInterceptor(handler);
  request.setUnsuccessfulResponseHandler(handler);
}
 
Example 13
Source File: BatchRequestTest.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize(HttpRequest request) {
  request.setInterceptor(this);
  initializerCalled = true;
}
 
Example 14
Source File: MediaHttpUploaderTest.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize(HttpRequest request) {
  request.setInterceptor(new TimingInterceptor());
}
 
Example 15
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.setInterceptor(new GZipCheckerInterceptor(gzipDisabled));
}
 
Example 16
Source File: MethodOverride.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
public void initialize(HttpRequest request) {
  request.setInterceptor(this);
}
 
Example 17
Source File: BatchRequest.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
/**
 * Executes all queued HTTP requests in a single call, parses the responses and invokes callbacks.
 *
 * <p>
 * Calling {@link #execute()} executes and clears the queued requests. This means that the
 * {@link BatchRequest} object can be reused to {@link #queue} and {@link #execute()} requests
 * again.
 * </p>
 */
public void execute() throws IOException {
  boolean retryAllowed;
  Preconditions.checkState(!requestInfos.isEmpty());

  // Log a warning if the user is using the global batch endpoint. In the future, we can turn this
  // into a preconditions check.
  if (GLOBAL_BATCH_ENDPOINT.equals(this.batchUrl.toString())) {
    LOGGER.log(Level.WARNING, GLOBAL_BATCH_ENDPOINT_WARNING);
  }

  HttpRequest batchRequest = requestFactory.buildPostRequest(this.batchUrl, null);
  // NOTE: batch does not support gzip encoding
  HttpExecuteInterceptor originalInterceptor = batchRequest.getInterceptor();
  batchRequest.setInterceptor(new BatchInterceptor(originalInterceptor));
  int retriesRemaining = batchRequest.getNumberOfRetries();

  do {
    retryAllowed = retriesRemaining > 0;
    MultipartContent batchContent = new MultipartContent();
    batchContent.getMediaType().setSubType("mixed");
    int contentId = 1;
    for (RequestInfo<?, ?> requestInfo : requestInfos) {
      batchContent.addPart(new MultipartContent.Part(
          new HttpHeaders().setAcceptEncoding(null).set("Content-ID", contentId++),
          new HttpRequestContent(requestInfo.request)));
    }
    batchRequest.setContent(batchContent);
    HttpResponse response = batchRequest.execute();
    BatchUnparsedResponse batchResponse;
    try {
      // Find the boundary from the Content-Type header.
      String boundary = "--" + response.getMediaType().getParameter("boundary");

      // Parse the content stream.
      InputStream contentStream = response.getContent();
      batchResponse =
          new BatchUnparsedResponse(contentStream, boundary, requestInfos, retryAllowed);

      while (batchResponse.hasNext) {
        batchResponse.parseNextResponse();
      }
    } finally {
      response.disconnect();
    }

    List<RequestInfo<?, ?>> unsuccessfulRequestInfos = batchResponse.unsuccessfulRequestInfos;
    if (!unsuccessfulRequestInfos.isEmpty()) {
      requestInfos = unsuccessfulRequestInfos;
    } else {
      break;
    }
    retriesRemaining--;
  } while (retryAllowed);
  requestInfos.clear();
}
 
Example 18
Source File: AppIdentityCredential.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize(HttpRequest request) throws IOException {
  request.setInterceptor(this);
}
 
Example 19
Source File: RetryHttpInitializer.java    From hadoop-connectors with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize(HttpRequest request) {
  // Credential must be the interceptor to fill in accessToken fields.
  request.setInterceptor(credential);

  // Request will be retried if server errors (5XX) or I/O errors are encountered.
  request.setNumberOfRetries(options.getMaxRequestRetries());

  // Set the timeout configurations.
  request.setConnectTimeout(Math.toIntExact(options.getConnectTimeout().toMillis()));
  request.setReadTimeout(Math.toIntExact(options.getReadTimeout().toMillis()));

  // IOExceptions such as "socket timed out" of "insufficient bytes written" will follow a
  // straightforward backoff.
  HttpBackOffIOExceptionHandler exceptionHandler =
      new HttpBackOffIOExceptionHandler(new ExponentialBackOff());
  if (sleeperOverride != null) {
    exceptionHandler.setSleeper(sleeperOverride);
  }

  // Supply a new composite handler for unsuccessful return codes. 401 Unauthorized will be
  // handled by the Credential, 410 Gone will be logged, and 5XX will be handled by a backoff
  // handler.
  LoggingResponseHandler loggingResponseHandler =
      new LoggingResponseHandler(
          new CredentialOrBackoffResponseHandler(),
          exceptionHandler,
          ImmutableSet.of(HttpStatus.SC_GONE, HttpStatus.SC_SERVICE_UNAVAILABLE),
          ImmutableSet.of(HTTP_SC_TOO_MANY_REQUESTS));
  request.setUnsuccessfulResponseHandler(loggingResponseHandler);
  request.setIOExceptionHandler(loggingResponseHandler);

  if (isNullOrEmpty(request.getHeaders().getUserAgent())
      && !isNullOrEmpty(options.getDefaultUserAgent())) {
    logger.atFiner().log(
        "Request is missing a user-agent, adding default value of '%s'",
        options.getDefaultUserAgent());
    request.getHeaders().setUserAgent(options.getDefaultUserAgent());
  }

  request.getHeaders().putAll(options.getHttpHeaders());
}
 
Example 20
Source File: MicrosoftParametersAuthentication.java    From codenvy with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void initialize(HttpRequest request) throws IOException {
  request.setInterceptor(this);
}