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

このクイックスタート ガイドの手順を実施すると、約 10 分で ゼロタッチにリクエストを送信するシンプルな Java コマンドライン アプリ 登録ユーザー API です。

前提条件

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

  • Google アカウント(ゼロタッチ登録のお客様のメンバー) あります。詳しくは、 開始されました
  • Java 1.7 以降。
  • Gradle 2.3 以降
  • インターネット アクセスとウェブブラウザ。

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

  1. こちらの ウィザードを使用して、Google Developers Console でプロジェクトを作成または選択し、 API が自動的に有効になります。[続行] をクリックし、[認証情報に進む] をクリックします。
  2. [認証情報の作成] で [キャンセル] をクリックします。
  3. ページ上部の [OAuth 同意画面] タブを選択します。以下を選択します。 [Email address]: まだ設定されていない場合は [Product name] を入力します。 [保存] ボタンをクリックします。
  4. [認証情報] タブを選択し、[認証情報を作成] をクリックします。 ボタンをクリックし、[OAuth クライアント ID] を選択します。
  5. アプリケーション タイプとして [その他] を選択し、名前を入力します。 [クイックスタート] を選択し、[Create] をクリックします。 ] ボタンを離します。
  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. アプリがデフォルトのブラウザで新しいタブを開こうとします。失敗した場合は、 ブラウザで開きますGoogle アカウントにまだログインしていない場合は、 ログインするように求められます。複数の Google アカウントにログインしている場合は、 承認のためのアカウントを作成します
  2. [Accept] をクリックします。
  3. ブラウザタブを閉じてもアプリは実行を継続します。

メモ

  • Google API クライアント ライブラリは認証データをファイル システムに格納するため、 承認は求められません。
  • アプリの認証データをリセットするには、 ~/.credentials/zero-touch.quickstart.json ファイルを実行し、アプリを再度実行します。
  • このクイックスタートの承認フローは、コマンドライン アプリに最適です。Google Chat で 認証については、をご覧ください。 OAuth 2.0 ウェブサーバー アプリケーションをご覧ください。

トラブルシューティング

確認する必要がある一般的な事項は次のとおりです。 クイックスタートの問題点をお聞かせください。修正いたします。

  • お客様のメンバーと同じ Google アカウントで API 呼び出しを承認していることを ゼロタッチ登録の顧客アカウント以下を使用してゼロタッチ登録ポータルにログインしてみてください。 同じ Google アカウントを使ってアクセスをテストします。
  • アカウントが、 ポータル。<ph type="x-smartling-placeholder"></ph>をご覧ください。 顧客アカウント

その他の情報