From 86d64446787b80185a0e900f6766e69acb974327 Mon Sep 17 00:00:00 2001 From: Pierrick Voulet <6769971+PierrickVoulet@users.noreply.github.com> Date: Thu, 1 Aug 2024 14:42:33 -0400 Subject: [PATCH] feat: Add Google Chat API quickstart (#1061) * feat: Add Google Chat API quickstart * Fix Google Style --------- Co-authored-by: pierrick --- chat/quickstart/README.md | 12 ++ chat/quickstart/build.gradle | 20 +++ chat/quickstart/settings.gradle | 18 +++ .../src/main/java/ChatQuickstart.java | 130 ++++++++++++++++++ 4 files changed, 180 insertions(+) create mode 100644 chat/quickstart/README.md create mode 100644 chat/quickstart/build.gradle create mode 100644 chat/quickstart/settings.gradle create mode 100644 chat/quickstart/src/main/java/ChatQuickstart.java diff --git a/chat/quickstart/README.md b/chat/quickstart/README.md new file mode 100644 index 00000000..ccae2e71 --- /dev/null +++ b/chat/quickstart/README.md @@ -0,0 +1,12 @@ +# Google Chat Java Quickstart + +Complete the steps described in the [quickstart instructions]( +https://developers.google.com/workspace/chat/api/guides/quickstart/java), +and in about five minutes you'll have a simple Java command-line +application that makes requests to the Google Chat API. + +## Run + +After following the quickstart setup instructions, run the sample: + +`gradle run` diff --git a/chat/quickstart/build.gradle b/chat/quickstart/build.gradle new file mode 100644 index 00000000..a1a7d7ef --- /dev/null +++ b/chat/quickstart/build.gradle @@ -0,0 +1,20 @@ +apply plugin: 'java' +apply plugin: 'application' + +mainClassName = 'ChatQuickstart' +sourceCompatibility = 11 +targetCompatibility = 11 +version = '1.0' + +repositories { + mavenCentral() +} + +dependencies { + implementation 'com.google.auth:google-auth-library-oauth2-http:1.23.0' + implementation 'com.google.api-client:google-api-client:1.33.0' + implementation 'com.google.api.grpc:proto-google-cloud-chat-v1:0.8.0' + implementation 'com.google.api:gax:2.48.1' + implementation 'com.google.cloud:google-cloud-chat:0.1.0' + implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' +} diff --git a/chat/quickstart/settings.gradle b/chat/quickstart/settings.gradle new file mode 100644 index 00000000..7bcc727d --- /dev/null +++ b/chat/quickstart/settings.gradle @@ -0,0 +1,18 @@ +/* + * This settings file was generated by the Gradle 'init' task. + * + * The settings file is used to specify which projects to include in your build. + * In a single project build this file can be empty or even removed. + * + * Detailed information about configuring a multi-project build in Gradle can be found + * in the user guide at https://docs.gradle.org/3.5/userguide/multi_project_builds.html + */ + +/* +// To declare projects as part of a multi-project build use the 'include' method +include 'shared' +include 'api' +include 'services:webservice' +*/ + +rootProject.name = 'quickstart' diff --git a/chat/quickstart/src/main/java/ChatQuickstart.java b/chat/quickstart/src/main/java/ChatQuickstart.java new file mode 100644 index 00000000..4956be1d --- /dev/null +++ b/chat/quickstart/src/main/java/ChatQuickstart.java @@ -0,0 +1,130 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// [START chat_quickstart] + +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.json.JsonFactory; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.client.util.store.FileDataStoreFactory; +import com.google.api.gax.core.FixedCredentialsProvider; +import com.google.auth.Credentials; +import com.google.auth.oauth2.AccessToken; +import com.google.auth.oauth2.UserCredentials; +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.ChatServiceSettings; +import com.google.chat.v1.ListSpacesRequest; +import com.google.chat.v1.Space; +import com.google.protobuf.util.JsonFormat; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Collections; +import java.util.Date; +import java.util.List; + +/* class to demonstrate use of Google Chat API spaces list API */ +public class ChatQuickstart { + /** Directory to store authorization tokens for this application. */ + private static final String TOKENS_DIRECTORY_PATH = "tokens"; + + /** + * Global instance of the scopes required by this quickstart. If modifying these scopes, delete + * your previously saved tokens/ folder. + */ + private static final List SCOPES = + Collections.singletonList("https://www.googleapis.com/auth/chat.spaces.readonly"); + + /** Global instance of the JSON factory. */ + private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); + + private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; + + /** + * Run the OAuth2 flow for local/installed app. + * + * @return An authorized Credential object. + * @throws IOException If the credentials.json file cannot be found. + */ + private static Credentials getCredentials() throws Exception { + // Load client secrets. + InputStream credentialsFileInputStream = + ChatQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH); + if (credentialsFileInputStream == null) { + throw new FileNotFoundException("Credentials file resource not found."); + } + GoogleClientSecrets clientSecrets = + GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(credentialsFileInputStream)); + + // Set up authorization code flow. + GoogleAuthorizationCodeFlow flow = + new GoogleAuthorizationCodeFlow.Builder( + GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, clientSecrets, SCOPES) + // Set these two options to generate refresh token alongside access token. + .setDataStoreFactory(new FileDataStoreFactory(new File(TOKENS_DIRECTORY_PATH))) + .setAccessType("offline") + .build(); + + // Authorize. + Credential credential = + new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); + + // Build and return an authorized Credential object + AccessToken accessToken = + new AccessToken( + credential.getAccessToken(), + new Date( + // put the actual expiry date of access token here + System.currentTimeMillis())); + return UserCredentials.newBuilder() + .setAccessToken(accessToken) + .setRefreshToken(credential.getRefreshToken()) + .setClientId(clientSecrets.getInstalled().getClientId()) + .setClientSecret(clientSecrets.getInstalled().getClientSecret()) + .build(); + } + + public static void main(String... args) throws Exception { + // Override default service settings to supply user credentials. + Credentials credentials = getCredentials(); + + // Create the ChatServiceSettings with the credentials + ChatServiceSettings chatServiceSettings = + ChatServiceSettings.newBuilder() + .setCredentialsProvider(FixedCredentialsProvider.create(credentials)) + .build(); + + try (ChatServiceClient chatServiceClient = ChatServiceClient.create(chatServiceSettings)) { + ListSpacesRequest request = + ListSpacesRequest.newBuilder() + // Filter spaces by space type (SPACE or GROUP_CHAT or + // DIRECT_MESSAGE). + .setFilter("spaceType = \"SPACE\"") + .build(); + + // Iterate over results and resolve additional pages automatically. + for (Space response : chatServiceClient.listSpaces(request).iterateAll()) { + System.out.println(JsonFormat.printer().print(response)); + } + } + } +} +// [END chat_quickstart]