คู่มือเริ่มใช้งานฉบับย่อของ Java

การเริ่มต้นอย่างรวดเร็วอธิบายวิธีตั้งค่าและเรียกใช้แอปที่เรียกใช้ Google Workspace API

การเริ่มต้นใช้งาน Google Workspace อย่างรวดเร็วจะใช้ไลบรารีของไคลเอ็นต์ API เพื่อจัดการรายละเอียดบางอย่างของขั้นตอนการตรวจสอบสิทธิ์และการให้สิทธิ์ เราขอแนะนำให้คุณใช้ไลบรารีของไคลเอ็นต์สำหรับแอปของคุณเอง การเริ่มต้นอย่างรวดเร็วนี้ใช้วิธีการการตรวจสอบสิทธิ์ที่เรียบง่ายซึ่งเหมาะสำหรับสภาพแวดล้อมการทดสอบ สำหรับสภาพแวดล้อมเวอร์ชันที่ใช้งานจริง เราขอแนะนำให้เรียนรู้เกี่ยวกับการตรวจสอบสิทธิ์และการให้สิทธิ์ก่อนเลือกข้อมูลเข้าสู่ระบบที่เหมาะกับแอปของคุณ

สร้างแอปพลิเคชันบรรทัดคำสั่ง Java ที่ส่งคำขอไปยัง Google Drive Activity API

วัตถุประสงค์

  • ตั้งค่าสภาพแวดล้อมของคุณ
  • ตั้งค่าตัวอย่าง
  • เรียกใช้ตัวอย่าง

ข้อกำหนดเบื้องต้น

  • บัญชี Google

ตั้งค่าสภาพแวดล้อมของคุณ

ตั้งค่าสภาพแวดล้อมเพื่อให้การเริ่มต้นอย่างรวดเร็วนี้เสร็จสมบูรณ์

เปิดใช้ API

ก่อนใช้ Google APIs คุณต้องเปิดใช้ API ในโปรเจ็กต์ Google Cloud คุณเปิด API ได้มากกว่า 1 รายการในโปรเจ็กต์ Google Cloud เดียว
  • ในคอนโซล Google Cloud ให้เปิดใช้ API กิจกรรม Google ไดรฟ์

    เปิดใช้ API

หากคุณใช้โปรเจ็กต์ Google Cloud ใหม่เพื่อให้การเริ่มต้นอย่างรวดเร็วนี้เสร็จสมบูรณ์ ให้กำหนดค่าหน้าจอขอความยินยอม OAuth และเพิ่มตัวคุณเองเป็นผู้ใช้ทดสอบ หากทำตามขั้นตอนนี้สำหรับโปรเจ็กต์ที่อยู่ในระบบคลาวด์เรียบร้อยแล้ว ให้ข้ามไปยังส่วนถัดไป

  1. ในคอนโซล Google Cloud ให้ไปที่เมนู > API และบริการ > หน้าจอขอความยินยอม OAuth

    ไปที่หน้าจอขอความยินยอม OAuth

  2. สำหรับประเภทผู้ใช้ ให้เลือกภายใน แล้วคลิกสร้าง
  3. กรอกแบบฟอร์มการลงทะเบียนแอปให้เสร็จสมบูรณ์ แล้วคลิกบันทึกและดำเนินการต่อ
  4. สำหรับตอนนี้ คุณอาจข้ามการเพิ่มขอบเขต แล้วคลิกบันทึกและต่อไป ในอนาคต เมื่อสร้างแอปเพื่อใช้นอกองค์กร Google Workspace คุณจะต้องเปลี่ยนประเภทผู้ใช้เป็นภายนอก จากนั้นจึงเพิ่มขอบเขตการให้สิทธิ์ที่แอปต้องการ

  5. ดูสรุปการลงทะเบียนแอป หากต้องการเปลี่ยนแปลง ให้คลิกแก้ไข หากการลงทะเบียนแอปถูกต้องแล้ว ให้คลิกกลับไปยังหน้าแดชบอร์ด

ให้สิทธิ์ข้อมูลเข้าสู่ระบบสำหรับแอปพลิเคชันเดสก์ท็อป

