Panduan memulai Java

Buat aplikasi command line Java yang membuat permintaan ke Google Chat API.

Panduan memulai menjelaskan cara menyiapkan dan menjalankan aplikasi yang memanggil Google Workspace API. Panduan memulai ini menggunakan pendekatan autentikasi yang disederhanakan dan sesuai untuk lingkungan pengujian. Untuk lingkungan produksi, sebaiknya pelajari autentikasi dan otorisasi sebelum memilih kredensial akses yang sesuai untuk aplikasi Anda.

Panduan memulai ini menggunakan library klien API yang direkomendasikan Google Workspace untuk menangani beberapa detail alur autentikasi dan otorisasi.

Tujuan

  • Menyiapkan lingkungan Anda.
  • Menyiapkan contoh.
  • Menjalankan contoh.

Prasyarat

Menyiapkan lingkungan Anda

Untuk menyelesaikan panduan memulai ini, siapkan lingkungan Anda.

Mengaktifkan API

Sebelum menggunakan Google API, Anda harus mengaktifkannya di project Google Cloud. Anda dapat mengaktifkan satu atau beberapa API dalam satu project Google Cloud.

Jika Anda menggunakan project Google Cloud baru untuk menyelesaikan panduan memulai ini, konfigurasikan layar izin OAuth. Jika Anda telah menyelesaikan langkah ini untuk project Cloud, lewati ke bagian berikutnya.

  1. Di Konsol API Google, buka Menu > Platform Google Auth > Branding.

    Buka Branding

  2. Jika telah mengonfigurasi platform Google Auth, Anda dapat mengonfigurasi setelan Layar Izin OAuth berikut di Branding, Audiens, dan Akses Data. Jika Anda melihat pesan yang menyatakan Google Auth platform not configured yet, klik Get Started:
    1. Di bagian App Information, di App name, masukkan nama untuk aplikasi.
    2. Di User support email, pilih alamat email dukungan tempat pengguna dapat menghubungi Anda jika mereka memiliki pertanyaan tentang izin mereka.
    3. Klik Next.
    4. Di bagian Audience, pilih Internal.
    5. Klik Next.
    6. Di bagian Contact Information, masukkan Email address tempat Anda dapat diberi tahu tentang perubahan apa pun pada project Anda.
    7. Klik Next.
    8. Di bagian Finish, tinjau Kebijakan Data Pengguna Layanan Google API dan jika Anda setuju, pilih I agree to the Google API Services: User Data Policy.
    9. Klik Continue.
    10. Klik Create.
  3. Untuk saat ini, Anda dapat melewati penambahan cakupan. Pada masa mendatang, saat membuat aplikasi untuk digunakan di luar organisasi Google Workspace Anda, Anda harus mengubah User type menjadi External. Kemudian, tambahkan cakupan otorisasi yang diperlukan aplikasi Anda. Untuk mempelajari lebih lanjut, lihat panduan lengkap Mengonfigurasi izin OAuth guide.

Mengotorisasi kredensial untuk aplikasi desktop

Untuk mengautentikasi pengguna akhir dan mengakses data pengguna di aplikasi Anda, Anda harus membuat satu atau beberapa Client ID OAuth 2.0. Client ID digunakan untuk mengidentifikasi aplikasi tunggal ke server OAuth Google. Jika aplikasi Anda berjalan di beberapa platform, Anda harus membuat client ID terpisah untuk setiap platform.
  1. Di Konsol Google Cloud, buka Menu > Platform Google Auth > Clients.

    Buka Klien

  2. Klik Create Client.
  3. Klik Application type > Desktop app.
  4. Di kolom Name, ketik nama untuk kredensial. Nama ini hanya ditampilkan di Konsol Google Cloud.
  5. Klik Create.

    Kredensial yang baru dibuat akan muncul di bagian "Client ID OAuth 2.0".

  6. Simpan file JSON yang didownload sebagai credentials.json, lalu pindahkan file ke direktori kerja Anda.

Mengonfigurasi aplikasi Google Chat

Untuk memanggil Google Chat API, Anda harus mengonfigurasi aplikasi Google Chat. Untuk permintaan tulis apa pun, Google Chat akan mengaitkan aplikasi Google Chat di UI menggunakan informasi berikut.

  1. Di Konsol API Google, buka halaman Configuration Chat API:

    Buka halaman Konfigurasi Chat API

  2. Di bagian Application info, masukkan informasi berikut:

    1. Di kolom App name, masukkan Chat API quickstart app.
    2. Di kolom Avatar URL, masukkan https://developers.google.com/chat/images/quickstart-app-avatar.png.
    3. Di kolom Description, masukkan Quickstart for calling the Chat API.
  3. Di bagian Interactive features, klik tombol Enable interactive features ke posisi nonaktif untuk menonaktifkan fitur interaktif untuk aplikasi Chat.

  4. Klik Save.

Menyiapkan ruang kerja

  1. Di direktori kerja Anda, buat struktur project baru:

    gradle init --type basic
    mkdir -p src/main/java src/main/resources 
    
  2. Di direktori src/main/resources/, salin file credentials.json yang sebelumnya Anda download.

  3. Buka file build.gradle default dan ganti kontennya dengan kode berikut:

    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'
    }

Menyiapkan contoh

  1. Di direktori src/main/java/, buat file Java baru dengan nama yang cocok dengan nilai mainClassName di file build.gradle Anda.

  2. Sertakan kode berikut di file Java baru Anda:

    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));
          }
        }
      }
    }

Menjalankan contoh

  1. Jalankan contoh:

    gradle run
    
  1. Saat pertama kali dijalankan, contoh aplikasi meminta Anda untuk mengotorisasi akses:
    1. Jika Anda belum login ke Akun Google, login saat diminta. Jika Anda login ke beberapa akun, pilih satu akun yang akan digunakan untuk otorisasi.
    2. Klik Accept.

    Aplikasi Java Anda berjalan dan memanggil Google Chat API.

    Informasi otorisasi disimpan dalam sistem file, sehingga saat Anda menjalankan kode contoh pada lain waktu, Anda tidak akan diminta untuk memberikan otorisasi.

Langkah berikutnya