מדריך למתחילים ל-Java ללקוחות שמשתמשים בחשבון שירות

במדריך למתחילים הזה תלמדו איך, ובעוד כ-10 דקות, תהיה לכם אפליקציית שורת פקודה פשוטה של Java שמבצעת בקשות ל-API של ההרשמה דרך הארגון דרך חשבון שירות.

דרישות מוקדמות

כדי להפעיל את המדריך למתחילים, צריך:

  • חשבון שירות שמקושר לחשבון הלקוח בהרשמה דרך הארגון. קראו את המאמר תחילת העבודה.
  • Java 1.7 ומעלה.
  • Gradle 2.3 ומעלה.
  • גישה לאינטרנט ולדפדפן אינטרנט.

שלב 1: הפעלת ה-API של ההרשמה דרך הארגון

  1. בעזרת האשף הזה אפשר ליצור או לבחור פרויקט ב-Google Developers Console ולהפעיל את ה-API באופן אוטומטי. לוחצים על Continue (המשך), ואז על Credentials .
  2. מגדירים שאל אילו נתונים נכנסים? נתוני אפליקציה.
  3. לוחצים על הבא. אמורה להופיע בקשה ליצור חשבון שירות.
  4. נותנים שם תיאורי לשם חשבון השירות.
  5. כדאי לרשום את מספר חשבון השירות (נראה כמו כתובת אימייל), כי הוא ישמש אותך בהמשך.
  6. מגדירים את התפקיד כחשבונות שירות > משתמש בחשבון שירות.
  7. לוחצים על Done כדי לסיים ליצור את חשבון השירות.
  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

הערות

מידע נוסף