com.google.api.client.googleapis.json.GoogleJsonError Java Examples

The following examples show how to use com.google.api.client.googleapis.json.GoogleJsonError. 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: TestingHttpTransport.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Convert the passed Json "result" to a response.
 *
 * <p>A {@code null} result will be converted to a successful response. An error response will
 * be generated only if the {@code result} is a {@link GoogleJsonError}.
 *
 * @param result the Json execute result.
 * @return the converted response of the result.
 * @throws IOException
 */
private MockLowLevelHttpResponse getResponse(GenericJson result) throws IOException {
  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
  if (result instanceof GoogleJsonError) {
    GoogleJsonError error = (GoogleJsonError) result;
    String errorContent = JSON_FACTORY.toString(new GenericJson().set("error", error));
    response
        .setStatusCode(error.getCode())
        .setReasonPhrase(error.getMessage())
        .setContentType(Json.MEDIA_TYPE)
        .setContent(errorContent);
  } else {
    response
        .setStatusCode(HTTP_OK)
        .setContentType(Json.MEDIA_TYPE)
        .setContent(result == null ? "" : JSON_FACTORY.toString(result));
  }
  return response;
}
 
Example #2
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 #3
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 #4
Source File: SkyTubeApp.java    From SkyTube with GNU General Public License v3.0 6 votes vote down vote up
public static void notifyUserOnError(Context ctx, Exception exc) {
	if (exc == null) {
		return;
	}
	final String message;
	if (exc instanceof GoogleJsonResponseException) {
		GoogleJsonResponseException exception = (GoogleJsonResponseException) exc;
		List<GoogleJsonError.ErrorInfo> errors = exception.getDetails().getErrors();
		if (errors != null && !errors.isEmpty()) {
			message =  "Server error:" + errors.get(0).getMessage()+ ", reason: "+ errors.get(0).getReason();
		} else {
			message = exception.getDetails().getMessage();
		}
	} else {
		message = exc.getMessage();
	}
	if (message != null) {
		Log.e("SkyTubeApp", "Error: "+message);
		Toast.makeText(ctx, message, Toast.LENGTH_LONG).show();
	}
}
 
Example #5
Source File: GoogleDriveFileSystem.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@Override
public boolean delete(Path path, boolean recursive) throws IOException {
  Preconditions.checkArgument(recursive, "Non-recursive is not supported.");
  String fileId = toFileId(path);
  LOG.debug("Deleting file: " + fileId);
  try {
    client.files().delete(fileId).execute();
  } catch (GoogleJsonResponseException e) {
    GoogleJsonError error = e.getDetails();
    if (404 == error.getCode()) { //Non-existing file id
      return false;
    }
    throw e;
  }
  return true;
}
 
Example #6
Source File: DriveExceptionMappingService.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Override
public BackgroundException map(final IOException failure) {
    final StringBuilder buffer = new StringBuilder();
    if(failure instanceof GoogleJsonResponseException) {
        final GoogleJsonResponseException error = (GoogleJsonResponseException) failure;
        this.append(buffer, error.getDetails().getMessage());
        switch(error.getDetails().getCode()) {
            case HttpStatus.SC_FORBIDDEN:
                final List<GoogleJsonError.ErrorInfo> errors = error.getDetails().getErrors();
                for(GoogleJsonError.ErrorInfo info : errors) {
                    if("usageLimits".equals(info.getDomain())) {
                        return new RetriableAccessDeniedException(buffer.toString(), Duration.ofSeconds(5), failure);
                    }
                }
                break;
        }
    }
    if(failure instanceof HttpResponseException) {
        final HttpResponseException response = (HttpResponseException) failure;
        this.append(buffer, response.getStatusMessage());
        return new DefaultHttpResponseExceptionMappingService().map(new org.apache.http.client
                .HttpResponseException(response.getStatusCode(), buffer.toString()));
    }
    return super.map(failure);
}
 
