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

The following examples show how to use com.google.api.client.http.HttpRequest#setResponseInterceptor() . 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: HttpHelper.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
<T> void makeRequest(
    HttpRequest baseRequest,
    T parsedResponseInstance,
    String requestIdentifier,
    String requestIdentifierDescription) throws FirebaseProjectManagementException {
  HttpResponse response = null;
  try {
    baseRequest.getHeaders().set(CLIENT_VERSION_HEADER, clientVersion);
    baseRequest.setParser(new JsonObjectParser(jsonFactory));
    baseRequest.setResponseInterceptor(interceptor);
    response = baseRequest.execute();
    jsonFactory.createJsonParser(response.getContent(), Charsets.UTF_8)
        .parseAndClose(parsedResponseInstance);
  } catch (Exception e) {
    handleError(requestIdentifier, requestIdentifierDescription, e);
  } finally {
    disconnectQuietly(response);
  }
}
 
Example 2
Source File: CryptoSigners.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] sign(byte[] payload) throws IOException {
  String encodedUrl = String.format(IAM_SIGN_BLOB_URL, serviceAccount);
  HttpResponse response = null;
  String encodedPayload = BaseEncoding.base64().encode(payload);
  Map<String, String> content = ImmutableMap.of("bytesToSign", encodedPayload);
  try {
    HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(encodedUrl),
        new JsonHttpContent(jsonFactory, content));
    request.setParser(new JsonObjectParser(jsonFactory));
    request.setResponseInterceptor(interceptor);
    response = request.execute();
    SignBlobResponse parsed = response.parseAs(SignBlobResponse.class);
    return BaseEncoding.base64().decode(parsed.signature);
  } finally {
    if (response != null) {
      try {
        response.disconnect();
      } catch (IOException ignored) {
        // Ignored
      }
    }
  }
}
 
Example 3
Source File: FirebaseInstanceId.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
private CallableOperation<Void, FirebaseInstanceIdException> deleteInstanceIdOp(
    final String instanceId) {
  checkArgument(!Strings.isNullOrEmpty(instanceId), "instance ID must not be null or empty");
  return new CallableOperation<Void, FirebaseInstanceIdException>() {
    @Override
    protected Void execute() throws FirebaseInstanceIdException {
      String url = String.format(
          "%s/project/%s/instanceId/%s", IID_SERVICE_URL, projectId, instanceId);
      HttpResponse response = null;
      try {
        HttpRequest request = requestFactory.buildDeleteRequest(new GenericUrl(url));
        request.setParser(new JsonObjectParser(jsonFactory));
        request.setResponseInterceptor(interceptor);
        response = request.execute();
        ByteStreams.exhaust(response.getContent());
      } catch (Exception e) {
        handleError(instanceId, e);
      } finally {
        disconnectQuietly(response);
      }
      return null;
    }
  };
}
 
Example 4
Source File: FirebaseMessagingClientImpl.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
private String sendSingleRequest(Message message, boolean dryRun) throws IOException {
  HttpRequest request = requestFactory.buildPostRequest(
      new GenericUrl(fcmSendUrl),
      new JsonHttpContent(jsonFactory, message.wrapForTransport(dryRun)));
  setCommonFcmHeaders(request.getHeaders());
  request.setParser(new JsonObjectParser(jsonFactory));
  request.setResponseInterceptor(responseInterceptor);
  HttpResponse response = request.execute();
  try {
    MessagingServiceResponse parsed = new MessagingServiceResponse();
    jsonFactory.createJsonParser(response.getContent()).parseAndClose(parsed);
    return parsed.getMessageId();
  } finally {
    ApiClientUtils.disconnectQuietly(response);
  }
}
 
Example 5
Source File: InstanceIdClientImpl.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
private TopicManagementResponse sendInstanceIdRequest(
    String topic, List<String> registrationTokens, String path) throws IOException {
  String url = String.format("%s/%s", IID_HOST, path);
  Map<String, Object> payload = ImmutableMap.of(
      "to", getPrefixedTopic(topic),
      "registration_tokens", registrationTokens
  );
  HttpResponse response = null;
  try {
    HttpRequest request = requestFactory.buildPostRequest(
        new GenericUrl(url), new JsonHttpContent(jsonFactory, payload));
    request.getHeaders().set("access_token_auth", "true");
    request.setParser(new JsonObjectParser(jsonFactory));
    request.setResponseInterceptor(responseInterceptor);
    response = request.execute();

    JsonParser parser = jsonFactory.createJsonParser(response.getContent());
    InstanceIdServiceResponse parsedResponse = new InstanceIdServiceResponse();
    parser.parse(parsedResponse);
    return new TopicManagementResponse(parsedResponse.results);
  } finally {
    ApiClientUtils.disconnectQuietly(response);
  }
}
 
