Java Code Examples for com.google.api.client.http.HttpResponseException#Builder

The following examples show how to use com.google.api.client.http.HttpResponseException#Builder . 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: StackdriverWriterTest.java    From java-monitoring-client-library with Apache License 2.0 6 votes vote down vote up
@Test
public void registerMetric_fetchesStackdriverDefinition() throws Exception {
  // Stackdriver throws an Exception with the status message "ALREADY_EXISTS" when you try to
  // register a metric that's already been registered, so we fake one here.
  ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes(UTF_8));
  HttpResponse response = GoogleJsonResponseExceptionHelper.createHttpResponse(400, inputStream);
  HttpResponseException.Builder httpResponseExceptionBuilder =
      new HttpResponseException.Builder(response);
  httpResponseExceptionBuilder.setStatusCode(400);
  httpResponseExceptionBuilder.setStatusMessage("ALREADY_EXISTS");
  GoogleJsonResponseException exception =
      new GoogleJsonResponseException(httpResponseExceptionBuilder, null);
  when(metricDescriptorCreate.execute()).thenThrow(exception);
  StackdriverWriter writer =
      new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);

  writer.registerMetric(metric);

  verify(client.projects().metricDescriptors().get("metric")).execute();
}
 
Example 2
Source File: StackdriverWriterTest.java    From java-monitoring-client-library with Apache License 2.0 6 votes vote down vote up
@Test
public void registerMetric_rethrowsException() throws Exception {
  ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes(UTF_8));
  HttpResponse response = GoogleJsonResponseExceptionHelper.createHttpResponse(400, inputStream);
  HttpResponseException.Builder httpResponseExceptionBuilder =
      new HttpResponseException.Builder(response);
  httpResponseExceptionBuilder.setStatusCode(404);
  GoogleJsonResponseException exception =
      new GoogleJsonResponseException(httpResponseExceptionBuilder, null);
  when(metricDescriptorCreate.execute()).thenThrow(exception);
  StackdriverWriter writer =
      new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);

  assertThrows(GoogleJsonResponseException.class, () -> writer.registerMetric(metric));
  assertThat(exception.getStatusCode()).isEqualTo(404);
}
 
Example 3
Source File: StackdriverWriterTest.java    From java-monitoring-client-library with Apache License 2.0 6 votes vote down vote up
@Test
public void getEncodedTimeSeries_nullLabels_encodes() throws Exception {
  ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes(UTF_8));
  HttpResponse response = GoogleJsonResponseExceptionHelper.createHttpResponse(400, inputStream);
  HttpResponseException.Builder httpResponseExceptionBuilder =
      new HttpResponseException.Builder(response);
  httpResponseExceptionBuilder.setStatusCode(400);
  httpResponseExceptionBuilder.setStatusMessage("ALREADY_EXISTS");
  GoogleJsonResponseException exception =
      new GoogleJsonResponseException(httpResponseExceptionBuilder, null);
  when(metricDescriptorCreate.execute()).thenThrow(exception);
  when(metricDescriptorGet.execute())
      .thenReturn(new MetricDescriptor().setName("foo").setLabels(null));
  StackdriverWriter writer =
      new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);
  writer.registerMetric(metric);

  TimeSeries timeSeries =
      writer.getEncodedTimeSeries(
          MetricPoint.create(metric, ImmutableList.of("foo"), Instant.ofEpochMilli(1337), 10L));

  assertThat(timeSeries.getMetric().getLabels()).isEmpty();
}
 
Example 4
Source File: KubernetesGCPServiceAccountSecretManagerTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldHandlePermissionDenied() throws IOException {
  when(serviceAccountKeyManager.serviceAccountExists(anyString())).thenReturn(true);

  final GoogleJsonResponseException permissionDenied = new GoogleJsonResponseException(
      new HttpResponseException.Builder(403, "Forbidden", new HttpHeaders()),
      new GoogleJsonError().set("status", "PERMISSION_DENIED"));

  doThrow(permissionDenied).when(serviceAccountKeyManager).createJsonKey(any());
  doThrow(permissionDenied).when(serviceAccountKeyManager).createP12Key(any());

  exception.expect(InvalidExecutionException.class);
  exception.expectMessage(String.format(
      "Permission denied when creating keys for service account: %s. Styx needs to be Service Account Key Admin.",
      SERVICE_ACCOUNT));

  sut.ensureServiceAccountKeySecret(WORKFLOW_ID.toString(), SERVICE_ACCOUNT);
}
 