Example #7
Source File: MockHttpTransportHelper.java    From hadoop-connectors with Apache License 2.0 6 votes vote down vote up
public static MockLowLevelHttpResponse jsonErrorResponse(ErrorResponses errorResponse)
    throws IOException {
  GoogleJsonError.ErrorInfo errorInfo = new GoogleJsonError.ErrorInfo();
  errorInfo.setReason(errorResponse.getErrorReason());
  errorInfo.setDomain(errorResponse.getErrorDomain());
  errorInfo.setFactory(JSON_FACTORY);

  GoogleJsonError jsonError = new GoogleJsonError();
  jsonError.setCode(errorResponse.getErrorCode());
  jsonError.setErrors(ImmutableList.of(errorInfo));
  jsonError.setMessage(errorResponse.getErrorMessage());
  jsonError.setFactory(JSON_FACTORY);

  GenericJson errorResponseJson = new GenericJson();
  errorResponseJson.set("error", jsonError);
  errorResponseJson.setFactory(JSON_FACTORY);

  return new MockLowLevelHttpResponse()
      .setContent(errorResponseJson.toPrettyString())
      .setContentType(Json.MEDIA_TYPE)
      .setStatusCode(errorResponse.getResponseCode());
}
 
Example #8
Source File: GoogleCloudStorageImpl.java    From hadoop-connectors with Apache License 2.0 6 votes vote down vote up
/** Processes failed copy requests */
private void onCopyFailure(
    KeySetView<IOException, Boolean> innerExceptions,
    GoogleJsonError jsonError,
    HttpHeaders responseHeaders,
    String srcBucketName,
    String srcObjectName) {
  GoogleJsonResponseException cause = createJsonResponseException(jsonError, responseHeaders);
  innerExceptions.add(
      errorExtractor.itemNotFound(cause)
          ? createFileNotFoundException(srcBucketName, srcObjectName, cause)
          : new IOException(
              String.format(
                  "Error copying '%s'", StringPaths.fromComponents(srcBucketName, srcObjectName)),
              cause));
}
 
Example #9
Source File: BatchRequestServiceTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testBatchRequestIOException() throws Exception {
  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);
  GoogleJsonError error = new GoogleJsonError();
  error.setCode(403);
  error.setMessage("unauthorized");
  doAnswer(
          invocation -> {
            throw new IOException();
          })
      .when(batchRequestHelper)
      .executeBatchRequest(batchRequest);

  batchService.add(requestToBatch);
  batchService.flush();
  batchService.stopAsync().awaitTerminated();
  validateFailedResult(requestToBatch.getFuture());
  assertFalse(batchService.isRunning());
}
 
Example #10
Source File: BatchRequestServiceTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailedResult() throws Exception {
  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);
  GoogleJsonError error = new GoogleJsonError();
  error.setCode(403);
  error.setMessage("unauthorized");
  doAnswer(
          invocation -> {
            requestToBatch.getCallback().onFailure(error, new HttpHeaders());
            return null;
          })
      .when(batchRequestHelper)
      .executeBatchRequest(batchRequest);

  batchService.add(requestToBatch);
  batchService.flush();
  batchService.stopAsync().awaitTerminated();
  validateFailedResult(requestToBatch.getFuture());
  assertFalse(batchService.isRunning());
}
 
