Java のクイックスタート

クイックスタートでは、 Google Workspace API

Google Workspace クイックスタートでは、API クライアント ライブラリを使用して 認証と認可のフローの詳細を確認できます。おすすめの方法 独自のアプリ用のクライアント ライブラリを使用します。このクイックスタートでは、 テストに適したシンプルな認証アプローチ できます。本番環境では、Terraform の IAM 構成の 認証と認可 次の日付より前 アクセス認証情報の選択 選択することもできます

Google Chat API にリクエストを送信する Java コマンドライン アプリケーションを作成します。

目標

  • 環境を設定する。
  • サンプルを設定します。
  • サンプルを実行します。

前提条件

環境の設定

このクイックスタートを完了するには、環境を設定します。

API を有効にする

Google API を使用する前に、Google Cloud プロジェクトで有効にする必要があります。 1 つの Google Cloud プロジェクトで 1 つ以上の API を有効にできます。
  • Google Cloud コンソールで、Google Chat API を有効にします。

    API の有効化

このクイックスタートを完了するために新しい Google Cloud プロジェクトを使用する場合は、 OAuth 同意画面を開き、自分自身をテストユーザーとして追加します。すでに 完了している場合は、次のセクションにスキップしてください。

  1. Google Cloud コンソールで、メニュー に移動します。 > API とサービス > OAuth 同意画面

    OAuth 同意画面に移動

  2. [ユーザーの種類] で [内部] を選択し、[作成] をクリックします。
  3. アプリ登録フォームに入力し、[保存して次へ] をクリックします。
  4. 現時点では、スコープの追加をスキップして [保存して次へ] をクリックします。 今後、Google Play 以外で使用するアプリを作成した場合、 [ユーザーの種類] を [外部] に変更してから、 アプリに必要な認証スコープを追加します。

  5. アプリ登録の概要を確認します。変更するには、[編集] をクリックします。アプリが 問題がなければ、[ダッシュボードに戻る] をクリックします。

デスクトップ アプリケーションの認証情報を承認する

エンドユーザーを認証してアプリでユーザーデータにアクセスするには、次のことを行う必要があります。 OAuth 2.0 クライアント ID を作成します。クライアント ID は Google の OAuth サーバーに送信します。アプリが複数のプラットフォームで動作する場合 プラットフォームごとに個別のクライアント ID を作成する必要があります。
  1. Google Cloud コンソールで、メニュー > [API と[サービス] > [認証情報] に移動します。

    [認証情報] に移動

  2. [認証情報を作成] > [OAuth クライアント ID] をクリックします。
  3. [アプリケーションの種類] > [デスクトップ アプリ] をクリックします。
  4. [名前] フィールドに、認証情報の名前を入力します。この名前は Google Cloud コンソールにのみ表示されます。
  5. [作成] をクリックします。OAuth クライアントの作成画面が表示され、新しいクライアント ID とクライアント シークレットが表示されます。
  6. [OK] をクリックします。新しく作成された認証情報が [OAuth 2.0 クライアント ID] に表示されます。
  7. ダウンロードした JSON ファイルを credentials.json として保存し、 作業ディレクトリに移動します。

Google Chat アプリを構成する

Google Chat API を呼び出すには、 Google Chat アプリ。すべての書き込みリクエストに対して、Google Chat は UI に Google Chat アプリの属性が表示されます。 次の情報が含まれます。

  1. Google Cloud コンソールで、Chat API の [構成] ページに移動します。

    [Chat API の構成] ページに移動

  2. [Application info] で、次の情報を入力します。

    1. [App name] フィールドに「Chat API quickstart app」と入力します。
    2. [アバターの URL] フィールドに、次のように入力します。 https://developers.google.com/chat/images/quickstart-app-avatar.png
    3. [説明] フィールドに「Quickstart for calling the Chat API」と入力します。
  3. [インタラクティブ機能] で、[インタラクティブ機能を有効にする] をクリックします。 インタラクティブ機能を無効にするには、 Chat アプリ。

  4. [保存] をクリックします。

職場環境を整える

  1. 作業ディレクトリで、新しいプロジェクト構造を作成します。

    gradle init --type basic
    mkdir -p src/main/java src/main/resources 
    
  2. src/main/resources/ ディレクトリで、credentials.json ファイルをコピーします。 画像が表示されます。

  3. デフォルトの build.gradle ファイルを開き、内容を コード:

    chat/quickstart/build.gradle
    apply plugin: 'java'
    apply plugin: 'application'
    
    mainClassName = 'ChatQuickstart'
    sourceCompatibility = 11
    targetCompatibility = 11
    version = '1.0'
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        implementation 'com.google.auth:google-auth-library-oauth2-http:1.23.0'
        implementation 'com.google.api-client:google-api-client:1.33.0'
        implementation 'com.google.api.grpc:proto-google-cloud-chat-v1:0.8.0'
        implementation 'com.google.api:gax:2.48.1'
        implementation 'com.google.cloud:google-cloud-chat:0.1.0'
        implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1'
    }
    