Example 6
Source File: LoggingHttpRequestInitializer.java    From googleads-shopping-samples with Apache License 2.0 6 votes vote down vote up
public void initialize(HttpRequest request) throws IOException {
  if (wrapped != null) {
    wrapped.initialize(request);
  }
  request.setLoggingEnabled(true);
  request.setCurlLoggingEnabled(false);
  request.setContentLoggingLimit(Integer.MAX_VALUE);
  request.setResponseInterceptor(
      new HttpResponseInterceptor() {
        private HttpResponseInterceptor wrapped = null;

        public void interceptResponse(HttpResponse response) throws IOException {
          if (wrapped != null) {
            wrapped.interceptResponse(response);
          }
          response.setLoggingEnabled(true);
          response.setContentLoggingLimit(Integer.MAX_VALUE);
        }

        public HttpResponseInterceptor setWrapped(HttpResponseInterceptor toWrap) {
          this.wrapped = toWrap;
          return this;
        }
      }.setWrapped(request.getResponseInterceptor()));
}
 
Example 7
Source File: FirebaseMessagingClientImpl.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private HttpRequestInitializer getBatchRequestInitializer() {
  return new HttpRequestInitializer() {
    @Override
    public void initialize(HttpRequest request) throws IOException {
      HttpRequestInitializer initializer = requestFactory.getInitializer();
      if (initializer != null) {
        initializer.initialize(request);
      }
      request.setResponseInterceptor(responseInterceptor);
    }
  };
}
 
Example 8
Source File: RetryHttpRequestInitializer.java    From beam with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(HttpRequest request) throws IOException {
  // Set a timeout for hanging-gets.
  // TODO: Do this exclusively for work requests.
  request.setReadTimeout(HANGING_GET_TIMEOUT_SEC * 1000);
  request.setWriteTimeout(this.writeTimeout);

  LoggingHttpBackOffHandler loggingHttpBackOffHandler =
      new LoggingHttpBackOffHandler(
          sleeper,
          // Back off on retryable http errors and IOExceptions.
          // A back-off multiplier of 2 raises the maximum request retrying time
          // to approximately 5 minutes (keeping other back-off parameters to
          // their default values).
          new ExponentialBackOff.Builder().setNanoClock(nanoClock).setMultiplier(2).build(),
          new ExponentialBackOff.Builder().setNanoClock(nanoClock).setMultiplier(2).build(),
          ignoredResponseCodes,
          this.customHttpErrors);

  request.setUnsuccessfulResponseHandler(loggingHttpBackOffHandler);
  request.setIOExceptionHandler(loggingHttpBackOffHandler);

  // Set response initializer
  if (responseInterceptor != null) {
    request.setResponseInterceptor(responseInterceptor);
  }
}
 
Example 9
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 10
Source File: AbstractGoogleClientRequest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
/** Create a request suitable for use against this service. */
private HttpRequest buildHttpRequest(boolean usingHead) throws IOException {
  Preconditions.checkArgument(uploader == null);
  Preconditions.checkArgument(!usingHead || requestMethod.equals(HttpMethods.GET));
  String requestMethodToUse = usingHead ? HttpMethods.HEAD : requestMethod;
  final HttpRequest httpRequest = getAbstractGoogleClient()
      .getRequestFactory().buildRequest(requestMethodToUse, buildHttpRequestUrl(), httpContent);
  new MethodOverride().intercept(httpRequest);
  httpRequest.setParser(getAbstractGoogleClient().getObjectParser());
  // custom methods may use POST with no content but require a Content-Length header
  if (httpContent == null && (requestMethod.equals(HttpMethods.POST)
      || requestMethod.equals(HttpMethods.PUT) || requestMethod.equals(HttpMethods.PATCH))) {
    httpRequest.setContent(new EmptyContent());
  }
  httpRequest.getHeaders().putAll(requestHeaders);
  if (!disableGZipContent) {
    httpRequest.setEncoding(new GZipEncoding());
  }
  httpRequest.setResponseReturnRawInputStream(returnRawInputStream);
  final HttpResponseInterceptor responseInterceptor = httpRequest.getResponseInterceptor();
  httpRequest.setResponseInterceptor(new HttpResponseInterceptor() {

    public void interceptResponse(HttpResponse response) throws IOException {
      if (responseInterceptor != null) {
        responseInterceptor.interceptResponse(response);
      }
      if (!response.isSuccessStatusCode() && httpRequest.getThrowExceptionOnExecuteError()) {
        throw newExceptionOnError(response);
      }
    }
  });
  return httpRequest;
}