Example #11
Source File: AsyncRequest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Wrapper on {@link JsonBatchCallback#onFailure} to record failure while executing batched
 * request.
 */
@Override
public void onFailure(GoogleJsonError error, HttpHeaders responseHeaders) {
  if (event != null) {
    event.failure();
    event = null;
  } else {
    operationStats.event(request.requestToExecute.getClass().getName()).failure();
  }
  logger.log(Level.WARNING, "Request failed with error {0}", error);
  if (request.retryPolicy.isRetryableStatusCode(error.getCode())) {
    if (request.getRetries() < request.retryPolicy.getMaxRetryLimit()) {
      request.setStatus(Status.RETRYING);
      request.incrementRetries();
      return;
    }
  }
  GoogleJsonResponseException exception =
      new GoogleJsonResponseException(
          new Builder(error.getCode(), error.getMessage(), responseHeaders), error);
  fail(exception);
}
 
Example #12
Source File: BatchRequestService.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
private GoogleJsonError getGoogleJsonError(Exception e) {
  if (e instanceof GoogleJsonResponseException) {
    return ((GoogleJsonResponseException) e).getDetails();
  }
  boolean retryableException =
      (e instanceof SSLHandshakeException || e instanceof SocketTimeoutException);
  if (retryableException) {
    logger.log(Level.WARNING, "Retrying request failed with exception:", e);
  }
  // Using retryable 504 Gateway Timeout error code.
  int errorCode = retryableException ? 504 : 0;
  GoogleJsonError error = new GoogleJsonError();
  error.setMessage(e.getMessage());
  error.setCode(errorCode);
  return error;
}
 
Example #13
Source File: BaseWorkflowSample.java    From googleads-shopping-samples with Apache License 2.0 6 votes vote down vote up
protected static void checkGoogleJsonResponseException(GoogleJsonResponseException e)
    throws GoogleJsonResponseException {
  GoogleJsonError err = e.getDetails();
  // err can be null if response is not JSON
  if (err != null) {
    // For errors in the 4xx range, print out the errors and continue normally.
    if (err.getCode() >= 400 && err.getCode() < 500) {
      System.out.printf("There are %d error(s)%n", err.getErrors().size());
      for (ErrorInfo info : err.getErrors()) {
        System.out.printf("- [%s] %s%n", info.getReason(), info.getMessage());
      }
    } else {
      throw e;
    }
  } else {
    throw e;
  }
}
 
Example #14
Source File: RepositoryDocTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test(expected = IOException.class)
public void execute_indexItemNotFound_notPushedToQueue_throwsIOException() throws Exception {
  Item item = new Item().setName("id1").setAcl(getCustomerAcl());
  RepositoryDoc doc = new RepositoryDoc.Builder().setItem(item).build();
  doAnswer(
          invocation -> {
            SettableFuture<Operation> updateFuture = SettableFuture.create();
            updateFuture.setException(
                new GoogleJsonResponseException(
                    new HttpResponseException.Builder(
                        HTTP_NOT_FOUND, "not found", new HttpHeaders()),
                    new GoogleJsonError()));
            return updateFuture;
          })
      .when(mockIndexingService)
      .indexItem(item, RequestMode.UNSPECIFIED);
  try {
    doc.execute(mockIndexingService);
  } finally {
    InOrder inOrder = inOrder(mockIndexingService);
    inOrder.verify(mockIndexingService).indexItem(item, RequestMode.UNSPECIFIED);
    inOrder.verifyNoMoreInteractions();
    assertEquals("id1", doc.getItem().getName());
  }
}
 
Example #15
Source File: ApiErrorExtractor.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
/**
 * Determines if the given exception indicates that 'userProject' is missing in request.
 * Recursively checks getCause() if outer exception isn't an instance of the correct class.
 */
public boolean userProjectMissing(IOException e) {
  GoogleJsonError jsonError = getJsonError(e);
  return jsonError != null
      && jsonError.getCode() == HttpStatusCodes.STATUS_CODE_BAD_REQUEST
      && USER_PROJECT_MISSING_MESSAGE.equals(jsonError.getMessage());
}
 
Example #16
Source File: CloudEndpointUtils.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * Logs the given throwable and shows an error alert dialog with its
 * message.
 * 
 * @param activity
 *            activity
 * @param tag
 *            log tag to use
 * @param t
 *            throwable to log and show
 */
public static void logAndShow(Activity activity, String tag, Throwable t) {
  Log.e(tag, "Error", t);
  String message = t.getMessage();
  // Exceptions that occur in your Cloud Endpoint implementation classes
  // are wrapped as GoogleJsonResponseExceptions
  if (t instanceof GoogleJsonResponseException) {
    GoogleJsonError details = ((GoogleJsonResponseException) t)
        .getDetails();
    if (details != null) {
      message = details.getMessage();
    }
  }
  showError(activity, message);
}
 
Example #17
Source File: Utils.java    From SimplePomodoro-android with MIT License 5 votes vote down vote up
/**
 * Logs the given throwable and shows an error alert dialog with its message.
 * 
 * @param activity activity
 * @param tag log tag to use
 * @param t throwable to log and show
 */
public static void logAndShow(Activity activity, String tag, Throwable t) {
  Log.e(tag, "Error", t);
  String message = t.getMessage();
  if (t instanceof GoogleJsonResponseException) {
    GoogleJsonError details = ((GoogleJsonResponseException) t).getDetails();
    if (details != null) {
      message = details.getMessage();
    }
  } else if (t.getCause() instanceof GoogleAuthException) {
    message = ((GoogleAuthException) t.getCause()).getMessage();
  }
  showError(activity, message);
}
 
Example #18
Source File: GcsDataflowProjectClient.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
/**
 * Uses the provided specification for the staging location, creating it if it does not already
 * exist. This may be a long-running blocking operation.
 */
public StagingLocationVerificationResult createStagingLocation(
    String projectId, String stagingLocation, IProgressMonitor progressMonitor) {
  SubMonitor monitor = SubMonitor.convert(progressMonitor, 2);
  String bucketName = toGcsBucketName(stagingLocation);
  if (locationIsAccessible(stagingLocation)) { // bucket already exists
    return new StagingLocationVerificationResult(
        String.format("Bucket %s exists", bucketName), true);
  }
  monitor.worked(1);

  // else create the bucket
  try {
    Bucket newBucket = new Bucket();
    newBucket.setName(bucketName);
    gcsClient.buckets().insert(projectId, newBucket).execute();
    return new StagingLocationVerificationResult(
        String.format("Bucket %s created", bucketName), true);
  } catch (GoogleJsonResponseException ex) {
    GoogleJsonError error = ex.getDetails();
    return new StagingLocationVerificationResult(error.getMessage(), false);
  } catch (IOException e) {
    return new StagingLocationVerificationResult(e.getMessage(), false);
  } finally {
    monitor.done();
  }
}
 
Example #19
Source File: CoreSocketFactoryTest.java    From cloud-sql-jdbc-socket-factory with Apache License 2.0 5 votes vote down vote up
private static GoogleJsonResponseException fakeGoogleJsonResponseException(
    int status, ErrorInfo errorInfo, String message) throws IOException {
  final JsonFactory jsonFactory = new JacksonFactory();
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
          errorInfo.setFactory(jsonFactory);
          GoogleJsonError jsonError = new GoogleJsonError();
          jsonError.setCode(status);
          jsonError.setErrors(Collections.singletonList(errorInfo));
          jsonError.setMessage(message);
          jsonError.setFactory(jsonFactory);
          GenericJson errorResponse = new GenericJson();
          errorResponse.set("error", jsonError);
          errorResponse.setFactory(jsonFactory);
          return new MockLowLevelHttpRequest()
              .setResponse(
                  new MockLowLevelHttpResponse()
                      .setContent(errorResponse.toPrettyString())
                      .setContentType(Json.MEDIA_TYPE)
                      .setStatusCode(status));
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setThrowExceptionOnExecuteError(false);
  HttpResponse response = request.execute();
  return GoogleJsonResponseException.from(jsonFactory, response);
}
 
Example #20
Source File: BigQueryServicesImplTest.java    From beam with Apache License 2.0 5 votes vote down vote up
/** A helper that generates the error JSON payload that Google APIs produce. */
private static GoogleJsonErrorContainer errorWithReasonAndStatus(String reason, int status) {
  ErrorInfo info = new ErrorInfo();
  info.setReason(reason);
  info.setDomain("global");
  // GoogleJsonError contains one or more ErrorInfo objects; our utiities read the first one.
  GoogleJsonError error = new GoogleJsonError();
  error.setErrors(ImmutableList.of(info));
  error.setCode(status);
  error.setMessage(reason);
  // The actual JSON response is an error container.
  GoogleJsonErrorContainer container = new GoogleJsonErrorContainer();
  container.setError(error);
  return container;
}
 
Example #21
Source File: BigqueryJobFailureException.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/** Create an error for JSON server response errors. */
public static BigqueryJobFailureException create(GoogleJsonResponseException cause) {
  GoogleJsonError err = cause.getDetails();
  if (err != null) {
    return new BigqueryJobFailureException(err.getMessage(), null, null, err);
  } else {
    return new BigqueryJobFailureException(cause.getMessage(), cause, null, null);
  }
}
 
Example #22
Source File: BigqueryJobFailureException.java    From nomulus with Apache License 2.0 5 votes vote down vote up
public BigqueryJobFailureException(
    String message,
    @Nullable Throwable cause,
    @Nullable JobStatus jobStatus,
    @Nullable GoogleJsonError jsonError) {
  super(message, cause);
  this.jobStatus = jobStatus;
  this.jsonError = jsonError;
}
 
Example #23
Source File: CloudEndpointUtils.java    From io2014-codelabs with Apache License 2.0 5 votes vote down vote up
/**
 * Logs the given throwable and shows an error alert dialog with its
 * message.
 * 
 * @param activity activity
 * @param tag log tag to use
 * @param t throwable to log and show
 */
public static void logAndShow(Activity activity, String tag, Throwable t) {
    Log.e(tag, "Error", t);
    String message = t.getMessage();
    if (t instanceof GoogleJsonResponseException) {
        GoogleJsonError details = ((GoogleJsonResponseException) t).getDetails();
        if (details != null) {
            message = details.getMessage();
        }
    }
    showError(activity, message);
}
 
Example #24
Source File: AbstractGoogleJsonClientTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
public void testExecuteUnparsed_error() throws Exception {
  HttpTransport transport = new MockHttpTransport() {
      @Override
    public LowLevelHttpRequest buildRequest(String name, String url) {
      return new MockLowLevelHttpRequest() {
          @Override
        public LowLevelHttpResponse execute() {
          MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
          result.setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
          result.setContentType(Json.MEDIA_TYPE);
          result.setContent("{\"error\":{\"code\":401,\"errors\":[{\"domain\":\"global\","
              + "\"location\":\"Authorization\",\"locationType\":\"header\","
              + "\"message\":\"me\",\"reason\":\"authError\"}],\"message\":\"me\"}}");
          return result;
        }
      };
    }
  };
  JsonFactory jsonFactory = new JacksonFactory();
  MockGoogleJsonClient client = new MockGoogleJsonClient.Builder(
      transport, jsonFactory, HttpTesting.SIMPLE_URL, "", null, false).setApplicationName(
      "Test Application").build();
  MockGoogleJsonClientRequest<String> request =
      new MockGoogleJsonClientRequest<String>(client, "GET", "foo", null, String.class);
  try {
    request.executeUnparsed();
    fail("expected " + GoogleJsonResponseException.class);
  } catch (GoogleJsonResponseException e) {
    // expected
    GoogleJsonError details = e.getDetails();
    assertEquals("me", details.getMessage());
    assertEquals("me", details.getErrors().get(0).getMessage());
  }
}
 
Example #25
Source File: ApiErrorExtractor.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
/**
 * Get the first ErrorInfo from an IOException if it is an instance of
 * GoogleJsonResponseException, otherwise return null.
 */
@Nullable
protected ErrorInfo getErrorInfo(IOException e) {
  GoogleJsonError jsonError = getJsonError(e);
  List<ErrorInfo> errors = jsonError != null ? jsonError.getErrors() : ImmutableList.of();
  return errors != null ? Iterables.getFirst(errors, null) : null;
}
 
Example #26
Source File: ApiErrorExtractorTest.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
/** Validates itemNotFound(). */
@Test
public void testItemNotFound() {
  // Check success cases.
  assertThat(errorExtractor.itemNotFound(notFound)).isTrue();
  GoogleJsonError gje = new GoogleJsonError();
  gje.setCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND);
  assertThat(errorExtractor.itemNotFound(new IOException(notFound))).isTrue();
  assertThat(errorExtractor.itemNotFound(new IOException(new IOException(notFound)))).isTrue();

  // Check failure case.
  assertThat(errorExtractor.itemNotFound(statusOk)).isFalse();
  assertThat(errorExtractor.itemNotFound(new IOException())).isFalse();
  assertThat(errorExtractor.itemNotFound(new IOException(new IOException()))).isFalse();
}
 
