Skip to content

Commit b59745f

Browse files
PierrickVouletpierrick
and
pierrick
authored
feat: add Cloud Client library samples for Chat (#1078)
* feat: add Cloud Client library samples for Chat * README improvements --------- Co-authored-by: pierrick <[email protected]>
1 parent 86d6444 commit b59745f

30 files changed

+1571
-0
lines changed

chat/client-libraries/cloud/README.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Google Chat API - Cloud Client library samples
2+
3+
## Set up
4+
5+
Add `service_account.json` and/or `client_secrets.json` to the current
6+
folder depending on the credentials used by the samples to run:
7+
8+
1. `service_account.json` for
9+
[app credentials](https://developers.google.com/workspace/chat/authenticate-authorize-chat-app)
10+
11+
1. `client_secrets.json` for
12+
[user credentials](https://developers.google.com/workspace/chat/authenticate-authorize-chat-user)
13+
14+
## Run with Maven
15+
16+
Execute
17+
`mvn exec:java -Dexec.mainClass="replace.with.the.sample.mainClass"`
18+
wih the main class of the sample.
19+
20+
For example, to run the sample `CreateMessageAppCred`, run
21+
`mvn exec:java -Dexec.mainClass="com.google.workspace.api.chat.samples.CreateMessageAppCred"`.
22+
23+
## Run with Gradle
24+
25+
Execute `gradle run` after setting the main class of the sample in the `build.gradle` file.
26+
27+
For example, to run the sample `CreateMessageAppCred`, use
28+
`com.google.workspace.api.chat.samples.CreateMessageAppCred`.
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 = 'com.google.workspace.api.chat.samples.CreateMessageAppCred'
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.apis:google-api-services-chat:v1-rev20240509-2.0.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/client-libraries/cloud/pom.xml

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
2+
<modelVersion>4.0.0</modelVersion>
3+
4+
<groupId>com.google.workspace.api.chat.samples</groupId>
5+
<artifactId>chat-api-samples</artifactId>
6+
<version>0.0.1</version>
7+
<name>Google API Client Library Chat Samples For Java</name>
8+
9+
10+
<properties>
11+
<maven.compiler.release>21</maven.compiler.release>
12+
<maven.compiler.source>1.8</maven.compiler.source>
13+
<maven.compiler.target>1.8</maven.compiler.target>
14+
</properties>
15+
16+
17+
<dependencies>
18+
<!-- Google OAuth2 Client Library -->
19+
<dependency>
20+
<groupId>com.google.auth</groupId>
21+
<artifactId>google-auth-library-oauth2-http</artifactId>
22+
<version>1.23.0</version>
23+
</dependency>
24+
<dependency>
25+
<groupId>com.google.oauth-client</groupId>
26+
<artifactId>google-oauth-client-jetty</artifactId>
27+
<version>1.34.1</version>
28+
</dependency>
29+
30+
31+
<!-- Google API Client Library -->
32+
<dependency>
33+
<groupId>com.google.apis</groupId>
34+
<artifactId>google-api-services-chat</artifactId>
35+
<version>v1-rev20240509-2.0.0</version>
36+
</dependency>
37+
38+
<!-- GAPIC library -->
39+
<!-- Used for instantiating Google Chat API protos -->
40+
<dependency>
41+
<groupId>com.google.api.grpc</groupId>
42+
<artifactId>proto-google-cloud-chat-v1</artifactId>
43+
<version>0.8.0</version>
44+
</dependency>
45+
<dependency>
46+
<groupId>com.google.api</groupId>
47+
<artifactId>gax</artifactId>
48+
<version>2.48.1</version>
49+
</dependency>
50+
<!-- Used for creating Chat Service Client for making Google Chat API calls -->
51+
<dependency>
52+
<groupId>com.google.cloud</groupId>
53+
<artifactId>google-cloud-chat</artifactId>
54+
<version>0.1.0</version>
55+
</dependency>
56+
57+
</dependencies>
58+
59+
</project>
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
/*
2+
* Copyright 2024 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.google.workspace.api.chat.samples;
18+
19+
import com.google.auth.oauth2.AccessToken;
20+
import com.google.auth.oauth2.GoogleCredentials;
21+
import com.google.auth.oauth2.ServiceAccountCredentials;
22+
import com.google.auth.oauth2.UserCredentials;
23+
import com.google.api.client.auth.oauth2.Credential;
24+
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
25+
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
26+
import com.google.api.client.json.gson.GsonFactory;
27+
import com.google.api.client.json.JsonFactory;
28+
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
29+
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
30+
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
31+
import com.google.api.gax.core.GoogleCredentialsProvider;
32+
import com.google.api.gax.core.FixedCredentialsProvider;
33+
import com.google.chat.v1.ChatServiceClient;
34+
import com.google.chat.v1.ChatServiceSettings;
35+
import com.google.common.collect.ImmutableList;
36+
37+
import java.io.FileInputStream;
38+
import java.io.FileReader;
39+
import java.util.Collections;
40+
import java.util.Date;
41+
42+
public class AuthenticationUtils{
43+
44+
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
45+
private static final String SERVICE_ACCOUNT_FILE = "service_account.json";
46+
private static final String CLIENT_SECRET_FILE = "client_secrets.json";
47+
private static final String APP_AUTH_OAUTH_SCOPE =
48+
"https://www.googleapis.com/auth/chat.bot";
49+
50+
public static ChatServiceClient createClientWithAppCredentials()
51+
throws Exception {
52+
// For more information on service account authentication, see
53+
// https://developers.google.com/workspace/chat/authenticate-authorize-chat-app
54+
GoogleCredentials credential = ServiceAccountCredentials.fromStream(
55+
new FileInputStream(SERVICE_ACCOUNT_FILE))
56+
.createScoped(ImmutableList.of(APP_AUTH_OAUTH_SCOPE));
57+
58+
// Create the ChatServiceSettings with the app credentials
59+
ChatServiceSettings chatServiceSettings =
60+
ChatServiceSettings.newBuilder()
61+
.setCredentialsProvider(
62+
FixedCredentialsProvider.create(credential))
63+
.build();
64+
65+
return ChatServiceClient.create(chatServiceSettings);
66+
}
67+
68+
public static ChatServiceClient createClientWithUserCredentials(
69+
ImmutableList<String> scopes) throws Exception {
70+
// For more information on user authentication, see
71+
// https://developers.google.com/workspace/chat/authenticate-authorize-chat-user
72+
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
73+
JSON_FACTORY, new FileReader(CLIENT_SECRET_FILE));
74+
75+
Credential credential = authorize(scopes, clientSecrets);
76+
77+
AccessToken accessToken = new AccessToken(
78+
credential.getAccessToken(),
79+
new Date(
80+
// put the actual expiry date of access token here
81+
System.currentTimeMillis()));
82+
UserCredentials googleCredentials =
83+
UserCredentials
84+
.newBuilder()
85+
.setAccessToken(accessToken)
86+
.setRefreshToken(credential.getRefreshToken())
87+
.setClientId(clientSecrets.getInstalled().getClientId())
88+
.setClientSecret(clientSecrets.getInstalled().getClientSecret())
89+
.build();
90+
91+
// Create the ChatServiceSettings with the credentials
92+
ChatServiceSettings chatServiceSettings =
93+
ChatServiceSettings
94+
.newBuilder()
95+
.setCredentialsProvider(
96+
FixedCredentialsProvider.create(googleCredentials))
97+
.build();
98+
99+
return ChatServiceClient.create(chatServiceSettings);
100+
}
101+
102+
// Generate access token and refresh token using scopes and client secrets.
103+
private static Credential authorize(
104+
ImmutableList<String> scopes, GoogleClientSecrets clientSecrets)
105+
throws Exception {
106+
// Set up authorization code flow.
107+
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
108+
GoogleNetHttpTransport.newTrustedTransport(),
109+
JSON_FACTORY,
110+
clientSecrets,
111+
scopes)
112+
// Set these two options to generate refresh token alongside access token.
113+
.setAccessType("offline")
114+
.setApprovalPrompt("force")
115+
.build();
116+
117+
// Authorize.
118+
return new AuthorizationCodeInstalledApp(
119+
flow, new LocalServerReceiver()).authorize("user");
120+
}
121+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
* Copyright 2024 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.google.workspace.api.chat.samples;
18+
19+
import com.google.common.collect.ImmutableList;
20+
import com.google.protobuf.util.JsonFormat;
21+
// [START chat_CreateMembershipUserCred]
22+
import com.google.chat.v1.ChatServiceClient;
23+
import com.google.chat.v1.CreateMembershipRequest;
24+
import com.google.chat.v1.Membership;
25+
import com.google.chat.v1.SpaceName;
26+
import com.google.chat.v1.User;
27+
28+
// This sample shows how to create membership with user credential for a human
29+
// user.
30+
public class CreateMembershipUserCred {
31+
32+
private static final String SCOPE =
33+
"https://www.googleapis.com/auth/chat.memberships";
34+
35+
public static void main(String[] args) throws Exception {
36+
try (ChatServiceClient chatServiceClient =
37+
AuthenticationUtils.createClientWithUserCredentials(
38+
ImmutableList.of(SCOPE))) {
39+
CreateMembershipRequest request =
40+
CreateMembershipRequest.newBuilder()
41+
// replace SPACE_NAME here
42+
.setParent("spaces/SPACE_NAME")
43+
.setMembership(
44+
Membership.newBuilder()
45+
.setMember(
46+
User.newBuilder()
47+
// replace USER_NAME here
48+
.setName("users/USER_NAME")
49+
// user type for the membership
50+
.setType(User.Type.HUMAN)
51+
.build())
52+
.build())
53+
.build();
54+
Membership response = chatServiceClient.createMembership(request);
55+
56+
System.out.println(JsonFormat.printer().print(response));
57+
}
58+
}
59+
}
60+
// [END chat_CreateMembershipUserCred]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
* Copyright 2024 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.google.workspace.api.chat.samples;
18+
19+
import com.google.common.collect.ImmutableList;
20+
import com.google.protobuf.util.JsonFormat;
21+
// [START chat_CreateMembershipUserCredForApp]
22+
import com.google.chat.v1.ChatServiceClient;
23+
import com.google.chat.v1.CreateMembershipRequest;
24+
import com.google.chat.v1.Membership;
25+
import com.google.chat.v1.SpaceName;
26+
import com.google.chat.v1.User;
27+
28+
// This sample shows how to create membership with user credential for the
29+
// calling app.
30+
public class CreateMembershipUserCredForApp {
31+
32+
private static final String SCOPE =
33+
"https://www.googleapis.com/auth/chat.memberships.app";
34+
35+
public static void main(String[] args) throws Exception {
36+
try (ChatServiceClient chatServiceClient =
37+
AuthenticationUtils.createClientWithUserCredentials(
38+
ImmutableList.of(SCOPE))) {
39+
CreateMembershipRequest request =
40+
CreateMembershipRequest.newBuilder()
41+
// replace SPACE_NAME here
42+
.setParent("spaces/SPACE_NAME")
43+
.setMembership(
44+
Membership.newBuilder()
45+
.setMember(
46+
User.newBuilder()
47+
// member name for app membership, do not change this.
48+
.setName("users/app")
49+
// user type for the membership
50+
.setType(User.Type.BOT)
51+
.build())
52+
.build())
53+
.build();
54+
Membership response = chatServiceClient.createMembership(request);
55+
56+
System.out.println(JsonFormat.printer().print(response));
57+
}
58+
}
59+
}
60+
// [END chat_CreateMembershipUserCredForApp]

0 commit comments

Comments
 (0)