Guida rapida di Java

Le guide rapide spiegano come configurare ed eseguire un'app che chiama un'API Google Workspace.

Le guide rapide di Google Workspace utilizzano le librerie client delle API per gestire alcuni dettagli del flusso di autenticazione e autorizzazione. Ti consigliamo di utilizzare le librerie client per le tue app. Questa guida rapida utilizza un approccio di autenticazione semplificato appropriato per un ambiente di test. Per un ambiente di produzione, ti consigliamo di informarti su autenticazione e autorizzazione prima di scegliere le credenziali di accesso appropriate per la tua app.

Crea un'applicazione a riga di comando Java che invia richieste all'API Google Drive Activity.

Obiettivi

  • Configurare l'ambiente.
  • Configura il campione.
  • Esegui l'esempio.

Prerequisiti

  • Un Account Google.

configura l'ambiente

Per completare questa guida rapida, configura il tuo ambiente.

Abilita l'API

Prima di utilizzare le API di Google, devi attivarle in un progetto Google Cloud. Puoi attivare una o più API in un singolo progetto Google Cloud.
  • Nella console Google Cloud, abilita l'API Google Drive Activity.

    Abilita l'API

Se utilizzi un nuovo progetto Google Cloud per completare questa guida rapida, configura la schermata per il consenso OAuth e aggiungiti come utente di test. Se hai già completato questo passaggio per il tuo progetto Cloud, vai alla sezione successiva.

  1. Nella console Google Cloud, vai a Menu > API e servizi > Schermata consenso OAuth.

    Vai alla schermata per il consenso OAuth

  2. In Tipo di utente, seleziona Interno e poi fai clic su Crea.
  3. Compila il modulo di registrazione dell'app, poi fai clic su Salva e continua.
  4. Per il momento, puoi saltare l'aggiunta di ambiti e fare clic su Salva e continua. In futuro, quando creerai un'app da utilizzare al di fuori della tua organizzazione Google Workspace, dovrai cambiare Tipo di utente in Esterno e poi aggiungere gli ambiti di autorizzazione richiesti dalla tua app.

  5. Rivedi il riepilogo della registrazione dell'app. Per apportare modifiche, fai clic su Modifica. Se la registrazione dell'app è corretta, fai clic su Torna alla dashboard.

Autorizza le credenziali per un'applicazione desktop

Per autenticare gli utenti finali e accedere ai dati utente nella tua app, devi creare uno o più ID client OAuth 2.0. Un ID client viene utilizzato per identificare una singola app nei server OAuth di Google. Se l'app viene eseguita su più piattaforme, devi creare un ID client separato per ogni piattaforma.
  1. Nella console Google Cloud, vai a Menu > API e servizi > Credenziali.

    Vai a Credenziali

  2. Fai clic su Crea credenziali > ID client OAuth.
  3. Fai clic su Tipo di applicazione > App desktop.
  4. Nel campo Nome, digita un nome per la credenziale. Questo nome viene visualizzato solo nella console Google Cloud.
  5. Fai clic su Crea. Viene visualizzata la schermata Creazione del client OAuth, in cui sono indicati il nuovo ID client e il client secret.
  6. Fai clic su Ok. La credenziale appena creata viene visualizzata in ID client OAuth 2.0.
  7. Salva il file JSON scaricato come credentials.json e spostalo nella directory di lavoro.

Prepara l'area di lavoro

  1. Nella directory di lavoro, crea una nuova struttura di progetto:

    gradle init --type basic
    mkdir -p src/main/java src/main/resources 
    
  2. Nella directory src/main/resources/, copia il file credentials.json che hai scaricato in precedenza.

  3. Apri il file build.gradle predefinito e sostituiscine il contenuto con il seguente codice:

    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'
    }
    

Configura il Sample

  1. Nella directory src/main/java/, crea un nuovo file Java con un nome che corrisponda al valore mainClassName nel file build.gradle.

  2. Includi il seguente codice nel nuovo file 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);
      }
    }

esegui l'esempio

  1. Esegui l'esempio:

    gradle run
    
  1. La prima volta che esegui l'esempio, ti viene richiesto di autorizzare l'accesso:
    1. Se non hai ancora eseguito l'accesso al tuo Account Google, accedi quando ti viene richiesto. Se hai eseguito l'accesso a più account, selezionane uno da utilizzare per l'autorizzazione.
    2. Fai clic su Accept (accetta).

    L'applicazione Java viene eseguita e chiama l'API Google Drive Activity.

    Le informazioni sull'autorizzazione sono archiviate nel file system, pertanto, la prossima volta che esegui il codice di esempio, non viene richiesta l'autorizzazione.

Passaggi successivi