Example 5
Source File: KubernetesGCPServiceAccountSecretManagerTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldHandleTooManyKeysCreated() throws IOException {
  when(serviceAccountKeyManager.serviceAccountExists(anyString())).thenReturn(true);

  final GoogleJsonResponseException resourceExhausted = new GoogleJsonResponseException(
      new HttpResponseException.Builder(429, "RESOURCE_EXHAUSTED", new HttpHeaders()),
      new GoogleJsonError().set("status", "RESOURCE_EXHAUSTED"));

  doThrow(resourceExhausted).when(serviceAccountKeyManager).createJsonKey(any());
  doThrow(resourceExhausted).when(serviceAccountKeyManager).createP12Key(any());

  exception.expect(InvalidExecutionException.class);
  exception.expectMessage(String.format(
      "Maximum number of keys on service account reached: %s. Styx requires 4 keys to operate.",
      SERVICE_ACCOUNT));

  sut.ensureServiceAccountKeySecret(WORKFLOW_ID.toString(), SERVICE_ACCOUNT);
}
 
Example 6
Source File: KmsConnectionImplTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private static GoogleJsonResponseException createNotFoundException() throws Exception {
  ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes(UTF_8));
  HttpResponse response = GoogleJsonResponseExceptionHelper.createHttpResponse(404, inputStream);
  HttpResponseException.Builder httpResponseExceptionBuilder =
      new HttpResponseException.Builder(response);
  httpResponseExceptionBuilder.setStatusCode(404);
  httpResponseExceptionBuilder.setStatusMessage("NOT_FOUND");
  return new GoogleJsonResponseException(httpResponseExceptionBuilder, null);
}
 
Example 7
Source File: GoogleCloudStorageExceptions.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
public static GoogleJsonResponseException createJsonResponseException(
    GoogleJsonError e, HttpHeaders responseHeaders) {
  if (e != null) {
    return new GoogleJsonResponseException(
        new HttpResponseException.Builder(e.getCode(), e.getMessage(), responseHeaders), e);
  }
  return null;
}
 
