Java Code Examples for com.google.api.client.googleapis.json.GoogleJsonResponseException#getDetails()

The following examples show how to use com.google.api.client.googleapis.json.GoogleJsonResponseException#getDetails() . 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: DirectoryGroupsConnection.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Override
public Set<String> getMembersOfGroup(String groupKey) throws IOException {
  // Documentation for this API call:
  // https://developers.google.com/admin-sdk/directory/v1/reference/members/list
  try {
    ImmutableSet.Builder<String> allMembers = new ImmutableSet.Builder<>();
    Directory.Members.List listRequest =
        directory.members().list(groupKey).setRoles(Role.MEMBER.toString());
    do {
      Members currentPage = listRequest.execute();
      for (Member member : nullToEmpty(currentPage.getMembers())) {
        allMembers.add(member.getEmail());
      }
      listRequest.setPageToken(currentPage.getNextPageToken());
    } while (!Strings.isNullOrEmpty(listRequest.getPageToken()));
    return allMembers.build();
  } catch (GoogleJsonResponseException e) {
    if (e.getDetails() != null
        && e.getDetails().getCode() == SC_NOT_FOUND
        && e.getDetails().getMessage().equals(GROUP_NOT_FOUND_MSG)) {
      return ImmutableSet.of();
    } else {
      throw e;
    }
  }
}
 
Example 2
Source File: DirectoryGroupsConnection.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Override
public Group createGroup(String groupKey) throws IOException {
  // Documentation for this API call:
  // https://developers.google.com/admin-sdk/directory/v1/reference/groups/insert
  Group group = new Group();
  group.setEmail(groupKey);
  try {
    Group createdGroup = directory.groups().insert(group).execute();
    addMemberToGroup(groupKey, gSuiteAdminAccountEmailAddress, Role.OWNER);
    groupsSettings.groups().patch(groupKey, defaultGroupPermissions).execute();
    return createdGroup;
  } catch (GoogleJsonResponseException e) {
    // Ignore the error thrown if the group already exists.
    if (e.getDetails() != null
        && e.getDetails().getCode() == SC_CONFLICT
        && e.getDetails().getMessage().equals("Entity already exists.")) {
      logger.atInfo().withCause(e).log(
          "Could not create group %s because it already exists.", groupKey);
      return directory.groups().get(groupKey).execute();
    } else {
      throw e;
    }
  }
}
 
Example 3
Source File: UpdateSnapshotViewAction.java    From nomulus with Apache License 2.0 6 votes vote down vote up
private static void updateTable(Bigquery bigquery, Table table) throws IOException {
  TableReference ref = table.getTableReference();
  try {
    bigquery
        .tables()
        .update(ref.getProjectId(), ref.getDatasetId(), ref.getTableId(), table)
        .execute();
  } catch (GoogleJsonResponseException e) {
    if (e.getDetails() != null && e.getDetails().getCode() == 404) {
      bigquery.tables().insert(ref.getProjectId(), ref.getDatasetId(), table).execute();
    } else {
      logger.atWarning().withCause(e).log(
          "UpdateSnapshotViewAction failed, caught exception %s", e.getDetails());
    }
  }
}
 