หากต้องการตรวจสอบสิทธิ์ผู้ใช้ปลายทางและเข้าถึงข้อมูลผู้ใช้ในแอป คุณต้องสร้างรหัสไคลเอ็นต์ OAuth 2.0 อย่างน้อย 1 รายการ รหัสไคลเอ็นต์ใช้เพื่อระบุแอปเดียวไปยังเซิร์ฟเวอร์ OAuth ของ Google หากแอปทำงานในหลายแพลตฟอร์ม คุณต้องสร้างรหัสไคลเอ็นต์แยกกันสำหรับแต่ละแพลตฟอร์ม
  1. ในคอนโซล Google Cloud ให้ไปที่เมนู > API และบริการ > ข้อมูลเข้าสู่ระบบ

    ไปที่ข้อมูลเข้าสู่ระบบ

  2. คลิกสร้างข้อมูลเข้าสู่ระบบ > รหัสไคลเอ็นต์ OAuth
  3. คลิกประเภทแอปพลิเคชัน > แอปบนเดสก์ท็อป
  4. ในช่องชื่อ ให้พิมพ์ชื่อของข้อมูลเข้าสู่ระบบ ชื่อนี้จะแสดงในคอนโซล Google Cloud เท่านั้น
  5. คลิกสร้าง หน้าจอที่สร้างของไคลเอ็นต์ OAuth จะปรากฏขึ้นเพื่อแสดงรหัสไคลเอ็นต์และรหัสลับไคลเอ็นต์ใหม่
  6. คลิกตกลง ข้อมูลเข้าสู่ระบบที่สร้างขึ้นใหม่จะปรากฏในส่วนรหัสไคลเอ็นต์ OAuth 2.0
  7. บันทึกไฟล์ JSON ที่ดาวน์โหลดเป็น credentials.json และย้ายไฟล์ไปยังไดเรกทอรีการทำงาน

เตรียมพื้นที่ทำงาน

  1. สร้างโครงสร้างโปรเจ็กต์ใหม่ในไดเรกทอรีการทำงาน ดังนี้

    gradle init --type basic
    mkdir -p src/main/java src/main/resources 
    
  2. ในไดเรกทอรี src/main/resources/ ให้คัดลอกไฟล์ credentials.json ที่คุณดาวน์โหลดไว้ก่อนหน้านี้

  3. เปิดไฟล์ build.gradle เริ่มต้นและแทนที่เนื้อหาด้วยโค้ดต่อไปนี้

    drive/activity-v2/quickstart/build.gradle
    apply plugin: 'java'
    apply plugin: 'application'
    
    mainClassName = 'DriveActivityQuickstart'
    sourceCompatibility = 11
    targetCompatibility = 11
    version = '1.0'
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        implementation 'com.google.api-client:google-api-client:2.0.0'
        implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1'
        implementation 'com.google.apis:google-api-services-driveactivity:v2-rev20220926-2.0.0'
    }
    