Example 8
Source File: TokenResponseException.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new instance of {@link TokenResponseException}.
 *
 * <p>
 * If there is a JSON error response, it is parsed using {@link TokenErrorResponse}, which can be
 * inspected using {@link #getDetails()}. Otherwise, the full response content is read and
 * included in the exception message.
 * </p>
 *
 * @param jsonFactory JSON factory
 * @param response HTTP response
 * @return new instance of {@link TokenErrorResponse}
 */
public static TokenResponseException from(JsonFactory jsonFactory, HttpResponse response) {
  HttpResponseException.Builder builder = new HttpResponseException.Builder(
      response.getStatusCode(), response.getStatusMessage(), response.getHeaders());
  // details
  Preconditions.checkNotNull(jsonFactory);
  TokenErrorResponse details = null;
  String detailString = null;
  String contentType = response.getContentType();
  try {
    if (!response.isSuccessStatusCode() && contentType != null && response.getContent() != null
        && HttpMediaType.equalsIgnoreParameters(Json.MEDIA_TYPE, contentType)) {
      details = new JsonObjectParser(jsonFactory).parseAndClose(
          response.getContent(), response.getContentCharset(), TokenErrorResponse.class);
      detailString = details.toPrettyString();
    } else {
      detailString = response.parseAsString();
    }
  } catch (IOException exception) {
    // it would be bad to throw an exception while throwing an exception
    exception.printStackTrace();
  }
  // message
  StringBuilder message = HttpResponseException.computeMessageBuffer(response);
  if (!com.google.api.client.util.Strings.isNullOrEmpty(detailString)) {
    message.append(StringUtils.LINE_SEPARATOR).append(detailString);
    builder.setContent(detailString);
  }
  builder.setMessage(message.toString());
  return new TokenResponseException(builder, details);
}
 
Example 9
Source File: LenientTokenResponseException.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new instance of {@link LenientTokenResponseException}.
 * <p>
 * If there is a JSON error response, it is parsed using
 * {@link TokenErrorResponse}, which can be inspected using
 * {@link #getDetails()}. Otherwise, the full response content is read and
 * included in the exception message.
 * </p>
 * 
 * @param jsonFactory JSON factory
 * @param readResponse an HTTP response that has already been read
 * @param responseContent the content String of the HTTP response
 * @return new instance of {@link TokenErrorResponse}
 */
public static LenientTokenResponseException from(JsonFactory jsonFactory,
        HttpResponse readResponse, String responseContent) {
    HttpResponseException.Builder builder = new HttpResponseException.Builder(
            readResponse.getStatusCode(), readResponse.getStatusMessage(),
            readResponse.getHeaders());
    // details
    Preconditions.checkNotNull(jsonFactory);
    TokenErrorResponse details = null;
    String detailString = null;
    String contentType = readResponse.getContentType();
    try {
        if (/* !response.isSuccessStatusCode() && */true
                && contentType != null
                && HttpMediaType.equalsIgnoreParameters(Json.MEDIA_TYPE, contentType)) {
            details = readResponse
                    .getRequest()
                    .getParser()
                    .parseAndClose(new StringReader(responseContent), TokenErrorResponse.class);
            detailString = details.toPrettyString();
        } else {
            detailString = responseContent;
        }
    } catch (IOException exception) {
        // it would be bad to throw an exception while throwing an exception
        exception.printStackTrace();
    }
    // message
    StringBuilder message = HttpResponseException.computeMessageBuffer(readResponse);
    if (!com.google.api.client.util.Strings.isNullOrEmpty(detailString)) {
        message.append(StringUtils.LINE_SEPARATOR).append(detailString);
        builder.setContent(detailString);
    }
    builder.setMessage(message.toString());
    return new LenientTokenResponseException(builder, details);
}
 
Example 10
Source File: BatchRequestServiceTest.java    From connector-sdk with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testRetryableGoogleJSONException() throws Exception {
  int httpErrorCode = 503;
  String errorMessage = "Service Unavailable";
  when(retryPolicy.isRetryableStatusCode(httpErrorCode)).thenReturn(true);
  when(retryPolicy.getMaxRetryLimit()).thenReturn(3);
  BatchRequestService batchService = setupService();
  batchService.startAsync().awaitRunning();
  assertTrue(batchService.isRunning());
  BatchRequest batchRequest = getMockBatchRequest();
  when(batchRequestHelper.createBatch(any())).thenReturn(batchRequest);
  AsyncRequest<GenericJson> requestToBatch =
      new AsyncRequest<GenericJson>(testRequest, retryPolicy, operationStats);
  assertEquals(0, requestToBatch.getRetries());
  assertEquals(Status.NEW, requestToBatch.getStatus());
  GoogleJsonError error = new GoogleJsonError();
  error.setCode(httpErrorCode);
  error.setMessage(errorMessage);
  GoogleJsonResponseException exception =
      new GoogleJsonResponseException(
          new HttpResponseException.Builder(httpErrorCode, errorMessage, new HttpHeaders()),
          error);
  GenericJson successfulResult = new GenericJson();
  doAnswer(
          i -> {
            if (requestToBatch.getRetries() >= 2) {
              requestToBatch.getCallback().onStart();
              requestToBatch.getCallback().onSuccess(successfulResult, new HttpHeaders());
              return null;
            } else {
              throw exception;
            }
          })
      .when(batchRequestHelper)
      .executeBatchRequest(batchRequest);

  batchService.add(requestToBatch);
  batchService.flush();
  batchService.stopAsync().awaitTerminated();
  verify(retryPolicy, times(2)).isRetryableStatusCode(httpErrorCode);
  verify(retryPolicy, times(2)).getMaxRetryLimit();
  verify(backOff, times(2)).nextBackOffMillis();
  assertEquals(successfulResult, requestToBatch.getFuture().get());
  assertEquals(Status.COMPLETED, requestToBatch.getStatus());
  assertEquals(2, requestToBatch.getRetries());
  assertFalse(batchService.isRunning());
}
 
Example 11
Source File: ServiceAccountUsageAuthorizerTest.java    From styx with Apache License 2.0 4 votes vote down vote up
private static GoogleJsonResponseException googleJsonResponseException(int code) {
  return new GoogleJsonResponseException(new HttpResponseException.Builder(code, "", new HttpHeaders()),
      new GoogleJsonError());
}
 
Example 12
Source File: GcpUtilTest.java    From styx with Apache License 2.0 4 votes vote down vote up
@Test
public void responseIsPermissionDenied() {
  final Throwable permissionDenied = new GoogleJsonResponseException(
      new HttpResponseException.Builder(403, "Forbidden", new HttpHeaders()), PERMISSION_DENIED_ERROR);
  assertThat(GcpUtil.isPermissionDenied(permissionDenied), is(true));
}
 
Example 13
Source File: GcpUtilTest.java    From styx with Apache License 2.0 4 votes vote down vote up
@Test
public void responseIsResourceExhausted() {
  final Throwable resourceExhausted = new GoogleJsonResponseException(
      new HttpResponseException.Builder(429, "Too Many Requests", new HttpHeaders()), RESOURCE_EXHAUSTED_ERROR);
  assertThat(GcpUtil.isResourceExhausted(resourceExhausted), is(true));
}