サービス アカウントを使用するお客様向けの Java クイックスタート

このクイックスタート ガイドの手順に沿って操作すると、約 10 分で簡単な Java コマンドライン アプリが作成され、サービス アカウントを使用してゼロタッチ登録の顧客 API にリクエストを行うことができます。

Prerequisites

このクイックスタートを実行するには、次の準備が必要です。

  • ゼロタッチ登録のお客様アカウントにリンクされたサービス アカウント。スタートガイドをご覧ください。
  • Java 1.7 以降
  • Gradle 2.3 以降
  • インターネット アクセスとウェブブラウザ。

ステップ 1: ゼロタッチ登録 API を有効にする

  1. このウィザードを使用して Google Cloud Console でプロジェクトを作成または選択し、API を自動的に有効にします。[続行]、[認証情報に移動] の順にクリックします。
  2. [アクセス対象のデータ] を [アプリケーション データ] に設定します。
  3. [Next] をクリックします。サービス アカウントを作成するよう求められます。
  4. [サービス アカウント名] にわかりやすい名前を付けます。
  5. サービス アカウント ID は後で使用しますので、メモしておきます(メールアドレスのように見えます)。
  6. ロール[サービス アカウント] > [サービス アカウント ユーザー] に設定します。
  7. [完了] をクリックして、サービス アカウントの作成を完了します。
  8. 作成したサービス アカウントのメールアドレスをクリックします。
  9. [**キー**] をクリックします。
  10. [鍵を追加] をクリックしてから、[新しい鍵を作成] をクリックします。
  11. [キーのタイプ] で [JSON] を選択します。
  12. [作成] をクリックして、秘密鍵がパソコンにダウンロードされます。
  13. [**閉じる**] をクリックします。
  14. 作業ディレクトリにファイルを移動し、名前を service_account_key.json に変更します。

ステップ 2: プロジェクトを準備する

Gradle プロジェクトを設定する手順は次のとおりです。

  1. 次のコマンドを実行して、作業ディレクトリに新しいプロジェクトを作成します。

    gradle init --type basic
    mkdir -p src/main/java src/main/resources
    
  2. サービス アカウントの作成時にダウンロードした service_account_key.json を、先ほど作成した src/main/resources/ ディレクトリにコピーします。

  3. デフォルトの build.gradle ファイルを開き、その内容を次のコードに置き換えます。

apply plugin: 'java'
apply plugin: 'application'

mainClassName = 'CustomerQuickstart'
sourceCompatibility = 1.7
targetCompatibility = 1.7
version = '1.0'

repositories {
    mavenCentral()
}

dependencies {
    compile 'com.google.api-client:google-api-client:2.2.0'
    compile 'com.google.apis:google-api-services-androiddeviceprovisioning:v1-rev20230509-2.0.0'
    compile 'com.google.auth:google-auth-library-oauth2-http:1.16.1'
    compile 'com.google.auth:google-auth-library-credentials:1.16.1'
    compile 'com.google.http-client:google-http-client:1.43.1'
    compile 'com.google.oauth-client:google-oauth-client-jetty:1.34.1'
}

手順 3: サンプルをセットアップする

src/main/java/CustomerQuickstart.java という名前のファイルを作成して次のコードをコピーし、ファイルを保存します。

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.androiddeviceprovisioning.v1.AndroidProvisioningPartner;
import com.google.api.services.androiddeviceprovisioning.v1.model.Company;
import com.google.api.services.androiddeviceprovisioning.v1.model.CustomerListCustomersResponse;
import com.google.api.services.androiddeviceprovisioning.v1.model.CustomerListDpcsResponse;
import com.google.api.services.androiddeviceprovisioning.v1.model.Dpc;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

/** This class forms the quickstart introduction to the zero-touch enrollment customer API. */
public class CustomerQuickstart {

  // A single auth scope is used for the zero-touch enrollment customer API.
  private static final List<String> SCOPES =
      Arrays.asList("https://www.googleapis.com/auth/androidworkzerotouchemm");
  private static final String APP_NAME = "Zero-touch Enrollment Java Quickstart";

  // Global shared instances
  private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
  private static HttpTransport HTTP_TRANSPORT;

  static {
    try {
      HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    } catch (Throwable t) {
      t.printStackTrace();
      System.exit(1);
    }
  }

  /**
   * Creates a GoogleCredentials object with the correct OAuth2 authorization for the service
   * account that calls the reseller API. The service endpoint invokes this method when setting up a
   * new service instance.
   *
   * @return an authorized GoogleCredentials object.
   * @throws IOException
   */
  public static GoogleCredentials authorize() throws IOException {
    // Load service account key.
    InputStream in = CustomerQuickstart.class.getResourceAsStream("/service_account_key.json");

    // Create the credential scoped to the zero-touch enrollment customer APIs.
    GoogleCredentials credential = ServiceAccountCredentials.fromStream(in).createScoped(SCOPES);
    return credential;
  }

  /**
   * Build and return an authorized zero-touch enrollment API client service. Use the service
   * endpoint to call the API methods.
   *
   * @return an authorized client service endpoint
   * @throws IOException
   */
  public static AndroidProvisioningPartner getService() throws IOException {
    GoogleCredentials credential = authorize();
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credential);
    return new AndroidProvisioningPartner.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName(APP_NAME)
        .build();
  }

  /**
   * Runs the zero-touch enrollment quickstart app.
   *
   * @throws IOException
   */
  public static void main(String[] args) throws IOException {

    // Create a zero-touch enrollment API service endpoint.
    AndroidProvisioningPartner service = getService();

    // Get the customer's account. Because a customer might have more
    // than one, limit the results to the first account found.
    AndroidProvisioningPartner.Customers.List accountRequest = service.customers().list();
    accountRequest.setPageSize(1);
    CustomerListCustomersResponse accountResponse = accountRequest.execute();
    if (accountResponse.getCustomers().isEmpty()) {
      // No accounts found for the user. Confirm the Google Account
      // that authorizes the request can access the zero-touch portal.
      System.out.println("No zero-touch enrollment account found.");
      System.exit(-1);
    }
    Company customer = accountResponse.getCustomers().get(0);
    String customerAccount = customer.getName();

    // Send an API request to list all the DPCs available using the customer account.
    AndroidProvisioningPartner.Customers.Dpcs.List request =
        service.customers().dpcs().list(customerAccount);
    CustomerListDpcsResponse response = request.execute();

    // Print out the details of each DPC.
    java.util.List<Dpc> dpcs = response.getDpcs();
    for (Dpc dpcApp : dpcs) {
      System.out.format("Name:%s  APK:%s\n", dpcApp.getDpcName(), dpcApp.getPackageName());
    }
  }
}

ステップ 4: サンプルを実行する

オペレーティング システムのヘルプを使用して、ファイル内のスクリプトを実行します。UNIX と Mac のパソコンの場合は、ターミナルで次のコマンドを実行します。

gradle -q run

メモ

その他の情報