### Install play-services-basement.aar as a local Maven dependency Source: https://github.com/googleapis/google-api-java-client/blob/main/README.md This command sequence downloads the play-services-basement.aar file, unzips it, and installs it as a local Maven dependency. This is a one-time setup procedure. ```bash mkdir /tmp/foo && cd /tmp/foo wget https://dl.google.com/dl/android/maven2/com/google/android/gms/play-services-basement/8.3.0/play-services-basement-8.3.0.aar unzip play-services-basement-8.3.0.aar mvn install:install-file \ -Dfile=classes.jar \ -DgroupId=com.google.android.google-play-services \ -DartifactId=google-play-services \ -Dversion=1 \ -Dpackaging=jar cd - ``` -------------------------------- ### Installed App OAuth Example Source: https://context7.com/googleapis/google-api-java-client/llms.txt Demonstrates the OAuth 2.0 authorization code flow for installed applications. It loads client secrets, builds a flow with offline access for refresh tokens, and authorizes user credentials. Use FileDataStoreFactory for persistence. ```java import com.google.api.client.auth.oauth2.AuthorizationCodeInstalledApp; 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.apache.v5.GoogleApache5HttpTransport; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; import com.google.api.client.json.gson.GsonFactory; import com.google.api.client.util.store.FileDataStoreFactory; import com.google.api.services.calendar.Calendar; import com.google.api.services.calendar.CalendarScopes; import java.io.File; import java.io.InputStreamReader; import java.util.Collections; public class InstalledAppOAuthExample { private static final File DATA_STORE_DIR = new File(System.getProperty("user.home"), ".credentials/calendar"); private static final GsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); public static Credential authorize() throws Exception { // Load client secrets from classpath resource GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(InstalledAppOAuthExample.class.getResourceAsStream("/client_secrets.json"))); // Build flow with offline access to get a refresh token GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( GoogleApache5HttpTransport.newTrustedTransport(), JSON_FACTORY, clientSecrets, Collections.singleton(CalendarScopes.CALENDAR)) .setDataStoreFactory(new FileDataStoreFactory(DATA_STORE_DIR)) .setAccessType("offline") .build(); // Opens browser, waits for callback on localhost, stores credential return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); } public static void main(String[] args) throws Exception { Credential credential = authorize(); Calendar service = new Calendar.Builder( GoogleApache5HttpTransport.newTrustedTransport(), JSON_FACTORY, credential) .setApplicationName("CalendarApp/1.0") .build(); // List next 10 events from primary calendar com.google.api.services.calendar.model.Events events = service.events().list("primary") .setMaxResults(10) .setSingleEvents(true) .setOrderBy("startTime") .execute(); events.getItems().forEach(e -> System.out.println(e.getSummary())); } } ``` -------------------------------- ### Authorize Installed Application with OAuth 2.0 Source: https://github.com/googleapis/google-api-java-client/wiki/OAuth2 This snippet demonstrates the authorization code flow for installed applications. It loads client secrets, sets up the authorization flow, and handles user authorization via a local server receiver. Requires a client_secrets.json file. ```java public static void main(String[] args) { try { httpTransport = GoogleNetHttpTransport.newTrustedTransport(); dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR); // authorization Credential credential = authorize(); // set up global Plus instance plus = new Plus.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName( APPLICATION_NAME).build(); // ... } private static Credential authorize() throws Exception { // load client secrets GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(PlusSample.class.getResourceAsStream("/client_secrets.json"))); // set up authorization code flow GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( httpTransport, JSON_FACTORY, clientSecrets, Collections.singleton(PlusScopes.PLUS_ME)).setDataStoreFactory( dataStoreFactory).build(); // authorize return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); } ``` -------------------------------- ### Resumable and Direct Media Download Example Source: https://context7.com/googleapis/google-api-java-client/llms.txt Downloads media content using MediaHttpDownloader, supporting both resumable and direct download methods. Resumable downloads automatically retry failed chunks. Attach a progress listener to monitor download progress and specify the output stream for the downloaded content. ```java import com.google.api.client.googleapis.media.MediaHttpDownloader; import com.google.api.client.googleapis.media.MediaHttpDownloaderProgressListener; import com.google.api.services.drive.Drive; import java.io.FileOutputStream; import java.io.OutputStream; public class MediaDownloadExample { static class DownloadProgress implements MediaHttpDownloaderProgressListener { @Override public void progressChanged(MediaHttpDownloader downloader) { switch (downloader.getDownloadState()) { case MEDIA_IN_PROGRESS: System.out.printf("Downloading: %.0f%%\n", downloader.getProgress() * 100); break; case MEDIA_COMPLETE: System.out.println("Download complete!"); break; } } } public static void downloadFile(Drive driveService, String fileId, String outputPath) throws Exception { try (OutputStream out = new FileOutputStream(outputPath)) { Drive.Files.Get request = driveService.files().get(fileId); // Attach progress listener and execute chunked download request.getMediaHttpDownloader() .setProgressListener(new DownloadProgress()); // For small files, switch to direct (single-request) download: // request.getMediaHttpDownloader().setDirectDownloadEnabled(true); request.executeMediaAndDownloadTo(out); } System.out.println("File saved to: " + outputPath); } } ``` -------------------------------- ### Build Drive Client with Apache 5 Transport Source: https://context7.com/googleapis/google-api-java-client/llms.txt Use `GoogleApache5HttpTransport.newTrustedTransport()` for the preferred HTTP transport. This example shows how to build a Drive client using application default credentials and the Gson factory. ```java import com.google.api.client.googleapis.apache.v5.GoogleApache5HttpTransport; import com.google.api.client.http.apache.v5.Apache5HttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.drive.Drive; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; import java.util.Collections; public class TransportExample { public static void main(String[] args) throws Exception { // Build Google-trusted Apache5 transport (mTLS auto-detected via env var) Apache5HttpTransport transport = GoogleApache5HttpTransport.newTrustedTransport(); // Obtain application default credentials scoped to Drive GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() .createScoped(Collections.singleton("https://www.googleapis.com/auth/drive.readonly")); // Build a Drive client using the transport Drive driveService = new Drive.Builder(transport, GsonFactory.getDefaultInstance(), new HttpCredentialsAdapter(credentials)) .setApplicationName("MyApp/1.0") .build(); // List files Drive.Files.List listRequest = driveService.files().list() .setPageSize(10) .setFields("nextPageToken, files(id, name)"); System.out.println(listRequest.execute().getFiles()); } } ``` -------------------------------- ### Resumable and Direct Media Upload Example Source: https://context7.com/googleapis/google-api-java-client/llms.txt Uploads files using MediaHttpUploader, supporting both resumable (default) and direct upload methods. Configure chunk size for resumable uploads and attach a progress listener to monitor the upload status. Ensure correct MIME type and file metadata are provided. ```java import com.google.api.client.googleapis.media.MediaHttpUploader; import com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener; import com.google.api.client.http.InputStreamContent; import com.google.api.services.drive.Drive; import com.google.api.services.drive.model.File; import java.io.BufferedInputStream; import java.io.FileInputStream; public class MediaUploadExample { static class ProgressLogger implements MediaHttpUploaderProgressListener { @Override public void progressChanged(MediaHttpUploader uploader) throws java.io.IOException { switch (uploader.getUploadState()) { case INITIATION_STARTED: System.out.println("Initiation started..."); break; case INITIATION_COMPLETE: System.out.println("Initiation complete."); break; case MEDIA_IN_PROGRESS: System.out.printf("Uploading: %.0f%%\n", uploader.getProgress() * 100); break; case MEDIA_COMPLETE: System.out.println("Upload complete!"); break; } } } public static void uploadFile(Drive driveService, java.io.File localFile) throws Exception { // Prepare metadata File fileMetadata = new File(); fileMetadata.setName(localFile.getName()); // Wrap file in a streaming content object InputStreamContent mediaContent = new InputStreamContent( "image/jpeg", new BufferedInputStream(new FileInputStream(localFile))); mediaContent.setLength(localFile.length()); // Create the insert request and attach progress listener Drive.Files.Create request = driveService.files().create(fileMetadata, mediaContent); request.getMediaHttpUploader() .setProgressListener(new ProgressLogger()) .setChunkSize(5 * 1024 * 1024); // 5 MB chunks (default: 10 MB) // For small files, switch to direct (single-request) upload: // request.getMediaHttpUploader().setDirectUploadEnabled(true); File uploaded = request.execute(); System.out.println("Uploaded file ID: " + uploaded.getId()); } } ``` -------------------------------- ### Resumable Media Upload with Service-Generated Libraries (Java) Source: https://github.com/googleapis/google-api-java-client/wiki/Media-Upload Implement a custom progress listener for resumable media uploads. This example shows how to handle different upload states and attach the listener to a file insert request. ```java class CustomProgressListener implements MediaHttpUploaderProgressListener { public void progressChanged(MediaHttpUploader uploader) throws IOException { switch (uploader.getUploadState()) { case INITIATION_STARTED: System.out.println("Initiation has started!"); break; case INITIATION_COMPLETE: System.out.println("Initiation is complete!"); break; case MEDIA_IN_PROGRESS: System.out.println(uploader.getProgress()); break; case MEDIA_COMPLETE: System.out.println("Upload is complete!"); } } } File mediaFile = new File("/tmp/driveFile.jpg"); InputStreamContent mediaContent = new InputStreamContent("image/jpeg", new BufferedInputStream(new FileInputStream(mediaFile))); mediaContent.setLength(mediaFile.length()); Drive.Files.Insert request = drive.files().insert(fileMetadata, mediaContent); request.getMediaHttpUploader().setProgressListener(new CustomProgressListener()); request.execute(); ``` -------------------------------- ### Initialize Google API Client on Android Source: https://github.com/googleapis/google-api-java-client/blob/main/docs/android.md Initializes the Google API client and credential using OAuth2 for Android. This setup is typically done in an Activity's onCreate method. ```java credential = GoogleAccountCredential.usingOAuth2(this, Collections.singleton(TasksScopes.TASKS)); SharedPreferences settings = getPreferences(Context.MODE_PRIVATE); credential.setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null)); // Tasks client service = new com.google.api.services.tasks.Tasks.Builder(httpTransport, jsonFactory, credential) .setApplicationName("Google-TasksAndroidSample/1.0").build(); ``` -------------------------------- ### Authorize Installed Application with Google API Client Source: https://github.com/googleapis/google-api-java-client/blob/main/docs/oauth-2.0.md Use this code to authorize an installed application using the OAuth 2.0 authorization code flow. It loads client secrets, sets up the flow, and handles user authorization. ```java public static void main(String[] args) { try { httpTransport = new NetHttpTransport(); dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR); // authorization Credential credential = authorize(); // set up global Plus instance plus = new Plus.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName( APPLICATION_NAME).build(); // ... } private static Credential authorize() throws Exception { // load client secrets GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(PlusSample.class.getResourceAsStream("/client_secrets.json"))); // set up authorization code flow GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( httpTransport, JSON_FACTORY, clientSecrets, Collections.singleton(PlusScopes.PLUS_ME)).setDataStoreFactory( dataStoreFactory).build(); // authorize return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); } ``` -------------------------------- ### Android OAuth 2.0 Integration Example Source: https://github.com/googleapis/google-api-java-client/wiki/OAuth2 This snippet demonstrates how to set up and use OAuth 2.0 for Google API access within an Android application. It includes credential creation, account selection, and handling authorization results. Ensure you have the necessary Google Play Services and have configured your app in the Google API Console. ```java com.google.api.services.tasks.Tasks service; @Override public void onCreate(Bundle savedInstanceState) { credential = GoogleAccountCredential.usingOAuth2(this, Collections.singleton(TasksScopes.TASKS)); SharedPreferences settings = getPreferences(Context.MODE_PRIVATE); credential.setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null)); service = new com.google.api.services.tasks.Tasks.Builder(httpTransport, jsonFactory, credential) .setApplicationName("Google-TasksAndroidSample/1.0").build(); } private void chooseAccount() { startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQUEST_GOOGLE_PLAY_SERVICES: if (resultCode == Activity.RESULT_OK) { haveGooglePlayServices(); } else { checkGooglePlayServicesAvailable(); } break; case REQUEST_AUTHORIZATION: if (resultCode == Activity.RESULT_OK) { AsyncLoadTasks.run(this); } else { chooseAccount(); } break; case REQUEST_ACCOUNT_PICKER: if (resultCode == Activity.RESULT_OK && data != null && data.getExtras() != null) { String accountName = data.getExtras().getString(AccountManager.KEY_ACCOUNT_NAME); if (accountName != null) { credential.setSelectedAccountName(accountName); SharedPreferences settings = getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putString(PREF_ACCOUNT_NAME, accountName); editor.commit(); AsyncLoadTasks.run(this); } } break; } } ``` -------------------------------- ### Build Project with GCP Credentials (Code Samples) Source: https://github.com/googleapis/google-api-java-client/blob/main/CONTRIBUTING.md For code samples requiring GCP service access, set the service account credentials and run this build command. ```bash export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service/account.json mvn clean verify ``` -------------------------------- ### Build and Test Project Source: https://github.com/googleapis/google-api-java-client/blob/main/CONTRIBUTING.md Run this command to build, package, and execute all unit tests for the project. ```bash mvn clean verify ``` -------------------------------- ### Authenticated API Call on App Engine Source: https://github.com/googleapis/google-api-java-client/blob/main/docs/google-app-engine.md Use AppIdentityCredential for authenticated calls to Google APIs within App Engine. This example shows fetching URL history using the Urlshortener API. ```java @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { AppIdentityCredential credential = new AppIdentityCredential(Arrays.asList(UrlshortenerScopes.URLSHORTENER)); Urlshortener shortener = new Urlshortener.Builder(new UrlFetchTransport(), new JacksonFactory(), credential) .build(); UrlHistory history = shortener.URL().list().execute(); ... ``` -------------------------------- ### Build and Run Integration Tests Source: https://github.com/googleapis/google-api-java-client/blob/main/CONTRIBUTING.md To include integration tests, set the GOOGLE_APPLICATION_CREDENTIALS environment variable and use this command to build, package, run unit tests, and execute integration tests. ```bash export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service/account.json mvn -Penable-integration-tests clean verify ``` -------------------------------- ### Enable Direct Media Upload (Java) Source: https://github.com/googleapis/google-api-java-client/wiki/Media-Upload Configure MediaHttpUploader to perform direct media uploads instead of resumable uploads. This is suitable for smaller files and simplifies the upload process by using a single HTTP request. ```java mediaHttpUploader.setDirectUploadEnabled(true); ``` -------------------------------- ### Initialize API Key and Request Headers with CommonGoogleClientRequestInitializer Source: https://context7.com/googleapis/google-api-java-client/llms.txt Use CommonGoogleClientRequestInitializer to set an API key, user project, audit reason, and user agent for all API requests. Attach this initializer to a service client builder using setGoogleClientRequestInitializer(). ```java import com.google.api.client.googleapis.apache.v5.GoogleApache5HttpTransport; import com.google.api.client.googleapis.services.CommonGoogleClientRequestInitializer; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.books.Books; public class InitializerExample { public static void main(String[] args) throws Exception { // Build an initializer with API key, user project, and audit reason CommonGoogleClientRequestInitializer initializer = CommonGoogleClientRequestInitializer.newBuilder() .setKey("AIzaSy_YOUR_API_KEY") .setUserProject("my-billing-project") .setRequestReason("support-ticket-12345") .setUserAgent("MyCompanyApp/2.0") .build(); // Attach to the Books service client Books books = new Books.Builder( GoogleApache5HttpTransport.newTrustedTransport(), GsonFactory.getDefaultInstance(), request -> {}) // no credential needed for public APIs with key .setApplicationName("BooksExample/1.0") .setGoogleClientRequestInitializer(initializer) .build(); // Execute a search Books.Volumes.List volumesList = books.volumes().list("java programming"); volumesList.setMaxResults(5L); com.google.api.services.books.model.Volumes volumes = volumesList.execute(); volumes.getItems().forEach(v -> System.out.println(v.getVolumeInfo().getTitle())); } } ``` -------------------------------- ### Enable Direct Media Download Source: https://github.com/googleapis/google-api-java-client/wiki/Media-Download Configure `MediaHttpDownloader` to use direct media download by setting `directDownloadEnabled` to `true`. This is suitable for smaller files and reduces the number of HTTP requests. ```java mediaHttpDownloader.setDirectDownloadEnabled(true); ``` -------------------------------- ### Build Storage Client with Application Default Credentials (ADC) Source: https://context7.com/googleapis/google-api-java-client/llms.txt Use this method when running in a Google Cloud environment where ADC are configured. It automatically picks up credentials. ```java import com.google.api.client.googleapis.apache.v5.GoogleApache5HttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.storage.Storage; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; import java.io.FileInputStream; import java.util.Collections; public class CredentialsExample { // --- Option 1: Application Default Credentials (ADC) --- static Storage buildWithADC() throws Exception { GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() .createScoped("https://www.googleapis.com/auth/devstorage.read_only"); return new Storage.Builder( GoogleApache5HttpTransport.newTrustedTransport(), GsonFactory.getDefaultInstance(), new HttpCredentialsAdapter(credentials)) .setApplicationName("MyProject/1.0") .build(); } // --- Option 2: Service Account JSON key file --- static Storage buildWithServiceAccount() throws Exception { GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream("/path/to/service-account.json")) .createScoped( Collections.singleton("https://www.googleapis.com/auth/devstorage.full_control")); return new Storage.Builder( GoogleApache5HttpTransport.newTrustedTransport(), GsonFactory.getDefaultInstance(), new HttpCredentialsAdapter(credentials)) .setApplicationName("MyProject/1.0") .build(); } // --- Option 3: Explicit access token --- static Storage buildWithAccessToken(String token) throws Exception { GoogleCredentials credentials = GoogleCredentials.newBuilder() .setAccessToken(new com.google.auth.oauth2.AccessToken(token, null)) .build(); return new Storage.Builder( GoogleApache5HttpTransport.newTrustedTransport(), GsonFactory.getDefaultInstance(), new HttpCredentialsAdapter(credentials)) .setApplicationName("MyProject/1.0") .build(); } } ``` -------------------------------- ### Format Code with Maven Plugin Source: https://github.com/googleapis/google-api-java-client/blob/main/CONTRIBUTING.md Execute this Maven command to format your project's code using the google-java-format plugin. ```bash mvn com.coveo:fmt-maven-plugin:format ``` -------------------------------- ### Initialize GoogleCredential with Access Token Source: https://github.com/googleapis/google-api-java-client/wiki/OAuth2 Use this when you already have an access token to initialize GoogleCredential for accessing protected resources. ```java GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken); Plus plus = new Plus.builder(new NetHttpTransport(), JacksonFactory.getDefaultInstance(), credential) .setApplicationName("Google-PlusSample/1.0") .build(); ``` -------------------------------- ### Maven Dependency Management with BOM Source: https://context7.com/googleapis/google-api-java-client/llms.txt Use the `libraries-bom` to ensure compatible dependency versions for all `com.google.api-client` artifacts. ```xml com.google.cloud libraries-bom 26.34.0 pom import com.google.api-client google-api-client com.google.api-client google-api-client-apache-v5 com.google.api-client google-api-client-gson ``` -------------------------------- ### Service Account Credential Initialization Source: https://github.com/googleapis/google-api-java-client/blob/main/docs/oauth-2.0.md Initialize Google credentials using a service account private key file. This is used for applications accessing their own data, not end-user data. ```java HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = GsonFactory.getDefaultInstance(); //Build service account credential GoogleCredentials googleCredentials = GoogleCredentials. fromStream(new FileInputStream("/path/to/file")); HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(googleCredentials); Storage storage = new Storage.Builder(httpTransport, jsonFactory, requestInitializer) .setApplicationName("MyProject-1234") .build(); ``` -------------------------------- ### Initialize Google AccountCredential and Tasks Client on Android Source: https://github.com/googleapis/google-api-java-client/wiki/Android Initializes GoogleAccountCredential using OAuth2 and sets up the Tasks client. Ensure the correct scopes are included and the account name is loaded from SharedPreferences. ```java @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Google Accounts credential = GoogleAccountCredential.usingOAuth2(this, Collections.singleton(TasksScopes.TASKS)); SharedPreferences settings = getPreferences(Context.MODE_PRIVATE); credential.setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null)); // Tasks client service = new com.google.api.services.tasks.Tasks.Builder(httpTransport, jsonFactory, credential) .setApplicationName("Google-TasksAndroidSample/1.0").build(); } ``` -------------------------------- ### Download Media Using Service-Specific Generated Libraries Source: https://github.com/googleapis/google-api-java-client/wiki/Media-Download Use the convenient download method provided by service-specific generated libraries to download media directly into an `OutputStream`. Ensure a `CustomProgressListener` is set to monitor the download. ```java OutputStream out = new FileOutputStream("/tmp/driveFile.jpg"); DriveFiles.Get request = drive.files().get(fileId); request.getMediaHttpDownloader().setProgressListener(new CustomProgressListener()); request.executeMediaAndDownloadTo(out); ```