Skip to content

Commit 86d6444

Browse files
PierrickVouletpierrick
andauthored
feat: Add Google Chat API quickstart (#1061)
* feat: Add Google Chat API quickstart * Fix Google Style --------- Co-authored-by: pierrick <pierrick@google.com>
1 parent d492e92 commit 86d6444

File tree

4 files changed

+180
-0
lines changed

4 files changed

+180
-0
lines changed

chat/quickstart/README.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# Google Chat Java Quickstart
2+
3+
Complete the steps described in the [quickstart instructions](
4+
https://developers.google.com/workspace/chat/api/guides/quickstart/java),
5+
and in about five minutes you'll have a simple Java command-line
6+
application that makes requests to the Google Chat API.
7+
8+
## Run
9+
10+
After following the quickstart setup instructions, run the sample:
11+
12+
`gradle run`

chat/quickstart/build.gradle

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
apply plugin: 'java'
2+
apply plugin: 'application'
3+
4+
mainClassName = 'ChatQuickstart'
5+
sourceCompatibility = 11
6+
targetCompatibility = 11
7+
version = '1.0'
8+
9+
repositories {
10+
mavenCentral()
11+
}
12+
13+
dependencies {
14+
implementation 'com.google.auth:google-auth-library-oauth2-http:1.23.0'
15+
implementation 'com.google.api-client:google-api-client:1.33.0'
16+
implementation 'com.google.api.grpc:proto-google-cloud-chat-v1:0.8.0'
17+
implementation 'com.google.api:gax:2.48.1'
18+
implementation 'com.google.cloud:google-cloud-chat:0.1.0'
19+
implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1'
20+
}

chat/quickstart/settings.gradle

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/*
2+
* This settings file was generated by the Gradle 'init' task.
3+
*
4+
* The settings file is used to specify which projects to include in your build.
5+
* In a single project build this file can be empty or even removed.
6+
*
7+
* Detailed information about configuring a multi-project build in Gradle can be found
8+
* in the user guide at https://docs.gradle.org/3.5/userguide/multi_project_builds.html
9+
*/
10+
11+
/*
12+
// To declare projects as part of a multi-project build use the 'include' method
13+
include 'shared'
14+
include 'api'
15+
include 'services:webservice'
16+
*/
17+
18+
rootProject.name = 'quickstart'
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
// Copyright 2024 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
// [START chat_quickstart]
16+
17+
import com.google.api.client.auth.oauth2.Credential;
18+
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
19+
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
20+
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
21+
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
22+
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
23+
import com.google.api.client.json.JsonFactory;
24+
import com.google.api.client.json.gson.GsonFactory;
25+
import com.google.api.client.util.store.FileDataStoreFactory;
26+
import com.google.api.gax.core.FixedCredentialsProvider;
27+
import com.google.auth.Credentials;
28+
import com.google.auth.oauth2.AccessToken;
29+
import com.google.auth.oauth2.UserCredentials;
30+
import com.google.chat.v1.ChatServiceClient;
31+
import com.google.chat.v1.ChatServiceSettings;
32+
import com.google.chat.v1.ListSpacesRequest;
33+
import com.google.chat.v1.Space;
34+
import com.google.protobuf.util.JsonFormat;
35+
import java.io.File;
36+
import java.io.FileNotFoundException;
37+
import java.io.IOException;
38+
import java.io.InputStream;
39+
import java.io.InputStreamReader;
40+
import java.util.Collections;
41+
import java.util.Date;
42+
import java.util.List;
43+
44+
/* class to demonstrate use of Google Chat API spaces list API */
45+
public class ChatQuickstart {
46+
/** Directory to store authorization tokens for this application. */
47+
private static final String TOKENS_DIRECTORY_PATH = "tokens";
48+
49+
/**
50+
* Global instance of the scopes required by this quickstart. If modifying these scopes, delete
51+
* your previously saved tokens/ folder.
52+
*/
53+
private static final List<String> SCOPES =
54+
Collections.singletonList("https://www.googleapis.com/auth/chat.spaces.readonly");
55+
56+
/** Global instance of the JSON factory. */
57+
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
58+
59+
private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
60+
61+
/**
62+
* Run the OAuth2 flow for local/installed app.
63+
*
64+
* @return An authorized Credential object.
65+
* @throws IOException If the credentials.json file cannot be found.
66+
*/
67+
private static Credentials getCredentials() throws Exception {
68+
// Load client secrets.
69+
InputStream credentialsFileInputStream =
70+
ChatQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
71+
if (credentialsFileInputStream == null) {
72+
throw new FileNotFoundException("Credentials file resource not found.");
73+
}
74+
GoogleClientSecrets clientSecrets =
75+
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(credentialsFileInputStream));
76+
77+
// Set up authorization code flow.
78+
GoogleAuthorizationCodeFlow flow =
79+
new GoogleAuthorizationCodeFlow.Builder(
80+
GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, clientSecrets, SCOPES)
81+
// Set these two options to generate refresh token alongside access token.
82+
.setDataStoreFactory(new FileDataStoreFactory(new File(TOKENS_DIRECTORY_PATH)))
83+
.setAccessType("offline")
84+
.build();
85+
86+
// Authorize.
87+
Credential credential =
88+
new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
89+
90+
// Build and return an authorized Credential object
91+
AccessToken accessToken =
92+
new AccessToken(
93+
credential.getAccessToken(),
94+
new Date(
95+
// put the actual expiry date of access token here
96+
System.currentTimeMillis()));
97+
return UserCredentials.newBuilder()
98+
.setAccessToken(accessToken)
99+
.setRefreshToken(credential.getRefreshToken())
100+
.setClientId(clientSecrets.getInstalled().getClientId())
101+
.setClientSecret(clientSecrets.getInstalled().getClientSecret())
102+
.build();
103+
}
104+
105+
public static void main(String... args) throws Exception {
106+
// Override default service settings to supply user credentials.
107+
Credentials credentials = getCredentials();
108+
109+
// Create the ChatServiceSettings with the credentials
110+
ChatServiceSettings chatServiceSettings =
111+
ChatServiceSettings.newBuilder()
112+
.setCredentialsProvider(FixedCredentialsProvider.create(credentials))
113+
.build();
114+
115+
try (ChatServiceClient chatServiceClient = ChatServiceClient.create(chatServiceSettings)) {
116+
ListSpacesRequest request =
117+
ListSpacesRequest.newBuilder()
118+
// Filter spaces by space type (SPACE or GROUP_CHAT or
119+
// DIRECT_MESSAGE).
120+
.setFilter("spaceType = \"SPACE\"")
121+
.build();
122+
123+
// Iterate over results and resolve additional pages automatically.
124+
for (Space response : chatServiceClient.listSpaces(request).iterateAll()) {
125+
System.out.println(JsonFormat.printer().print(response));
126+
}
127+
}
128+
}
129+
}
130+
// [END chat_quickstart]

0 commit comments

Comments
 (0)