Example 4
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 5
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 6
Source File: GoogleStorageExceptionMappingService.java    From cyberduck with GNU General Public License v3.0 5 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;
        if(error.getDetails() != null) {
            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: 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 8
Source File: CloudSqlInstance.java    From cloud-sql-jdbc-socket-factory with Apache License 2.0 5 votes vote down vote up
/**
 * Checks for common errors that can occur when interacting with the Cloud SQL Admin API, and adds
 * additional context to help the user troubleshoot them.
 *
 * @param ex exception thrown by the Admin API request
 * @param fallbackDesc generic description used as a fallback if no additional information can be
 *     provided to the user
 */
private RuntimeException addExceptionContext(IOException ex, String fallbackDesc) {
  // Verify we are able to extract a reason from an exception, or fallback to a generic desc
  GoogleJsonResponseException gjrEx =
      ex instanceof GoogleJsonResponseException ? (GoogleJsonResponseException) ex : null;
  if (gjrEx == null
      || gjrEx.getDetails() == null
      || gjrEx.getDetails().getErrors() == null
      || gjrEx.getDetails().getErrors().isEmpty()) {
    return new RuntimeException(fallbackDesc, ex);
  }
  // Check for commonly occurring user errors and add additional context
  String reason = gjrEx.getDetails().getErrors().get(0).getReason();
  if ("accessNotConfigured".equals(reason)) {
    // This error occurs when the project doesn't have the "Cloud SQL Admin API" enabled
    String apiLink =
        "https://console.cloud.google.com/apis/api/sqladmin/overview?project=" + projectId;
    return new RuntimeException(
        String.format(
            "[%s] The Google Cloud SQL Admin API is not enabled for the project \"%s\". Please "
                + "use the Google Developers Console to enable it: %s",
            connectionName, projectId, apiLink),
        ex);
  } else if ("notAuthorized".equals(reason)) {
    // This error occurs if the instance doesn't exist or the account isn't authorized
    // TODO(kvg): Add credential account name to error string.
    return new RuntimeException(
        String.format(
            "[%s] The Cloud SQL Instance does not exist or your account is not authorized to "
                + "access it. Please verify the instance connection name and check the IAM "
                + "permissions for project \"%s\" ",
            connectionName, projectId),
        ex);
  }
  // Fallback to the generic description
  return new RuntimeException(fallbackDesc, ex);
}
 
Example 9
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 10
Source File: BigqueryConnection.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/** Helper that returns true if a dataset with this name exists. */
public boolean checkDatasetExists(String datasetName) throws IOException {
  try {
    bigquery.datasets().get(getProjectId(), datasetName).execute();
    return true;
  } catch (GoogleJsonResponseException e) {
    if (e.getDetails() != null && e.getDetails().getCode() == 404) {
      return false;
    }
    throw e;
  }
}
 
Example 11
Source File: BigqueryConnection.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/** Helper that returns true if a table with this name and dataset name exists. */
public boolean checkTableExists(String datasetName, String tableName) throws IOException {
  try {
    bigquery.tables().get(getProjectId(), datasetName, tableName).execute();
    return true;
  } catch (GoogleJsonResponseException e) {
    if (e.getDetails() != null && e.getDetails().getCode() == 404) {
      return false;
    }
    throw e;
  }
}
 
Example 12
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 13
Source File: DirectoryGroupsConnection.java    From nomulus with Apache License 2.0 4 votes vote down vote up
@Override
public void addMemberToGroup(String groupKey, String email, Role role) throws IOException {
  // Documentation for this API call:
  // https://developers.google.com/admin-sdk/directory/v1/reference/members/insert
  Member member = new Member();
  member.setEmail(email);
  member.setRole(role.toString());
  try {
    directory.members().insert(groupKey, member).execute();
  } catch (GoogleJsonResponseException e) {
    // If the member is already in the group, ignore the error, get the existing member, and
    // return it.
    GoogleJsonError err = e.getDetails();
    if (err == null) {
      throw e;
    } else if (err.getCode() == SC_NOT_FOUND && err.getMessage().equals(GROUP_NOT_FOUND_MSG)) {
      logger.atInfo().withCause(e).log(
          "Creating group %s during addition of member %s because the group doesn't exist.",
          groupKey, email);
      createGroup(groupKey);
      addMemberToGroup(groupKey, email, role);
    } else if (err.getCode() == SC_NOT_FOUND && err.getMessage().equals(MEMBER_NOT_FOUND_MSG)) {
      throw new RuntimeException(String.format(
          "Adding member %s to group %s failed because the member wasn't found.",
          email,
          groupKey), e);
    } else if (err.getCode() == SC_CONFLICT
        && err.getMessage().equals(MEMBER_ALREADY_EXISTS_MSG)) {
      // This error case usually happens when an email address is already a member of the gorup,
      // but it is bouncing incoming emails. It won't show up in the members list API call, but
      // will throw a "Member already exists" error message if you attempt to add it again. The
      // correct thing to do is log an info message when this happens and then ignore it.
      logger.atInfo().withCause(e).log(
          "Could not add email %s to group %s because it is already a member "
              + "(likely because the email address is bouncing incoming messages).",
          email, groupKey);
    } else {
      throw e;
    }
  }
}
 
Example 14
Source File: ApiErrorExtractor.java    From hadoop-connectors with Apache License 2.0 4 votes vote down vote up
/** If the exception is a GoogleJsonResponseException, get the error details, else return null. */
@Nullable
protected GoogleJsonError getJsonError(IOException e) {
  GoogleJsonResponseException jsonException = getJsonResponseException(e);
  return jsonException == null ? null : jsonException.getDetails();
}