private static AccessToken getGcloudAccessToken()

in artifactregistry-auth-common/src/main/java/com/google/cloud/artifactregistry/auth/GcloudCredentials.java [89:117]


  private static AccessToken getGcloudAccessToken(CommandExecutor commandExecutor) throws IOException {
    try {
      String gcloud = gCloudCommand();
      CommandExecutorResult commandExecutorResult = commandExecutor.executeCommand(gcloud, "config", "config-helper", "--format=json(credential)");
      int exitCode = commandExecutorResult.exitCode;
      String stdOut = commandExecutorResult.stdOut;

      if (exitCode != 0) {
        String stdErr = commandExecutorResult.stdErr;
        throw new IOException(String.format("gcloud exited with status: %d\nOutput:\n%s\nError Output:\n%s\n",
            exitCode, stdOut, stdErr));
      }

      GenericData result = JSON_FACTORY.fromString(stdOut, GenericData.class);
      Map credential = (Map) result.get("credential");
      if (credential == null) {
        throw new IOException("No credential returned from gcloud");
      }
      if (!credential.containsKey(KEY_ACCESS_TOKEN) || !credential.containsKey(KEY_TOKEN_EXPIRY)) {
        throw new IOException("Malformed response from gcloud");
      }
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
      df.setTimeZone(TimeZone.getTimeZone("UTC"));
      Date expiry = df.parse((String) credential.get(KEY_TOKEN_EXPIRY));
      return new AccessToken((String) credential.get(KEY_ACCESS_TOKEN), expiry);
    } catch (ParseException e) {
      throw new IOException("Failed to parse timestamp from gcloud output", e);
    }
  }