お客様向け Java クイックスタート

このクイックスタート ガイドの手順により、約 10 分でゼロタッチ登録の顧客 API にリクエストを行うシンプルな Java コマンドライン アプリを作成します。

Prerequisites

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

  • ゼロタッチ登録の顧客アカウントのメンバーである Google アカウント。スタートガイドをご覧ください。
  • Java 1.7 以降
  • Gradle 2.3 以降
  • インターネット アクセスとウェブブラウザ。

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

  1. このウィザードを使用して Google Cloud Console でプロジェクトを作成または選択し、API を自動的に有効にします。[続行]、[認証情報に移動] の順にクリックします。
  2. [認証情報を作成] で [キャンセル] をクリックします。
  3. ページ上部の [OAuth 同意画面] タブを選択します。[メールアドレス] を選択し、まだ設定されていない場合はプロダクト名を入力して、[保存] ボタンをクリックします。
  4. [認証情報] タブを選択し、[認証情報を作成] ボタンをクリックして、[OAuth クライアント ID] を選択します。
  5. アプリケーション タイプとして [その他] を選択し、「クイックスタート」という名前を入力して、[作成] ボタンをクリックします。
  6. [OK] をクリックして [OAuth クライアント] パネルを閉じます。
  7. [ JSON をダウンロード] をクリックします。
  8. 作業ディレクトリにファイルを移動し、名前を client_secret.json に変更します。

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

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

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

    gradle init --type basic
    mkdir -p src/main/java src/main/resources
    
  2. ステップ 1 でダウンロードした client_secret.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.oauth-client:google-oauth-client-jetty:1.34.1'
}

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

src/main/java/CustomerQuickstart.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.http.HttpTransport;
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.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 java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;

/** This class forms the quickstart introduction to the zero-touch enrollemnt 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";
  private static final java.io.File DATA_STORE_DIR =
      new java.io.File(System.getProperty("user.home"), ".credentials/zero-touch.quickstart.json");

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

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

  /**
   * Creates a Credential object with the correct OAuth2 authorization for the user calling the
   * customer API. The service endpoint invokes this method when setting up a new service instance.
   *
   * @return an authorized Credential object.
   * @throws IOException
   */
  public static Credential authorize() throws IOException {
    // Load client secrets.
    InputStream in = CustomerQuickstart.class.getResourceAsStream("/client_secret.json");

    GoogleClientSecrets clientSecrets =
        GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in, "UTF-8"));

    // Ask the user to authorize the request using their Google Account
    // in their browser.
    GoogleAuthorizationCodeFlow flow =
        new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(DATA_STORE_FACTORY)
            .setAccessType("offline")
            .build();
    Credential credential =
        new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    System.out.println("Credential file saved to: " + DATA_STORE_DIR.getAbsolutePath());
    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 {
    Credential credential = authorize();
    return new AndroidProvisioningPartner.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
        .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

アプリを初めて実行するときは、アクセスを承認する必要があります。

  1. アプリがデフォルトのブラウザで新しいタブを開こうとします。失敗した場合は、コンソールから URL をコピーして、ブラウザで開きます。Google アカウントにまだログインしていない場合は、ログインを求められます。複数の Google アカウントにログインしている場合、認可に使用するアカウントを選択するよう求められます。
  2. [同意する] をクリックします。
  3. ブラウザタブを閉じます。アプリの実行は続行されます。

メモ

  • Google API クライアント ライブラリはファイル システムに認可データを保存するため、後続の起動では認可のプロンプトは表示されません。
  • アプリの承認データをリセットするには、~/.credentials/zero-touch.quickstart.json ファイルを削除してアプリを再度実行します。
  • このクイックスタートの承認フローは、コマンドライン アプリに最適です。ウェブアプリに承認を追加する方法については、 OAuth 2.0 ウェブサーバー アプリケーションをご覧ください。

トラブルシューティング

確認する一般的な項目は次のとおりです。 クイックスタートで 問題が発生した点を Google にお知らせください。解決に向けて対応いたします。

  • ゼロタッチ登録の顧客メンバーと同じ Google アカウントを使用した API 呼び出しを承認していることを確認します。同じ Google アカウントを使用してゼロタッチ登録のポータルにログインし、アクセスをテストします。
  • アカウントがポータルの最新の利用規約に同意していることを確認します。 顧客アカウントをご覧ください。

その他の情報