ตั้งค่าตัวอย่าง

  1. ในไดเรกทอรี src/main/java/ ให้สร้างไฟล์ Java ใหม่ที่มีชื่อตรงกับค่า mainClassName ในไฟล์ build.gradle

  2. ใส่โค้ดต่อไปนี้ในไฟล์ Java ใหม่

    drive/activity-v2/quickstart/src/main/java/DriveActivityQuickstart.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.driveactivity.v2.DriveActivityScopes;
    import com.google.api.services.driveactivity.v2.model.*;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.AbstractMap;
    import java.util.Arrays;
    import java.util.Iterator;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class DriveActivityQuickstart {
      /**
       * Application name.
       */
      private static final String APPLICATION_NAME = "Drive Activity API Java Quickstart";
    
      /**
       * Directory to store authorization tokens for this application.
       */
      private static final java.io.File DATA_STORE_DIR = new java.io.File("tokens");
      /**
       * Global instance of the JSON factory.
       */
      private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
      /**
       * Global instance of the scopes required by this quickstart.
       *
       * <p>If modifying these scopes, delete your previously saved tokens/ folder.
       */
      private static final List<String> SCOPES =
          Arrays.asList(DriveActivityScopes.DRIVE_ACTIVITY_READONLY);
      private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
      /**
       * Global instance of the {@link FileDataStoreFactory}.
       */
      private static FileDataStoreFactory DATA_STORE_FACTORY;
      /**
       * Global instance of the HTTP transport.
       */
      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 an authorized Credential object.
       *
       * @return an authorized Credential object.
       * @throws IOException
       */
      public static Credential authorize() throws IOException {
        // Load client secrets.
        InputStream in = DriveActivityQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
        if (in == null) {
          throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
        }
        GoogleClientSecrets clientSecrets =
            GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
    
        // Build flow and trigger user authorization request.
        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("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
        return credential;
      }
    
      /**
       * Build and return an authorized Drive Activity client service.
       *
       * @return an authorized DriveActivity client service
       * @throws IOException
       */
      public static com.google.api.services.driveactivity.v2.DriveActivity getDriveActivityService()
          throws IOException {
        Credential credential = authorize();
        com.google.api.services.driveactivity.v2.DriveActivity service =
            new com.google.api.services.driveactivity.v2.DriveActivity.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME)
                .build();
        return service;
      }
    
      public static void main(String[] args) throws IOException {
        // Build a new authorized API client service.
        com.google.api.services.driveactivity.v2.DriveActivity service = getDriveActivityService();
    
        // Print the recent activity in your Google Drive.
        QueryDriveActivityResponse result =
            service.activity().query(new QueryDriveActivityRequest().setPageSize(10)).execute();
        List<DriveActivity> activities = result.getActivities();
        if (activities == null || activities.size() == 0) {
          System.out.println("No activity.");
        } else {
          System.out.println("Recent activity:");
          for (DriveActivity activity : activities) {
            String time = getTimeInfo(activity);
            String action = getActionInfo(activity.getPrimaryActionDetail());
            List<String> actors =
                activity.getActors().stream()
                    .map(DriveActivityQuickstart::getActorInfo)
                    .collect(Collectors.toList());
            List<String> targets =
                activity.getTargets().stream()
                    .map(DriveActivityQuickstart::getTargetInfo)
                    .collect(Collectors.toList());
            System.out.printf(
                "%s: %s, %s, %s\n", time, truncated(actors), action, truncated(targets));
          }
        }
      }
    
      /**
       * Returns a string representation of the first elements in a list.
       */
      private static String truncated(List<String> array) {
        return truncatedTo(array, 2);
      }
    
      /**
       * Returns a string representation of the first elements in a list.
       */
      private static String truncatedTo(List<String> array, int limit) {
        String contents = array.stream().limit(limit).collect(Collectors.joining(", "));
        String more = array.size() > limit ? ", ..." : "";
        return "[" + contents + more + "]";
      }
    
      /**
       * Returns the name of a set property in an object, or else "unknown".
       */
      private static <T> String getOneOf(AbstractMap<String, T> obj) {
        Iterator<String> iterator = obj.keySet().iterator();
        return iterator.hasNext() ? iterator.next() : "unknown";
      }
    
      /**
       * Returns a time associated with an activity.
       */
      private static String getTimeInfo(DriveActivity activity) {
        if (activity.getTimestamp() != null) {
          return activity.getTimestamp();
        }
        if (activity.getTimeRange() != null) {
          return activity.getTimeRange().getEndTime();
        }
        return "unknown";
      }
    
      /**
       * Returns the type of action.
       */
      private static String getActionInfo(ActionDetail actionDetail) {
        return getOneOf(actionDetail);
      }
    
      /**
       * Returns user information, or the type of user if not a known user.
       */
      private static String getUserInfo(User user) {
        if (user.getKnownUser() != null) {
          KnownUser knownUser = user.getKnownUser();
          Boolean isMe = knownUser.getIsCurrentUser();
          return (isMe != null && isMe) ? "people/me" : knownUser.getPersonName();
        }
        return getOneOf(user);
      }
    
      /**
       * Returns actor information, or the type of actor if not a user.
       */
      private static String getActorInfo(Actor actor) {
        if (actor.getUser() != null) {
          return getUserInfo(actor.getUser());
        }
        return getOneOf(actor);
      }
    
      /**
       * Returns the type of a target and an associated title.
       */
      private static String getTargetInfo(Target target) {
        if (target.getDriveItem() != null) {
          return "driveItem:\"" + target.getDriveItem().getTitle() + "\"";
        }
        if (target.getDrive() != null) {
          return "drive:\"" + target.getDrive().getTitle() + "\"";
        }
        if (target.getFileComment() != null) {
          DriveItem parent = target.getFileComment().getParent();
          if (parent != null) {
            return "fileComment:\"" + parent.getTitle() + "\"";
          }
          return "fileComment:unknown";
        }
        return getOneOf(target);
      }
    }

เรียกใช้ตัวอย่าง

  1. เรียกใช้ตัวอย่าง

    gradle run
    
  1. ครั้งแรกที่เรียกใช้ตัวอย่าง ระบบจะแสดงข้อความแจ้งให้คุณให้สิทธิ์เข้าถึง
    1. หากยังไม่ได้ลงชื่อเข้าใช้บัญชี Google ให้ลงชื่อเข้าใช้เมื่อได้รับข้อความแจ้ง หากคุณลงชื่อเข้าใช้หลายบัญชี ให้เลือก 1 บัญชีที่จะใช้ในการให้สิทธิ์
    2. คลิกยอมรับ

    แอปพลิเคชัน Java จะเรียกใช้และเรียก Google Drive Activity API

    ระบบไฟล์เก็บข้อมูลการให้สิทธิ์ไว้ ดังนั้นเมื่อคุณเรียกใช้โค้ดตัวอย่างในครั้งถัดไป คุณจะไม่ได้รับข้อความแจ้งให้ให้สิทธิ์

ขั้นตอนถัดไป