サンプルのセットアップ

  1. src/main/java/ ディレクトリに、次の名前の新しい Java ファイルを作成します。 これは、build.gradle ファイルの mainClassName 値と一致します。

  2. 新しい Java ファイルに次のコードを含めます。

    chat/quickstart/src/main/java/ChatQuickstart.java
    import com.google.api.client.auth.oauth2.Credential;
    import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
    import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
    import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
    import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
    import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
    import com.google.api.client.json.JsonFactory;
    import com.google.api.client.json.gson.GsonFactory;
    import com.google.api.client.util.store.FileDataStoreFactory;
    import com.google.api.gax.core.FixedCredentialsProvider;
    import com.google.auth.Credentials;
    import com.google.auth.oauth2.AccessToken;
    import com.google.auth.oauth2.UserCredentials;
    import com.google.chat.v1.ChatServiceClient;
    import com.google.chat.v1.ChatServiceSettings;
    import com.google.chat.v1.ListSpacesRequest;
    import com.google.chat.v1.Space;
    import com.google.protobuf.util.JsonFormat;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.Collections;
    import java.util.Date;
    import java.util.List;
    
    /* class to demonstrate use of Google Chat API spaces list API */
    public class ChatQuickstart {
      /** Directory to store authorization tokens for this application. */
      private static final String TOKENS_DIRECTORY_PATH = "tokens";
    
      /**
       * Global instance of the scopes required by this quickstart. If modifying these scopes, delete
       * your previously saved tokens/ folder.
       */
      private static final List<String> SCOPES =
          Collections.singletonList("https://www.googleapis.com/auth/chat.spaces.readonly");
    
      /** Global instance of the JSON factory. */
      private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
    
      private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
    
      /**
       * Run the OAuth2 flow for local/installed app.
       *
       * @return An authorized Credential object.
       * @throws IOException If the credentials.json file cannot be found.
       */
      private static Credentials getCredentials() throws Exception {
        // Load client secrets.
        InputStream credentialsFileInputStream =
            ChatQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
        if (credentialsFileInputStream == null) {
          throw new FileNotFoundException("Credentials file resource not found.");
        }
        GoogleClientSecrets clientSecrets =
            GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(credentialsFileInputStream));
    
        // Set up authorization code flow.
        GoogleAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow.Builder(
                    GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, clientSecrets, SCOPES)
                // Set these two options to generate refresh token alongside access token.
                .setDataStoreFactory(new FileDataStoreFactory(new File(TOKENS_DIRECTORY_PATH)))
                .setAccessType("offline")
                .build();
    
        // Authorize.
        Credential credential =
            new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    
        // Build and return an authorized Credential object
        AccessToken accessToken =
            new AccessToken(
                credential.getAccessToken(),
                new Date(
                    // put the actual expiry date of access token here
                    System.currentTimeMillis()));
        return UserCredentials.newBuilder()
            .setAccessToken(accessToken)
            .setRefreshToken(credential.getRefreshToken())
            .setClientId(clientSecrets.getInstalled().getClientId())
            .setClientSecret(clientSecrets.getInstalled().getClientSecret())
            .build();
      }
    
      public static void main(String... args) throws Exception {
        // Override default service settings to supply user credentials.
        Credentials credentials = getCredentials();
    
        // Create the ChatServiceSettings with the credentials
        ChatServiceSettings chatServiceSettings =
            ChatServiceSettings.newBuilder()
                .setCredentialsProvider(FixedCredentialsProvider.create(credentials))
                .build();
    
        try (ChatServiceClient chatServiceClient = ChatServiceClient.create(chatServiceSettings)) {
          ListSpacesRequest request =
              ListSpacesRequest.newBuilder()
                  // Filter spaces by space type (SPACE or GROUP_CHAT or
                  // DIRECT_MESSAGE).
                  .setFilter("spaceType = \"SPACE\"")
                  .build();
    
          // Iterate over results and resolve additional pages automatically.
          for (Space response : chatServiceClient.listSpaces(request).iterateAll()) {
            System.out.println(JsonFormat.printer().print(response));
          }
        }
      }
    }

サンプルの実行

  1. サンプルを実行する

    gradle run
    
  1. サンプルを初めて実行すると、アクセスの承認を求められます。
    1. Google アカウントにまだログインしていない場合は、ログインを求められたらログインします。条件 複数のアカウントにログインしている場合は、承認に使用するアカウントを 1 つ選択してください。
    2. [Accept] をクリックします。

    Java アプリケーションが実行され、Google Chat API が呼び出されます。

    認証情報はファイル システムに保存されるため、次回サンプルを実行する際に 承認を求められることはありません。

次のステップ