Example #27
Source File: ApiErrorExtractorTest.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
private static GoogleJsonResponseException googleJsonResponseException(
    int status, ErrorInfo errorInfo, String httpStatusString) throws IOException {
  final JsonFactory jsonFactory = new JacksonFactory();
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
          errorInfo.setFactory(jsonFactory);
          GoogleJsonError jsonError = new GoogleJsonError();
          jsonError.setCode(status);
          jsonError.setErrors(Collections.singletonList(errorInfo));
          jsonError.setMessage(httpStatusString);
          jsonError.setFactory(jsonFactory);
          GenericJson errorResponse = new GenericJson();
          errorResponse.set("error", jsonError);
          errorResponse.setFactory(jsonFactory);
          return new MockLowLevelHttpRequest()
              .setResponse(
                  new MockLowLevelHttpResponse()
                      .setContent(errorResponse.toPrettyString())
                      .setContentType(Json.MEDIA_TYPE)
                      .setStatusCode(status));
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  request.setThrowExceptionOnExecuteError(false);
  HttpResponse response = request.execute();
  return GoogleJsonResponseException.from(jsonFactory, response);
}
 
Example #28
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 #29
Source File: BatchRequestTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
@Override
public void onFailure(ErrorOutput.ErrorBody e, HttpHeaders responseHeaders) throws IOException {
  GoogleJsonErrorContainer errorContainer = new GoogleJsonErrorContainer();

  if (e.hasError()) {
    ErrorOutput.ErrorProto errorProto = e.getError();

    GoogleJsonError error = new GoogleJsonError();
    if (errorProto.hasCode()) {
      error.setCode(errorProto.getCode());
    }
    if (errorProto.hasMessage()) {
      error.setMessage(errorProto.getMessage());
    }

    List<ErrorInfo> errorInfos = new ArrayList<ErrorInfo>(errorProto.getErrorsCount());
    for (ErrorOutput.IndividualError individualError : errorProto.getErrorsList()) {
      ErrorInfo errorInfo = new ErrorInfo();
      if (individualError.hasDomain()) {
        errorInfo.setDomain(individualError.getDomain());
      }
      if (individualError.hasMessage()) {
        errorInfo.setMessage(individualError.getMessage());
      }
      if (individualError.hasReason()) {
        errorInfo.setReason(individualError.getReason());
      }
      errorInfos.add(errorInfo);
    }
    error.setErrors(errorInfos);
    errorContainer.setError(error);
  }
  callback.onFailure(errorContainer, responseHeaders);
}
 
Example #30
Source File: BatchRequestTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
@Override
public void onFailure(GoogleJsonErrorContainer e, HttpHeaders responseHeaders) {
  failureCalls++;
  GoogleJsonError error = e.getError();
  ErrorInfo errorInfo = error.getErrors().get(0);
  assertEquals(ERROR_DOMAIN, errorInfo.getDomain());
  assertEquals(ERROR_REASON, errorInfo.getReason());
  assertEquals(ERROR_MSG, errorInfo.getMessage());
  assertEquals(ERROR_CODE, error.getCode());
  assertEquals(ERROR_MSG, error.getMessage());
}