From 2fa7089ab98faf6e959d472aa95495bf5201ea24 Mon Sep 17 00:00:00 2001 From: Mahima Desetty <45216855+mahima-desetty@users.noreply.github.com> Date: Mon, 12 Dec 2022 11:41:45 -0500 Subject: [PATCH 01/19] =?UTF-8?q?feat:=20added=20Java=20code=20snippets=20?= =?UTF-8?q?for=20Aliases,=20CourseWork,=20and=20Topics=C2=A0=20(#464)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * add alias snippet and unit test * java snippets for topics, create coursework, create alias * updates based on team review * renamed alias methods, added devsite comments * added missing license header to TestDeleteTopic.java --- .../src/main/java/AddAliasToCourse.java | 85 ++++++++++++++ .../src/main/java/CreateCourseWithAlias.java | 89 +++++++++++++++ .../src/main/java/CreateCourseWork.java | 107 ++++++++++++++++++ .../snippets/src/main/java/CreateTopic.java | 81 +++++++++++++ .../snippets/src/main/java/DeleteTopic.java | 76 +++++++++++++ .../snippets/src/main/java/GetTopic.java | 80 +++++++++++++ .../snippets/src/main/java/ListTopics.java | 98 ++++++++++++++++ .../snippets/src/main/java/UpdateTopic.java | 89 +++++++++++++++ .../snippets/src/test/java/BaseTest.java | 4 + .../src/test/java/TestAddAliasToCourse.java | 34 ++++++ .../test/java/TestCreateCourseWithAlias.java | 36 ++++++ .../src/test/java/TestCreateCourseWork.java | 28 +++++ .../src/test/java/TestCreateTopic.java | 28 +++++ .../src/test/java/TestDeleteTopic.java | 29 +++++ .../snippets/src/test/java/TestGetTopic.java | 31 +++++ .../src/test/java/TestListTopics.java | 31 +++++ .../src/test/java/TestUpdateTopic.java | 28 +++++ 17 files changed, 954 insertions(+) create mode 100644 classroom/snippets/src/main/java/AddAliasToCourse.java create mode 100644 classroom/snippets/src/main/java/CreateCourseWithAlias.java create mode 100644 classroom/snippets/src/main/java/CreateCourseWork.java create mode 100644 classroom/snippets/src/main/java/CreateTopic.java create mode 100644 classroom/snippets/src/main/java/DeleteTopic.java create mode 100644 classroom/snippets/src/main/java/GetTopic.java create mode 100644 classroom/snippets/src/main/java/ListTopics.java create mode 100644 classroom/snippets/src/main/java/UpdateTopic.java create mode 100644 classroom/snippets/src/test/java/TestAddAliasToCourse.java create mode 100644 classroom/snippets/src/test/java/TestCreateCourseWithAlias.java create mode 100644 classroom/snippets/src/test/java/TestCreateCourseWork.java create mode 100644 classroom/snippets/src/test/java/TestCreateTopic.java create mode 100644 classroom/snippets/src/test/java/TestDeleteTopic.java create mode 100644 classroom/snippets/src/test/java/TestGetTopic.java create mode 100644 classroom/snippets/src/test/java/TestListTopics.java create mode 100644 classroom/snippets/src/test/java/TestUpdateTopic.java diff --git a/classroom/snippets/src/main/java/AddAliasToCourse.java b/classroom/snippets/src/main/java/AddAliasToCourse.java new file mode 100644 index 00000000..10434391 --- /dev/null +++ b/classroom/snippets/src/main/java/AddAliasToCourse.java @@ -0,0 +1,85 @@ +// Copyright 2022 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 +// +// https://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 classroom_add_alias_to_course_class] + +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.HttpRequestInitializer; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.classroom.Classroom; +import com.google.api.services.classroom.ClassroomScopes; +import com.google.api.services.classroom.model.CourseAlias; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import java.io.IOException; +import java.util.Collections; + +/* Class to demonstrate the use of Classroom Create Alias API. */ +public class AddAliasToCourse { + /** + * Add an alias on an existing course. + * + * @param courseId - id of the course to add an alias to. + * @return - newly created course alias. + * @throws IOException - if credentials file not found. + */ + public static CourseAlias addAliasToCourse(String courseId) throws IOException { + /* Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity for + guides on implementing OAuth2 for your application. */ + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSES)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); + + // Create the classroom API client. + Classroom service = new Classroom.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Classroom samples") + .build(); + + // [START classroom_add_alias_to_course_code_snippet] + + /* Create a new CourseAlias object with a project-wide alias. Project-wide aliases use a prefix + of "p:" and can only be seen and used by the application that created them. */ + CourseAlias content = new CourseAlias() + .setAlias("p:biology_10"); + CourseAlias courseAlias = null; + + try { + courseAlias = service.courses().aliases().create(courseId, content) + .execute(); + System.out.printf("Course alias created: %s \n", courseAlias.getAlias()); + } catch (GoogleJsonResponseException e) { + //TODO (developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 409) { + System.out.printf("The course alias already exists: %s.\n", content); + } else { + throw e; + } + } catch (Exception e) { + throw e; + } + return courseAlias; + + // [END classroom_add_alias_to_course_code_snippet] + + } +} +// [END classroom_add_alias_to_course_class] diff --git a/classroom/snippets/src/main/java/CreateCourseWithAlias.java b/classroom/snippets/src/main/java/CreateCourseWithAlias.java new file mode 100644 index 00000000..77a6521b --- /dev/null +++ b/classroom/snippets/src/main/java/CreateCourseWithAlias.java @@ -0,0 +1,89 @@ +// Copyright 2022 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 +// +// https://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 classroom_create_course_with_alias_class] +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.HttpRequestInitializer; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.classroom.Classroom; +import com.google.api.services.classroom.ClassroomScopes; +import com.google.api.services.classroom.model.Course; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import java.io.IOException; +import java.util.Collections; + +/* Class to demonstrate how to create a course with an alias. */ +public class CreateCourseWithAlias { + /** + * Create a new course with an alias. Set the new course id to the desired alias. + * + * @return - newly created course. + * @throws IOException - if credentials file not found. + */ + public static Course createCourseWithAlias() throws IOException { + /* Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity for + guides on implementing OAuth2 for your application. */ + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSES)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); + + // Create the classroom API client. + Classroom service = new Classroom.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Classroom samples") + .build(); + + // [START classroom_create_course_with_alias_code_snippet] + + Course course = null; + + /* Create a new Course with the alias set as the id field. Project-wide aliases use a prefix + of "p:" and can only be seen and used by the application that created them. */ + Course content = new Course() + .setId("p:history_4_2022") + .setName("9th Grade History") + .setSection("Period 4") + .setDescriptionHeading("Welcome to 9th Grade History.") + .setOwnerId("me") + .setCourseState("PROVISIONED"); + + try { + course = service.courses().create(content).execute(); + // Prints the new created course id and name + System.out.printf("Course created: %s (%s)\n", course.getName(), course.getId()); + } catch (GoogleJsonResponseException e) { + //TODO (developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 409) { + System.out.printf("The course alias already exists: %s.\n", content.getId()); + } else { + throw e; + } + } catch (Exception e) { + throw e; + } + return course; + + // [END classroom_create_course_with_alias_code_snippet] + + } +} +// [END classroom_create_course_with_alias_class] diff --git a/classroom/snippets/src/main/java/CreateCourseWork.java b/classroom/snippets/src/main/java/CreateCourseWork.java new file mode 100644 index 00000000..631ced38 --- /dev/null +++ b/classroom/snippets/src/main/java/CreateCourseWork.java @@ -0,0 +1,107 @@ +// Copyright 2022 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 +// +// https://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 classroom_create_coursework_class] +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.HttpRequestInitializer; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.classroom.Classroom; +import com.google.api.services.classroom.ClassroomScopes; +import com.google.api.services.classroom.model.CourseWork; +import com.google.api.services.classroom.model.Date; +import com.google.api.services.classroom.model.Link; +import com.google.api.services.classroom.model.Material; +import com.google.api.services.classroom.model.TimeOfDay; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import java.io.IOException; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +/* Class to demonstrate the use of Classroom Create CourseWork API. */ +public class CreateCourseWork { + /** + * Creates course work. + * + * @param courseId - id of the course to create coursework in. + * @return - newly created CourseWork object. + * @throws IOException - if credentials file not found. + */ + public static CourseWork createCourseWork(String courseId) throws IOException { + /* Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity for + guides on implementing OAuth2 for your application. */ + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); + + // Create the classroom API client. + Classroom service = new Classroom.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Classroom samples") + .build(); + + // [START classroom_create_coursework_code_snippet] + + CourseWork courseWork = null; + try { + // Create a link to add as a material on course work. + Link articleLink = new Link() + .setTitle("SR-71 Blackbird") + .setUrl("https://www.lockheedmartin.com/en-us/news/features/history/blackbird.html"); + + // Create a list of Materials to add to course work. + List materials = Arrays.asList(new Material().setLink(articleLink)); + + /* Create new CourseWork object with the material attached. + Set workType to `ASSIGNMENT`. Possible values of workType can be found here: + https://developers.google.com/classroom/reference/rest/v1/CourseWorkType + Set state to `PUBLISHED`. Possible values of state can be found here: + https://developers.google.com/classroom/reference/rest/v1/courses.courseWork#courseworkstate */ + CourseWork content = new CourseWork() + .setTitle("Supersonic aviation") + .setDescription("Read about how the SR-71 Blackbird, the world’s fastest and " + + "highest-flying manned aircraft, was built.") + .setMaterials(materials) + .setDueDate(new Date().setMonth(12).setDay(10).setYear(2022)) + .setDueTime(new TimeOfDay().setHours(15).setMinutes(0)) + .setWorkType("ASSIGNMENT") + .setState("PUBLISHED"); + + courseWork = service.courses().courseWork().create(courseId, content) + .execute(); + } catch (GoogleJsonResponseException e) { + //TODO (developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("The courseId does not exist: %s.\n", courseId); + } else { + throw e; + } + throw e; + } catch (Exception e) { + throw e; + } + return courseWork; + + // [END classroom_create_coursework_code_snippet] + } +} +// [END classroom_create_coursework_class] \ No newline at end of file diff --git a/classroom/snippets/src/main/java/CreateTopic.java b/classroom/snippets/src/main/java/CreateTopic.java new file mode 100644 index 00000000..a46e573f --- /dev/null +++ b/classroom/snippets/src/main/java/CreateTopic.java @@ -0,0 +1,81 @@ +// Copyright 2022 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 +// +// https://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 classroom_create_topic_class] + +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.HttpRequestInitializer; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.classroom.Classroom; +import com.google.api.services.classroom.ClassroomScopes; +import com.google.api.services.classroom.model.Topic; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import java.io.IOException; +import java.util.Collections; + +/* Class to demonstrate how to create a topic. */ +public class CreateTopic { + /** + * Create a new topic in a course. + * + * @param courseId - the id of the course to create a topic in. + * @return - newly created topic. + * @throws IOException - if credentials file not found. + */ + public static Topic createTopic(String courseId) throws IOException { + /* Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity for + guides on implementing OAuth2 for your application. */ + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_TOPICS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); + + // Create the classroom API client. + Classroom service = new Classroom.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Classroom samples") + .build(); + + // [START classroom_create_topic_code_snippet] + + Topic topic = null; + try { + // Create the new Topic. + Topic content = new Topic().setName("Semester 1"); + topic = service.courses().topics().create(courseId, content).execute(); + System.out.println("Topic id: " + topic.getTopicId() + "\n" + "Course id: " + courseId); + } catch (GoogleJsonResponseException e) { + //TODO (developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("The courseId does not exist: %s.\n", courseId); + } else { + throw e; + } + } catch (Exception e) { + throw e; + } + return topic; + + // [END classroom_create_topic_code_snippet] + + } +} +// [END classroom_create_topic_class] diff --git a/classroom/snippets/src/main/java/DeleteTopic.java b/classroom/snippets/src/main/java/DeleteTopic.java new file mode 100644 index 00000000..b8ee8f73 --- /dev/null +++ b/classroom/snippets/src/main/java/DeleteTopic.java @@ -0,0 +1,76 @@ +// Copyright 2022 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 +// +// https://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 classroom_delete_topic_class] + +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.HttpRequestInitializer; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.classroom.Classroom; +import com.google.api.services.classroom.ClassroomScopes; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import java.io.IOException; +import java.util.Collections; + +/* Class to demonstrate how to delete a topic. */ +public class DeleteTopic { + /** + * Delete a topic in a course. + * + * @param courseId - the id of the course where the topic belongs. + * @param topicId - the id of the topic to delete. + * @return - updated topic. + * @throws IOException - if credentials file not found. + */ + public static void deleteTopic(String courseId, String topicId) throws IOException { + /* Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity for + guides on implementing OAuth2 for your application. */ + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_TOPICS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); + + // Create the classroom API client. + Classroom service = new Classroom.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Classroom samples") + .build(); + + // [START classroom_delete_topic_code_snippet] + + try { + service.courses().topics().delete(courseId, topicId).execute(); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("The courseId or topicId does not exist: %s, %s.\n", courseId, topicId); + } else { + throw e; + } + } catch (Exception e) { + throw e; + } + + // [END classroom_delete_topic_code_snippet] + + } +} +// [END classroom_delete_topic_class] diff --git a/classroom/snippets/src/main/java/GetTopic.java b/classroom/snippets/src/main/java/GetTopic.java new file mode 100644 index 00000000..5332bd5c --- /dev/null +++ b/classroom/snippets/src/main/java/GetTopic.java @@ -0,0 +1,80 @@ +// Copyright 2022 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 +// +// https://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 classroom_get_topic_class] + +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.HttpRequestInitializer; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.classroom.Classroom; +import com.google.api.services.classroom.ClassroomScopes; +import com.google.api.services.classroom.model.Topic; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import java.io.IOException; +import java.util.Collections; + +/* Class to demonstrate how to get a topic. */ +public class GetTopic { + /** + * Get a topic in a course. + * + * @param courseId - the id of the course the topic belongs to. + * @param topicId - the id of the topic to retrieve. + * @return - the topic to retrieve. + * @throws IOException - if credentials file not found. + */ + public static Topic getTopic(String courseId, String topicId) throws IOException { + /* Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity for + guides on implementing OAuth2 for your application. */ + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_TOPICS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); + + // Create the classroom API client. + Classroom service = new Classroom.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Classroom samples") + .build(); + + // [START classroom_get_topic_code_snippet] + + Topic topic = null; + try { + // Get the topic. + topic = service.courses().topics().get(courseId, topicId).execute(); + } catch (GoogleJsonResponseException e) { + //TODO (developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("The courseId or topicId does not exist: %s, %s.\n", courseId, topicId); + } else { + throw e; + } + } catch (Exception e) { + throw e; + } + return topic; + + // [END classroom_get_topic_code_snippet] + + } +} +// [END classroom_get_topic_class] diff --git a/classroom/snippets/src/main/java/ListTopics.java b/classroom/snippets/src/main/java/ListTopics.java new file mode 100644 index 00000000..61ea9b89 --- /dev/null +++ b/classroom/snippets/src/main/java/ListTopics.java @@ -0,0 +1,98 @@ +// Copyright 2022 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 +// +// https://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 classroom_list_topic_class] + +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.HttpRequestInitializer; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.classroom.Classroom; +import com.google.api.services.classroom.ClassroomScopes; +import com.google.api.services.classroom.model.ListTopicResponse; +import com.google.api.services.classroom.model.Topic; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/* Class to demonstrate how to list topics in a course. */ +public class ListTopics { + /** + * List topics in a course. + * + * @param courseId - the id of the course to retrieve topics for. + * @return - the list of topics in the course that the caller is permitted to view. + * @throws IOException - if credentials file not found. + */ + public static List listTopics(String courseId) throws IOException { + /* Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity for + guides on implementing OAuth2 for your application. */ + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_TOPICS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); + + // Create the classroom API client. + Classroom service = new Classroom.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Classroom samples") + .build(); + + // [START classroom_list_topic_code_snippet] + + List topics = new ArrayList<>(); + String pageToken = null; + + try { + do { + ListTopicResponse response = service.courses().topics().list(courseId) + .setPageSize(100) + .setPageToken(pageToken) + .execute(); + topics.addAll(response.getTopic()); + pageToken = response.getNextPageToken(); + } while (pageToken != null); + + if (topics.isEmpty()) { + System.out.println("No topics found."); + } else { + for (Topic topic : topics) { + System.out.printf("%s (%s)\n", topic.getName(), topic.getTopicId()); + } + } + } catch (GoogleJsonResponseException e) { + //TODO (developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("The courseId does not exist: %s.\n", courseId); + } else { + throw e; + } + } catch (Exception e) { + throw e; + } + return topics; + + // [END classroom_list_topic_code_snippet] + + } +} +// [END classroom_list_topic_class] diff --git a/classroom/snippets/src/main/java/UpdateTopic.java b/classroom/snippets/src/main/java/UpdateTopic.java new file mode 100644 index 00000000..770bee30 --- /dev/null +++ b/classroom/snippets/src/main/java/UpdateTopic.java @@ -0,0 +1,89 @@ +// Copyright 2022 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 +// +// https://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 classroom_update_topic_class] + +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.HttpRequestInitializer; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.classroom.Classroom; +import com.google.api.services.classroom.ClassroomScopes; +import com.google.api.services.classroom.model.Topic; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import java.io.IOException; +import java.util.Collections; + +/* Class to demonstrate how to update one or more fields in a topic. */ +public class UpdateTopic { + /** + * Update one or more fields in a topic in a course. + * + * @param courseId - the id of the course where the topic belongs. + * @param topicId - the id of the topic to update. + * @return - updated topic. + * @throws IOException - if credentials file not found. + */ + public static Topic updateTopic(String courseId, String topicId) throws IOException { + /* Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity for + guides on implementing OAuth2 for your application. */ + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_TOPICS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); + + // Create the classroom API client. + Classroom service = new Classroom.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Classroom samples") + .build(); + + // [START classroom_update_topic_code_snippet] + + Topic topic = null; + try { + // Retrieve the topic to update. + Topic topicToUpdate = service.courses().topics().get(courseId, topicId).execute(); + + // Update the name field for the topic retrieved. + topicToUpdate.setName("Semester 2"); + + /* Call the patch endpoint and set the updateMask query parameter to the field that needs to + be updated. */ + topic = service.courses().topics().patch(courseId, topicId, topicToUpdate) + .set("updateMask", "name") + .execute(); + } catch(GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("The courseId or topicId does not exist: %s, %s.\n", courseId, topicId); + } else { + throw e; + } + } catch (Exception e) { + throw e; + } + return topic; + + // [END classroom_update_topic_code_snippet] + + } +} +// [END classroom_update_topic_class] diff --git a/classroom/snippets/src/test/java/BaseTest.java b/classroom/snippets/src/test/java/BaseTest.java index c1e46717..cc3996de 100644 --- a/classroom/snippets/src/test/java/BaseTest.java +++ b/classroom/snippets/src/test/java/BaseTest.java @@ -80,6 +80,10 @@ public CourseAlias createAlias(String courseId) throws IOException { } public void deleteCourse(String courseId) throws IOException { + // updating the course state to be archived so the course can be deleted. + Course course = service.courses().get(courseId).execute(); + course.setCourseState("ARCHIVED"); + this.service.courses().update(courseId, course).execute(); this.service.courses().delete(courseId).execute(); } } diff --git a/classroom/snippets/src/test/java/TestAddAliasToCourse.java b/classroom/snippets/src/test/java/TestAddAliasToCourse.java new file mode 100644 index 00000000..c5b85777 --- /dev/null +++ b/classroom/snippets/src/test/java/TestAddAliasToCourse.java @@ -0,0 +1,34 @@ +// Copyright 2022 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 +// +// https://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. + +import com.google.api.services.classroom.model.CourseAlias; +import java.io.IOException; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; + +// Unit test class for Add Alias classroom snippet +public class TestAddAliasToCourse extends BaseTest { + + @Test + public void testAddCourseAlias() throws IOException { + CourseAlias courseAlias = AddAliasToCourse.addAliasToCourse(testCourse.getId()); + List courseAliases = service.courses().aliases() + .list(testCourse.getId() + ).execute() + .getAliases(); + Assert.assertNotNull("Course alias not returned.", courseAlias); + Assert.assertTrue("No course aliases exist.", courseAliases.size() > 0); + } +} \ No newline at end of file diff --git a/classroom/snippets/src/test/java/TestCreateCourseWithAlias.java b/classroom/snippets/src/test/java/TestCreateCourseWithAlias.java new file mode 100644 index 00000000..5152b984 --- /dev/null +++ b/classroom/snippets/src/test/java/TestCreateCourseWithAlias.java @@ -0,0 +1,36 @@ +// Copyright 2022 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 +// +// https://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. + +import com.google.api.services.classroom.model.Course; +import com.google.api.services.classroom.model.CourseAlias; +import java.io.IOException; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; + +// Unit test class for Create Alias classroom snippet +public class TestCreateCourseWithAlias extends BaseTest { + + @Test + public void testCreateCourseWithAlias() throws IOException { + Course course = CreateCourseWithAlias.createCourseWithAlias(); + List courseAliases = service.courses().aliases() + .list(course.getId() + ).execute() + .getAliases(); + Assert.assertNotNull("Course not returned.", course); + Assert.assertTrue("No course aliases exist.", courseAliases.size() > 0); + deleteCourse(course.getId()); + } +} \ No newline at end of file diff --git a/classroom/snippets/src/test/java/TestCreateCourseWork.java b/classroom/snippets/src/test/java/TestCreateCourseWork.java new file mode 100644 index 00000000..e3a25b6b --- /dev/null +++ b/classroom/snippets/src/test/java/TestCreateCourseWork.java @@ -0,0 +1,28 @@ +// Copyright 2022 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 +// +// https://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. + +import com.google.api.services.classroom.model.CourseWork; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Test; + +// Unit test class for Create Coursework classroom snippet +public class TestCreateCourseWork extends BaseTest { + + @Test + public void testCreateCoursework() throws IOException { + CourseWork courseWork = CreateCourseWork.createCourseWork(testCourse.getId()); + Assert.assertNotNull("Coursework not returned.", courseWork); + } +} diff --git a/classroom/snippets/src/test/java/TestCreateTopic.java b/classroom/snippets/src/test/java/TestCreateTopic.java new file mode 100644 index 00000000..e2d77586 --- /dev/null +++ b/classroom/snippets/src/test/java/TestCreateTopic.java @@ -0,0 +1,28 @@ +// Copyright 2022 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 +// +// https://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. + +import com.google.api.services.classroom.model.Topic; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Test; + +// Unit test class for Create Topic classroom snippet +public class TestCreateTopic extends BaseTest { + + @Test + public void testCreateTopic() throws IOException { + Topic topic = CreateTopic.createTopic(testCourse.getId()); + Assert.assertNotNull("Topic not returned.", topic); + } +} diff --git a/classroom/snippets/src/test/java/TestDeleteTopic.java b/classroom/snippets/src/test/java/TestDeleteTopic.java new file mode 100644 index 00000000..b093865c --- /dev/null +++ b/classroom/snippets/src/test/java/TestDeleteTopic.java @@ -0,0 +1,29 @@ +// Copyright 2022 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 +// +// https://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. + +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.services.classroom.model.Topic; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Test; + +public class TestDeleteTopic extends BaseTest { + @Test + public void testDeleteTopic() throws IOException { + Topic topic = CreateTopic.createTopic(testCourse.getId()); + DeleteTopic.deleteTopic(testCourse.getId(), topic.getTopicId()); + Assert.assertThrows(GoogleJsonResponseException.class, + () -> GetTopic.getTopic(testCourse.getId(), topic.getTopicId())); + } +} diff --git a/classroom/snippets/src/test/java/TestGetTopic.java b/classroom/snippets/src/test/java/TestGetTopic.java new file mode 100644 index 00000000..b7cb7840 --- /dev/null +++ b/classroom/snippets/src/test/java/TestGetTopic.java @@ -0,0 +1,31 @@ +// Copyright 2022 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 +// +// https://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. + +import com.google.api.services.classroom.model.Topic; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Test; + +// Unit test class for Get Topic classroom snippet +public class TestGetTopic extends BaseTest { + + @Test + public void testGetTopic() throws IOException { + Topic topic = CreateTopic.createTopic(testCourse.getId()); + Topic getTopic = GetTopic.getTopic(testCourse.getId(), topic.getTopicId()); + Assert.assertNotNull("Topic could not be created.", topic); + Assert.assertNotNull("Topic could not be retrieved.", getTopic); + Assert.assertEquals("Wrong topic was retrieved.", topic, getTopic); + } +} diff --git a/classroom/snippets/src/test/java/TestListTopics.java b/classroom/snippets/src/test/java/TestListTopics.java new file mode 100644 index 00000000..081be57b --- /dev/null +++ b/classroom/snippets/src/test/java/TestListTopics.java @@ -0,0 +1,31 @@ +// Copyright 2022 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 +// +// https://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. + +import com.google.api.services.classroom.model.Topic; +import java.io.IOException; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; + +// Unit test class for List Topics classroom snippet +public class TestListTopics extends BaseTest { + + @Test + public void testListTopics() throws IOException { + CreateTopic.createTopic(testCourse.getId()); + List listTopics = ListTopics.listTopics(testCourse.getId()); + Assert.assertNotNull("Topics could not be retrieved.", listTopics); + Assert.assertFalse("No topics were retrieved.", listTopics.size() == 0); + } +} diff --git a/classroom/snippets/src/test/java/TestUpdateTopic.java b/classroom/snippets/src/test/java/TestUpdateTopic.java new file mode 100644 index 00000000..5b1b9eec --- /dev/null +++ b/classroom/snippets/src/test/java/TestUpdateTopic.java @@ -0,0 +1,28 @@ +// Copyright 2022 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 +// +// https://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. +import com.google.api.services.classroom.model.Topic; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Test; + +// Unit test class for Update Topic classroom snippet +public class TestUpdateTopic extends BaseTest { + @Test + public void testUpdateTopic() throws IOException { + Topic topic = CreateTopic.createTopic(testCourse.getId()); + System.out.println("New topic created: " + topic.getName()); + Topic updatedTopic = UpdateTopic.updateTopic(testCourse.getId(), topic.getTopicId()); + Assert.assertNotEquals("Topic name was not updated.", topic.getName(), updatedTopic.getName()); + } +} From e49fb413ed95f62a4c0d71dd7ecb20b755585cd7 Mon Sep 17 00:00:00 2001 From: Mahima Desetty <45216855+mahima-desetty@users.noreply.github.com> Date: Mon, 19 Dec 2022 11:17:03 -0600 Subject: [PATCH 02/19] feat: added List, ModifyAttachments, Patch, Return methods for StudentSubmission resource (#467) * add alias snippet and unit test * java snippets for topics, create coursework, create alias * updates based on team review * renamed alias methods, added devsite comments * added missing license header to TestDeleteTopic.java * Adding List, ModifyAttachments, Patch, Return StudentSubmission methods * minor fixes * adding comments for developer * modifications based on team review * modifications based on team review * Adding print statements and devsite tag to ListCourseAliases --- .../src/main/java/CreateCourseWork.java | 5 +- .../snippets/src/main/java/GetTopic.java | 1 + .../src/main/java/ListCourseAliases.java | 8 +- .../src/main/java/ListStudentSubmissions.java | 105 ++++++++++++++++++ .../src/main/java/ListSubmissions.java | 102 +++++++++++++++++ .../snippets/src/main/java/ListTopics.java | 6 +- .../ModifyAttachmentsStudentSubmission.java | 100 +++++++++++++++++ .../src/main/java/PatchStudentSubmission.java | 98 ++++++++++++++++ .../main/java/ReturnStudentSubmission.java | 80 +++++++++++++ .../snippets/src/main/java/UpdateTopic.java | 5 +- .../src/test/java/TestListSubmissions.java | 31 ++++++ 11 files changed, 534 insertions(+), 7 deletions(-) create mode 100644 classroom/snippets/src/main/java/ListStudentSubmissions.java create mode 100644 classroom/snippets/src/main/java/ListSubmissions.java create mode 100644 classroom/snippets/src/main/java/ModifyAttachmentsStudentSubmission.java create mode 100644 classroom/snippets/src/main/java/PatchStudentSubmission.java create mode 100644 classroom/snippets/src/main/java/ReturnStudentSubmission.java create mode 100644 classroom/snippets/src/test/java/TestListSubmissions.java diff --git a/classroom/snippets/src/main/java/CreateCourseWork.java b/classroom/snippets/src/main/java/CreateCourseWork.java index 631ced38..7f9973ca 100644 --- a/classroom/snippets/src/main/java/CreateCourseWork.java +++ b/classroom/snippets/src/main/java/CreateCourseWork.java @@ -80,13 +80,14 @@ public static CourseWork createCourseWork(String courseId) throws IOException { .setDescription("Read about how the SR-71 Blackbird, the world’s fastest and " + "highest-flying manned aircraft, was built.") .setMaterials(materials) - .setDueDate(new Date().setMonth(12).setDay(10).setYear(2022)) - .setDueTime(new TimeOfDay().setHours(15).setMinutes(0)) .setWorkType("ASSIGNMENT") .setState("PUBLISHED"); courseWork = service.courses().courseWork().create(courseId, content) .execute(); + + /* Prints the created courseWork. */ + System.out.printf("CourseWork created: %s\n", courseWork.getTitle()); } catch (GoogleJsonResponseException e) { //TODO (developer) - handle error appropriately GoogleJsonError error = e.getDetails(); diff --git a/classroom/snippets/src/main/java/GetTopic.java b/classroom/snippets/src/main/java/GetTopic.java index 5332bd5c..140a0407 100644 --- a/classroom/snippets/src/main/java/GetTopic.java +++ b/classroom/snippets/src/main/java/GetTopic.java @@ -60,6 +60,7 @@ public static Topic getTopic(String courseId, String topicId) throws IOException try { // Get the topic. topic = service.courses().topics().get(courseId, topicId).execute(); + System.out.printf("Topic '%s' found.\n", topic.getName()); } catch (GoogleJsonResponseException e) { //TODO (developer) - handle error appropriately GoogleJsonError error = e.getDetails(); diff --git a/classroom/snippets/src/main/java/ListCourseAliases.java b/classroom/snippets/src/main/java/ListCourseAliases.java index 171f4fa6..c3141cf1 100644 --- a/classroom/snippets/src/main/java/ListCourseAliases.java +++ b/classroom/snippets/src/main/java/ListCourseAliases.java @@ -13,7 +13,7 @@ // limitations under the License. -// [START classroom_list_aliases] +// [START classroom_list_aliases_class] import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; @@ -57,6 +57,8 @@ public static List listCourseAliases(String courseId) .setApplicationName("Classroom samples") .build(); + // [START classroom_list_aliases_code_snippet] + String pageToken = null; List courseAliases = new ArrayList<>(); @@ -89,6 +91,8 @@ public static List listCourseAliases(String courseId) } } return courseAliases; + + // [END classroom_list_aliases_code_snippet] } } -// [END classroom_list_aliases] \ No newline at end of file +// [END classroom_list_aliases_class] \ No newline at end of file diff --git a/classroom/snippets/src/main/java/ListStudentSubmissions.java b/classroom/snippets/src/main/java/ListStudentSubmissions.java new file mode 100644 index 00000000..acc7b898 --- /dev/null +++ b/classroom/snippets/src/main/java/ListStudentSubmissions.java @@ -0,0 +1,105 @@ +// Copyright 2022 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 +// +// https://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 classroom_list_student_submissions_class] + +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.HttpRequestInitializer; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.classroom.Classroom; +import com.google.api.services.classroom.ClassroomScopes; +import com.google.api.services.classroom.model.ListStudentSubmissionsResponse; +import com.google.api.services.classroom.model.StudentSubmission; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/* Class to demonstrate the use of Classroom List StudentSubmissions API. */ +public class ListStudentSubmissions { + /** + * Retrieves a specific student's submissions for the specified course work. + * + * @param courseId - identifier of the course. + * @param courseWorkId - identifier of the course work. + * @param userId - identifier of the student whose work to return. + * @return - list of student submissions. + * @throws IOException - if credentials file not found. + */ + public static List listStudentSubmissions(String courseId, String courseWorkId, + String userId) throws IOException { + /* Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity for + guides on implementing OAuth2 for your application. */ + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); + + // Create the classroom API client. + Classroom service = new Classroom.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Classroom samples") + .build(); + + // [START classroom_list_student_submissions_code_snippet] + + List studentSubmissions = new ArrayList<>(); + String pageToken = null; + + try { + do { + // Set the userId as a query parameter on the request. + ListStudentSubmissionsResponse response = service.courses().courseWork().studentSubmissions() + .list(courseId, courseWorkId) + .set("userId", userId) + .execute(); + if (response.getStudentSubmissions() != null) { + studentSubmissions.addAll(response.getStudentSubmissions()); + pageToken = response.getNextPageToken(); + } + } while (pageToken != null); + + if (studentSubmissions.isEmpty()) { + System.out.println("No student submission found."); + } else { + for (StudentSubmission submission : studentSubmissions) { + System.out.printf("Student submission: %s.\n", submission.getId()); + } + } + } catch (GoogleJsonResponseException e) { + //TODO (developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("The courseId (%s), courseWorkId (%s), or userId (%s) does " + + "not exist.\n", courseId, courseWorkId, userId); + } else { + throw e; + } + } catch (Exception e) { + throw e; + } + return studentSubmissions; + + // [END classroom_list_student_submissions_code_snippet] + + } +} +// [END classroom_list_student_submissions_class] \ No newline at end of file diff --git a/classroom/snippets/src/main/java/ListSubmissions.java b/classroom/snippets/src/main/java/ListSubmissions.java new file mode 100644 index 00000000..ed5898de --- /dev/null +++ b/classroom/snippets/src/main/java/ListSubmissions.java @@ -0,0 +1,102 @@ +// Copyright 2022 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 +// +// https://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 classroom_list_submissions_class] + +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.HttpRequestInitializer; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.classroom.Classroom; +import com.google.api.services.classroom.ClassroomScopes; +import com.google.api.services.classroom.model.ListStudentSubmissionsResponse; +import com.google.api.services.classroom.model.StudentSubmission; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/* Class to demonstrate the use of Classroom List StudentSubmissions API. */ +public class ListSubmissions { + /** + * Retrieves submissions for all students for the specified course work in a course. + * + * @param courseId - identifier of the course. + * @param courseWorkId - identifier of the course work. + * @return - list of student submissions. + * @throws IOException - if credentials file not found. + */ + public static List listSubmissions(String courseId, String courseWorkId) + throws IOException { + /* Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity for + guides on implementing OAuth2 for your application. */ + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); + + // Create the classroom API client. + Classroom service = new Classroom.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Classroom samples") + .build(); + + // [START classroom_list_submissions_code_snippet] + + List studentSubmissions = new ArrayList<>(); + String pageToken = null; + + try { + do { + ListStudentSubmissionsResponse response = service.courses().courseWork().studentSubmissions() + .list(courseId, courseWorkId) + .execute(); + if (response.getStudentSubmissions() != null) { + studentSubmissions.addAll(response.getStudentSubmissions()); + } + } while (pageToken != null); + + if (studentSubmissions.isEmpty()) { + System.out.println("No student submission found."); + } else { + for (StudentSubmission submission : studentSubmissions) { + System.out.printf("Student id (%s), student submission id (%s)\n", submission.getUserId(), + submission.getId()); + } + } + } catch (GoogleJsonResponseException e) { + //TODO (developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("The courseId (%s) or courseWorkId (%s) does not exist.\n", courseId, + courseWorkId); + } else { + throw e; + } + } catch (Exception e) { + throw e; + } + return studentSubmissions; + + // [END classroom_list_submissions_code_snippet] + + } +} +// [END classroom_list_submissions_class] \ No newline at end of file diff --git a/classroom/snippets/src/main/java/ListTopics.java b/classroom/snippets/src/main/java/ListTopics.java index 61ea9b89..e754f82b 100644 --- a/classroom/snippets/src/main/java/ListTopics.java +++ b/classroom/snippets/src/main/java/ListTopics.java @@ -67,8 +67,10 @@ public static List listTopics(String courseId) throws IOException { .setPageSize(100) .setPageToken(pageToken) .execute(); - topics.addAll(response.getTopic()); - pageToken = response.getNextPageToken(); + if (response.getTopic() != null) { + topics.addAll(response.getTopic()); + pageToken = response.getNextPageToken(); + } } while (pageToken != null); if (topics.isEmpty()) { diff --git a/classroom/snippets/src/main/java/ModifyAttachmentsStudentSubmission.java b/classroom/snippets/src/main/java/ModifyAttachmentsStudentSubmission.java new file mode 100644 index 00000000..252f51f5 --- /dev/null +++ b/classroom/snippets/src/main/java/ModifyAttachmentsStudentSubmission.java @@ -0,0 +1,100 @@ +// Copyright 2022 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 +// +// https://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 classroom_modify_attachments_student_submissions_class] + +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.HttpRequestInitializer; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.classroom.Classroom; +import com.google.api.services.classroom.ClassroomScopes; +import com.google.api.services.classroom.model.Attachment; +import com.google.api.services.classroom.model.Link; +import com.google.api.services.classroom.model.ModifyAttachmentsRequest; +import com.google.api.services.classroom.model.StudentSubmission; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import java.io.IOException; +import java.util.Arrays; +import java.util.Collections; + +/* Class to demonstrate the use of Classroom ModifyAttachments StudentSubmissions API. */ +public class ModifyAttachmentsStudentSubmission { + /** + * Modify attachments on a student submission. + * + * @param courseId - identifier of the course. + * @param courseWorkId - identifier of the course work. + * @param id - identifier of the student submission. + * @return - the modified student submission. + * @throws IOException - if credentials file not found. + */ + public static StudentSubmission modifyAttachments(String courseId, String courseWorkId, String id) + throws IOException { + /* Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity for + guides on implementing OAuth2 for your application. */ + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); + + // Create the classroom API client. + Classroom service = new Classroom.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Classroom samples") + .build(); + + // [START classroom_modify_attachments_student_submissions_code_snippet] + + StudentSubmission studentSubmission = null; + try { + // Create ModifyAttachmentRequest object that includes a new attachment with a link. + Link link = new Link().setUrl("https://en.wikipedia.org/wiki/Irrational_number"); + Attachment attachment = new Attachment().setLink(link); + ModifyAttachmentsRequest modifyAttachmentsRequest = new ModifyAttachmentsRequest() + .setAddAttachments(Arrays.asList(attachment)); + + // The modified studentSubmission object is returned with the new attachment added to it. + studentSubmission = service.courses().courseWork().studentSubmissions().modifyAttachments( + courseId, courseWorkId, id, modifyAttachmentsRequest) + .execute(); + + /* Prints the modified student submission. */ + System.out.printf("Modified student submission attachments: '%s'.\n", studentSubmission + .getAssignmentSubmission() + .getAttachments()); + } catch (GoogleJsonResponseException e) { + //TODO (developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("The courseId (%s), courseWorkId (%s), or studentSubmissionId (%s) does " + + "not exist.\n", courseId, courseWorkId, id); + } else { + throw e; + } + } catch(Exception e) { + throw e; + } + return studentSubmission; + + // [END classroom_modify_attachments_student_submissions_code_snippet] + + } +} +// [END classroom_modify_attachments_student_submissions_class] \ No newline at end of file diff --git a/classroom/snippets/src/main/java/PatchStudentSubmission.java b/classroom/snippets/src/main/java/PatchStudentSubmission.java new file mode 100644 index 00000000..1690ef8e --- /dev/null +++ b/classroom/snippets/src/main/java/PatchStudentSubmission.java @@ -0,0 +1,98 @@ +// Copyright 2022 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 +// +// https://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 classroom_patch_student_submissions_class] + +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.HttpRequestInitializer; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.classroom.Classroom; +import com.google.api.services.classroom.ClassroomScopes; +import com.google.api.services.classroom.model.StudentSubmission; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import java.io.IOException; +import java.util.Collections; + +/* Class to demonstrate the use of Classroom Patch StudentSubmissions API. */ +public class PatchStudentSubmission { + /** + * Updates the draft grade and/or assigned grade of a student submission. + * + * @param courseId - identifier of the course. + * @param courseWorkId - identifier of the course work. + * @param id - identifier of the student submission. + * @return - the updated student submission. + * @throws IOException - if credentials file not found. + */ + public static StudentSubmission patchStudentSubmission(String courseId, String courseWorkId, + String id) throws IOException { + /* Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity for + guides on implementing OAuth2 for your application. */ + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); + + // Create the classroom API client. + Classroom service = new Classroom.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Classroom samples") + .build(); + + // [START classroom_patch_student_submissions_code_snippet] + + StudentSubmission studentSubmission = null; + try { + // Updating the draftGrade and assignedGrade fields for the specific student submission. + StudentSubmission content = service.courses().courseWork().studentSubmissions() + .get(courseId, courseWorkId, id) + .execute(); + content.setAssignedGrade(90.00); + content.setDraftGrade(80.00); + + // The updated studentSubmission object is returned with the new draftGrade and assignedGrade. + studentSubmission = service.courses().courseWork().studentSubmissions() + .patch(courseId, courseWorkId, id, content) + .set("updateMask", "draftGrade,assignedGrade") + .execute(); + + /* Prints the updated student submission. */ + System.out.printf("Updated student submission draft grade (%s) and assigned grade (%s).\n", + studentSubmission.getDraftGrade(), + studentSubmission.getAssignedGrade()); + } catch (GoogleJsonResponseException e) { + //TODO (developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("The courseId (%s), courseWorkId (%s), or studentSubmissionId (%s) does " + + "not exist.\n", courseId, courseWorkId, id); + } else { + throw e; + } + } catch (Exception e) { + throw e; + } + return studentSubmission; + + // [END classroom_patch_student_submissions_code_snippet] + + } +} +// [END classroom_patch_student_submissions_class] \ No newline at end of file diff --git a/classroom/snippets/src/main/java/ReturnStudentSubmission.java b/classroom/snippets/src/main/java/ReturnStudentSubmission.java new file mode 100644 index 00000000..6b40fc96 --- /dev/null +++ b/classroom/snippets/src/main/java/ReturnStudentSubmission.java @@ -0,0 +1,80 @@ +// Copyright 2022 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 +// +// https://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 classroom_return_student_submissions_class] + +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.HttpRequestInitializer; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.classroom.Classroom; +import com.google.api.services.classroom.ClassroomScopes; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import java.io.IOException; +import java.util.Collections; + +/* Class to demonstrate the use of Classroom Return StudentSubmissions API. */ +public class ReturnStudentSubmission { + /** + * Return a student submission back to the student which updates the submission state to `RETURNED`. + * + * @param courseId - identifier of the course. + * @param courseWorkId - identifier of the course work. + * @param id - identifier of the student submission. + * @throws IOException - if credentials file not found. + */ + public static void returnSubmission(String courseId, String courseWorkId, String id) + throws IOException { + /* Load pre-authorized user credentials from the environment. + TODO(developer) - See https://developers.google.com/identity for + guides on implementing OAuth2 for your application. */ + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); + + // Create the classroom API client. + Classroom service = new Classroom.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Classroom samples") + .build(); + + // [START classroom_return_student_submissions_code_snippet] + + try { + service.courses().courseWork().studentSubmissions() + .classroomReturn(courseId, courseWorkId, id, null) + .execute(); + } catch (GoogleJsonResponseException e) { + //TODO (developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("The courseId (%s), courseWorkId (%s), or studentSubmissionId (%s) does " + + "not exist.\n", courseId, courseWorkId, id); + } else { + throw e; + } + } catch (Exception e) { + throw e; + } + + // [END classroom_return_student_submissions_code_snippet] + + } +} +// [END classroom_return_student_submissions_class] diff --git a/classroom/snippets/src/main/java/UpdateTopic.java b/classroom/snippets/src/main/java/UpdateTopic.java index 770bee30..f45ffeca 100644 --- a/classroom/snippets/src/main/java/UpdateTopic.java +++ b/classroom/snippets/src/main/java/UpdateTopic.java @@ -69,7 +69,10 @@ public static Topic updateTopic(String courseId, String topicId) throws IOExcept topic = service.courses().topics().patch(courseId, topicId, topicToUpdate) .set("updateMask", "name") .execute(); - } catch(GoogleJsonResponseException e) { + + /* Prints the updated topic. */ + System.out.printf("Topic '%s' updated.\n", topic.getName()); + } catch (GoogleJsonResponseException e) { // TODO(developer) - handle error appropriately GoogleJsonError error = e.getDetails(); if (error.getCode() == 404) { diff --git a/classroom/snippets/src/test/java/TestListSubmissions.java b/classroom/snippets/src/test/java/TestListSubmissions.java new file mode 100644 index 00000000..148e9529 --- /dev/null +++ b/classroom/snippets/src/test/java/TestListSubmissions.java @@ -0,0 +1,31 @@ +// Copyright 2022 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 +// +// https://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. + +import com.google.api.services.classroom.model.StudentSubmission; +import java.io.IOException; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; + +// Unit test class for ListSubmissions classroom snippet +public class TestListSubmissions extends BaseTest { + + @Test + public void testListSubmissions() throws IOException { + List submissions = ListSubmissions.listSubmissions( + testCourse.getId(), + "-"); + Assert.assertNotNull("No submissions returned.", submissions); + } +} From 8718e29af586e50c912eb15aa48c57377fd1f2a6 Mon Sep 17 00:00:00 2001 From: Mahima Desetty <45216855+mahima-desetty@users.noreply.github.com> Date: Tue, 17 Jan 2023 12:44:14 -0500 Subject: [PATCH 03/19] feat: added Guardian and Guardian Invitation code snippets. (#528) * add alias snippet and unit test * java snippets for topics, create coursework, create alias * updates based on team review * renamed alias methods, added devsite comments * added missing license header to TestDeleteTopic.java * Adding List, ModifyAttachments, Patch, Return StudentSubmission methods * minor fixes * adding comments for developer * modifications based on team review * modifications based on team review * Adding print statements and devsite tag to ListCourseAliases * added class templates for guardians and guardianInvitations * guardian and guardian invitation implementation * tests for list guardians and list guardian invitations * adding tests for guardians and guardian invites. removing use of ADC for auth. * base test updates * updates based on team feedback * fixing BaseTest.java * updating copyright year to 2023 for new files * testing google-java-format plugin to fix lint errors * updated files after running google-java-format plugin * updated BaseTest * fixing copyright header for BaseTest --- classroom/snippets/build.gradle | 6 +- .../main/java/CancelGuardianInvitation.java | 97 +++++++++++++++++ .../src/main/java/ClassroomCredentials.java | 64 +++++++++++ .../main/java/CreateGuardianInvitation.java | 90 ++++++++++++++++ .../src/main/java/DeleteGuardian.java | 66 ++++++++++++ .../snippets/src/main/java/GetGuardian.java | 74 +++++++++++++ .../ListGuardianInvitationsByStudent.java | 102 ++++++++++++++++++ .../snippets/src/main/java/ListGuardians.java | 99 +++++++++++++++++ .../src/main/java/ListStudentSubmissions.java | 51 +++++---- .../src/main/java/ListSubmissions.java | 50 +++++---- .../snippets/src/main/java/ListTopics.java | 39 ++++--- .../snippets/src/test/java/BaseTest.java | 68 ++++++------ .../java/TestCancelGuardianInvitation.java | 37 +++++++ .../java/TestCreateGuardianInvitation.java | 31 ++++++ .../src/test/java/TestDeleteGuardian.java | 31 ++++++ .../TestListGuardianInvitationsByStudent.java | 31 ++++++ .../src/test/java/TestListGuardians.java | 30 ++++++ 17 files changed, 868 insertions(+), 98 deletions(-) create mode 100644 classroom/snippets/src/main/java/CancelGuardianInvitation.java create mode 100644 classroom/snippets/src/main/java/ClassroomCredentials.java create mode 100644 classroom/snippets/src/main/java/CreateGuardianInvitation.java create mode 100644 classroom/snippets/src/main/java/DeleteGuardian.java create mode 100644 classroom/snippets/src/main/java/GetGuardian.java create mode 100644 classroom/snippets/src/main/java/ListGuardianInvitationsByStudent.java create mode 100644 classroom/snippets/src/main/java/ListGuardians.java create mode 100644 classroom/snippets/src/test/java/TestCancelGuardianInvitation.java create mode 100644 classroom/snippets/src/test/java/TestCreateGuardianInvitation.java create mode 100644 classroom/snippets/src/test/java/TestDeleteGuardian.java create mode 100644 classroom/snippets/src/test/java/TestListGuardianInvitationsByStudent.java create mode 100644 classroom/snippets/src/test/java/TestListGuardians.java diff --git a/classroom/snippets/build.gradle b/classroom/snippets/build.gradle index 6971123c..8def0b0f 100644 --- a/classroom/snippets/build.gradle +++ b/classroom/snippets/build.gradle @@ -7,9 +7,13 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' - implementation 'com.google.auth:google-auth-library-oauth2-http:1.11.0' + implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-classroom:v1-rev20220323-2.0.0' testImplementation 'junit:junit:4.13.2' + + /** This will be removed once all the classes have been updated to use the + * ClassroomCredentials class. */ + implementation 'com.google.auth:google-auth-library-oauth2-http:1.11.0' } test { diff --git a/classroom/snippets/src/main/java/CancelGuardianInvitation.java b/classroom/snippets/src/main/java/CancelGuardianInvitation.java new file mode 100644 index 00000000..33585400 --- /dev/null +++ b/classroom/snippets/src/main/java/CancelGuardianInvitation.java @@ -0,0 +1,97 @@ +// Copyright 2023 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 +// +// https://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 classroom_cancel_guardian_invitation_class] + +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.classroom.Classroom; +import com.google.api.services.classroom.ClassroomScopes; +import com.google.api.services.classroom.model.GuardianInvitation; +import java.io.IOException; +import java.util.Collections; +import java.util.List; + +/* Class to demonstrate the use of Classroom Patch Guardian Invitation API. */ +public class CancelGuardianInvitation { + /** + * Cancel a guardian invitation by modifying the state of the invite. + * + * @param studentId - the id of the student. + * @param invitationId - the id of the guardian invitation to modify. + * @return - the modified guardian invitation. + * @throws IOException - if credentials file not found. + */ + public static GuardianInvitation cancelGuardianInvitation(String studentId, String invitationId) + throws Exception { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + final List SCOPES = + Collections.singletonList(ClassroomScopes.CLASSROOM_GUARDIANLINKS_STUDENTS); + + // Create the classroom API client + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); + + // [START classroom_cancel_guardian_invitation_code_snippet] + + GuardianInvitation guardianInvitation = null; + + try { + /* Change the state of the GuardianInvitation from PENDING to COMPLETE. See + https://developers.google.com/classroom/reference/rest/v1/userProfiles.guardianInvitations#guardianinvitationstate + for other possible states of guardian invitations. */ + GuardianInvitation content = + service.userProfiles().guardianInvitations().get(studentId, invitationId).execute(); + content.setState("COMPLETE"); + + guardianInvitation = + service + .userProfiles() + .guardianInvitations() + .patch(studentId, invitationId, content) + .set("updateMask", "state") + .execute(); + + System.out.printf( + "Invitation (%s) state set to %s\n.", + guardianInvitation.getInvitationId(), guardianInvitation.getState()); + } catch (GoogleJsonResponseException e) { + // TODO (developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf( + "There is no record of studentId (%s) or invitationId (%s).", studentId, invitationId); + } else { + throw e; + } + } catch (Exception e) { + throw e; + } + return guardianInvitation; + + // [END classroom_cancel_guardian_invitation_code_snippet] + } +} +// [END classroom_cancel_guardian_invitation_class] diff --git a/classroom/snippets/src/main/java/ClassroomCredentials.java b/classroom/snippets/src/main/java/ClassroomCredentials.java new file mode 100644 index 00000000..70cd5d94 --- /dev/null +++ b/classroom/snippets/src/main/java/ClassroomCredentials.java @@ -0,0 +1,64 @@ +// Copyright 2023 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 +// +// https://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. + +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.http.javanet.NetHttpTransport; +import com.google.api.client.json.JsonFactory; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.client.util.store.FileDataStoreFactory; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Collection; + +public class ClassroomCredentials { + private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); + private static final String TOKENS_DIRECTORY_PATH = "tokens"; + private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; + + /** + * Creates an authorized Credential object. + * + * @param HTTP_TRANSPORT The network HTTP Transport. + * @param SCOPES The scopes required to make the API call. + * @return An authorized Credential object. + * @throws IOException If the credentials.json file cannot be found. + */ + static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT, Collection SCOPES) + throws IOException { + // Load client secrets. + InputStream in = ClassroomCredentials.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(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH))) + .setAccessType("offline") + .build(); + + LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build(); + return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user"); + } +} diff --git a/classroom/snippets/src/main/java/CreateGuardianInvitation.java b/classroom/snippets/src/main/java/CreateGuardianInvitation.java new file mode 100644 index 00000000..cb3fe374 --- /dev/null +++ b/classroom/snippets/src/main/java/CreateGuardianInvitation.java @@ -0,0 +1,90 @@ +// Copyright 2023 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 +// +// https://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 classroom_create_guardian_invitation_class] + +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.classroom.Classroom; +import com.google.api.services.classroom.ClassroomScopes; +import com.google.api.services.classroom.model.GuardianInvitation; +import java.io.IOException; +import java.util.Collections; +import java.util.List; + +/* Class to demonstrate the use of Classroom Create Guardian Invitation API. */ +public class CreateGuardianInvitation { + /** + * Creates a guardian invitation by sending an email to the guardian for confirmation. + * + * @param studentId - the id of the student. + * @param guardianEmail - email to send the guardian invitation to. + * @return - the newly created guardian invitation. + * @throws IOException - if credentials file not found. + */ + public static GuardianInvitation createGuardianInvitation(String studentId, String guardianEmail) + throws Exception { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + final List SCOPES = + Collections.singletonList(ClassroomScopes.CLASSROOM_GUARDIANLINKS_STUDENTS); + + // Create the classroom API client + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); + + // [START classroom_create_guardian_invitation_code_snippet] + + GuardianInvitation guardianInvitation = null; + + /* Create a GuardianInvitation object with state set to PENDING. See + https://developers.google.com/classroom/reference/rest/v1/userProfiles.guardianInvitations#guardianinvitationstate + for other possible states of guardian invitations. */ + GuardianInvitation content = + new GuardianInvitation() + .setStudentId(studentId) + .setInvitedEmailAddress(guardianEmail) + .setState("PENDING"); + try { + guardianInvitation = + service.userProfiles().guardianInvitations().create(studentId, content).execute(); + + System.out.printf("Invitation created: %s\n", guardianInvitation.getInvitationId()); + } catch (GoogleJsonResponseException e) { + // TODO (developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("There is no record of studentId: %s", studentId); + } else { + throw e; + } + } catch (Exception e) { + throw e; + } + return guardianInvitation; + + // [END classroom_create_guardian_invitation_code_snippet] + } +} +// [END classroom_create_guardian_invitation_class] diff --git a/classroom/snippets/src/main/java/DeleteGuardian.java b/classroom/snippets/src/main/java/DeleteGuardian.java new file mode 100644 index 00000000..7cc67a23 --- /dev/null +++ b/classroom/snippets/src/main/java/DeleteGuardian.java @@ -0,0 +1,66 @@ +// Copyright 2023 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 +// +// https://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 classroom_delete_guardian_class] + +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.classroom.Classroom; +import com.google.api.services.classroom.ClassroomScopes; +import java.io.IOException; +import java.util.Collections; +import java.util.List; + +/* Class to demonstrate the use of Classroom Delete Guardian API. */ +public class DeleteGuardian { + /** + * Delete a guardian for a specific student. + * + * @param studentId - the id of the student the guardian belongs to. + * @param guardianId - the id of the guardian to delete. + * @throws IOException - if credentials file not found. + */ + public static void deleteGuardian(String studentId, String guardianId) throws Exception { + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + final List SCOPES = + Collections.singletonList(ClassroomScopes.CLASSROOM_GUARDIANLINKS_STUDENTS); + + // Create the classroom API client + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); + + // [START classroom_delete_guardian_code_snippet] + try { + service.userProfiles().guardians().delete(studentId, guardianId).execute(); + System.out.printf("The guardian with id %s was deleted.\n", guardianId); + } catch (GoogleJsonResponseException e) { + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("There is no record of guardianId (%s).", guardianId); + } + } + // [END classroom_delete_guardian_code_snippet] + } +} +// [END classroom_delete_guardian_class] diff --git a/classroom/snippets/src/main/java/GetGuardian.java b/classroom/snippets/src/main/java/GetGuardian.java new file mode 100644 index 00000000..781b6728 --- /dev/null +++ b/classroom/snippets/src/main/java/GetGuardian.java @@ -0,0 +1,74 @@ +// Copyright 2023 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 +// +// https://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 classroom_get_guardian_class] + +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.classroom.Classroom; +import com.google.api.services.classroom.ClassroomScopes; +import com.google.api.services.classroom.model.Guardian; +import java.io.IOException; +import java.util.Collections; +import java.util.List; + +/* Class to demonstrate the use of Classroom Get Guardian API. */ +public class GetGuardian { + /** + * Retrieve a guardian for a specific student. + * + * @param studentId - the id of the student the guardian belongs to. + * @param guardianId - the id of the guardian to delete. + * @throws IOException - if credentials file not found. + */ + public static void getGuardian(String studentId, String guardianId) throws Exception { + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + final List SCOPES = + Collections.singletonList(ClassroomScopes.CLASSROOM_GUARDIANLINKS_STUDENTS); + + // Create the classroom API client + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); + + // [START classroom_get_guardian_code_snippet] + Guardian guardian = null; + + try { + guardian = service.userProfiles().guardians().get(studentId, guardianId).execute(); + System.out.printf("Guardian retrieved: %s", guardian.getInvitedEmailAddress()); + } catch (GoogleJsonResponseException e) { + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.err.printf("There is no record of guardianId (%s).\n", guardianId); + throw e; + } else { + throw e; + } + } catch (Exception e) { + throw e; + } + // [END classroom_get_guardian_code_snippet] + } +} +// [END classroom_get_guardian_class] diff --git a/classroom/snippets/src/main/java/ListGuardianInvitationsByStudent.java b/classroom/snippets/src/main/java/ListGuardianInvitationsByStudent.java new file mode 100644 index 00000000..b565f44d --- /dev/null +++ b/classroom/snippets/src/main/java/ListGuardianInvitationsByStudent.java @@ -0,0 +1,102 @@ +// Copyright 2023 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 +// +// https://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 classroom_list_guardian_invitations_class] + +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.classroom.Classroom; +import com.google.api.services.classroom.ClassroomScopes; +import com.google.api.services.classroom.model.GuardianInvitation; +import com.google.api.services.classroom.model.ListGuardianInvitationsResponse; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/* Class to demonstrate the use of Classroom List Guardian Invitations API. */ +public class ListGuardianInvitationsByStudent { + /** + * Retrieves guardian invitations by student. + * + * @param studentId - the id of the student. + * @return a list of guardian invitations that were sent for a specific student. + * @throws IOException - if credentials file not found. + */ + public static List listGuardianInvitationsByStudent(String studentId) + throws Exception { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + final List SCOPES = + Collections.singletonList(ClassroomScopes.CLASSROOM_GUARDIANLINKS_STUDENTS); + + // Create the classroom API client + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); + + // [START classroom_list_guardian_invitations_code_snippet] + + List guardianInvitations = new ArrayList<>(); + String pageToken = null; + + try { + do { + ListGuardianInvitationsResponse response = + service + .userProfiles() + .guardianInvitations() + .list(studentId) + .setPageToken(pageToken) + .execute(); + + /* Ensure that the response is not null before retrieving data from it to avoid errors. */ + if (response.getGuardianInvitations() != null) { + guardianInvitations.addAll(response.getGuardianInvitations()); + pageToken = response.getNextPageToken(); + } + } while (pageToken != null); + + if (guardianInvitations.isEmpty()) { + System.out.println("No guardian invitations found."); + } else { + for (GuardianInvitation invitation : guardianInvitations) { + System.out.printf("Guardian invitation id: %s\n", invitation.getInvitationId()); + } + } + } catch (GoogleJsonResponseException e) { + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("There is no record of studentId (%s).", studentId); + } else { + throw e; + } + } catch (Exception e) { + throw e; + } + return guardianInvitations; + + // [END classroom_list_guardian_invitations_code_snippet] + } +} +// [END classroom_list_guardian_invitations_class] diff --git a/classroom/snippets/src/main/java/ListGuardians.java b/classroom/snippets/src/main/java/ListGuardians.java new file mode 100644 index 00000000..1cb87014 --- /dev/null +++ b/classroom/snippets/src/main/java/ListGuardians.java @@ -0,0 +1,99 @@ +// Copyright 2023 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 +// +// https://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 classroom_list_guardians_class] + +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.classroom.Classroom; +import com.google.api.services.classroom.ClassroomScopes; +import com.google.api.services.classroom.model.Guardian; +import com.google.api.services.classroom.model.ListGuardiansResponse; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/* Class to demonstrate the use of Classroom List Guardians API. */ +public class ListGuardians { + /** + * Retrieves active guardians for a specific student. + * + * @param studentId - the id of the student. + * @return a list of active guardians for a specific student. + * @throws IOException - if credentials file not found. + */ + public static List listGuardians(String studentId) throws Exception { + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + final List SCOPES = + Collections.singletonList(ClassroomScopes.CLASSROOM_GUARDIANLINKS_STUDENTS); + + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); + + // [START classroom_list_guardians_code_snippet] + + List guardians = new ArrayList<>(); + String pageToken = null; + + try { + do { + ListGuardiansResponse response = + service.userProfiles().guardians().list(studentId).setPageToken(pageToken).execute(); + + /* Ensure that the response is not null before retrieving data from it to avoid errors. */ + if (response.getGuardians() != null) { + guardians.addAll(response.getGuardians()); + pageToken = response.getNextPageToken(); + } + } while (pageToken != null); + + if (guardians.isEmpty()) { + System.out.println("No guardians found."); + } else { + for (Guardian guardian : guardians) { + System.out.printf( + "Guardian name: %s, guardian id: %s, guardian email: %s\n", + guardian.getGuardianProfile().getName().getFullName(), + guardian.getGuardianId(), + guardian.getInvitedEmailAddress()); + } + } + + } catch (GoogleJsonResponseException e) { + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("There is no record of studentId (%s).", studentId); + } else { + throw e; + } + } catch (Exception e) { + throw e; + } + return guardians; + + // [END classroom_list_guardians_code_snippet] + } +} +// [END classroom_list_guardians_class] diff --git a/classroom/snippets/src/main/java/ListStudentSubmissions.java b/classroom/snippets/src/main/java/ListStudentSubmissions.java index acc7b898..c5d8b29f 100644 --- a/classroom/snippets/src/main/java/ListStudentSubmissions.java +++ b/classroom/snippets/src/main/java/ListStudentSubmissions.java @@ -12,7 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. - // [START classroom_list_student_submissions_class] import com.google.api.client.googleapis.json.GoogleJsonError; @@ -42,22 +41,22 @@ public class ListStudentSubmissions { * @return - list of student submissions. * @throws IOException - if credentials file not found. */ - public static List listStudentSubmissions(String courseId, String courseWorkId, - String userId) throws IOException { + public static List listStudentSubmissions( + String courseId, String courseWorkId, String userId) throws IOException { /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() - .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + TODO(developer) - See https://developers.google.com/identity for + guides on implementing OAuth2 for your application. */ + GoogleCredentials credentials = + GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials); // Create the classroom API client. - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom samples") - .build(); + Classroom service = + new Classroom.Builder( + new NetHttpTransport(), GsonFactory.getDefaultInstance(), requestInitializer) + .setApplicationName("Classroom samples") + .build(); // [START classroom_list_student_submissions_code_snippet] @@ -67,10 +66,17 @@ public static List listStudentSubmissions(String courseId, St try { do { // Set the userId as a query parameter on the request. - ListStudentSubmissionsResponse response = service.courses().courseWork().studentSubmissions() - .list(courseId, courseWorkId) - .set("userId", userId) - .execute(); + ListStudentSubmissionsResponse response = + service + .courses() + .courseWork() + .studentSubmissions() + .list(courseId, courseWorkId) + .setPageToken(pageToken) + .set("userId", userId) + .execute(); + + /* Ensure that the response is not null before retrieving data from it to avoid errors. */ if (response.getStudentSubmissions() != null) { studentSubmissions.addAll(response.getStudentSubmissions()); pageToken = response.getNextPageToken(); @@ -85,11 +91,12 @@ public static List listStudentSubmissions(String courseId, St } } } catch (GoogleJsonResponseException e) { - //TODO (developer) - handle error appropriately + // TODO (developer) - handle error appropriately GoogleJsonError error = e.getDetails(); if (error.getCode() == 404) { - System.out.printf("The courseId (%s), courseWorkId (%s), or userId (%s) does " - + "not exist.\n", courseId, courseWorkId, userId); + System.out.printf( + "The courseId (%s), courseWorkId (%s), or userId (%s) does " + "not exist.\n", + courseId, courseWorkId, userId); } else { throw e; } @@ -102,4 +109,4 @@ public static List listStudentSubmissions(String courseId, St } } -// [END classroom_list_student_submissions_class] \ No newline at end of file +// [END classroom_list_student_submissions_class] diff --git a/classroom/snippets/src/main/java/ListSubmissions.java b/classroom/snippets/src/main/java/ListSubmissions.java index ed5898de..d5356d70 100644 --- a/classroom/snippets/src/main/java/ListSubmissions.java +++ b/classroom/snippets/src/main/java/ListSubmissions.java @@ -12,7 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. - // [START classroom_list_submissions_class] import com.google.api.client.googleapis.json.GoogleJsonError; @@ -44,19 +43,19 @@ public class ListSubmissions { public static List listSubmissions(String courseId, String courseWorkId) throws IOException { /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() - .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + TODO(developer) - See https://developers.google.com/identity for + guides on implementing OAuth2 for your application. */ + GoogleCredentials credentials = + GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials); // Create the classroom API client. - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom samples") - .build(); + Classroom service = + new Classroom.Builder( + new NetHttpTransport(), GsonFactory.getDefaultInstance(), requestInitializer) + .setApplicationName("Classroom samples") + .build(); // [START classroom_list_submissions_code_snippet] @@ -65,11 +64,19 @@ public static List listSubmissions(String courseId, String co try { do { - ListStudentSubmissionsResponse response = service.courses().courseWork().studentSubmissions() - .list(courseId, courseWorkId) - .execute(); + ListStudentSubmissionsResponse response = + service + .courses() + .courseWork() + .studentSubmissions() + .list(courseId, courseWorkId) + .setPageToken(pageToken) + .execute(); + + /* Ensure that the response is not null before retrieving data from it to avoid errors. */ if (response.getStudentSubmissions() != null) { studentSubmissions.addAll(response.getStudentSubmissions()); + pageToken = response.getNextPageToken(); } } while (pageToken != null); @@ -77,16 +84,17 @@ public static List listSubmissions(String courseId, String co System.out.println("No student submission found."); } else { for (StudentSubmission submission : studentSubmissions) { - System.out.printf("Student id (%s), student submission id (%s)\n", submission.getUserId(), - submission.getId()); + System.out.printf( + "Student id (%s), student submission id (%s)\n", + submission.getUserId(), submission.getId()); } } } catch (GoogleJsonResponseException e) { - //TODO (developer) - handle error appropriately + // TODO (developer) - handle error appropriately GoogleJsonError error = e.getDetails(); if (error.getCode() == 404) { - System.out.printf("The courseId (%s) or courseWorkId (%s) does not exist.\n", courseId, - courseWorkId); + System.out.printf( + "The courseId (%s) or courseWorkId (%s) does not exist.\n", courseId, courseWorkId); } else { throw e; } @@ -99,4 +107,4 @@ public static List listSubmissions(String courseId, String co } } -// [END classroom_list_submissions_class] \ No newline at end of file +// [END classroom_list_submissions_class] diff --git a/classroom/snippets/src/main/java/ListTopics.java b/classroom/snippets/src/main/java/ListTopics.java index e754f82b..6412a1cb 100644 --- a/classroom/snippets/src/main/java/ListTopics.java +++ b/classroom/snippets/src/main/java/ListTopics.java @@ -12,7 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. - // [START classroom_list_topic_class] import com.google.api.client.googleapis.json.GoogleJsonError; @@ -42,19 +41,19 @@ public class ListTopics { */ public static List listTopics(String courseId) throws IOException { /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() - .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_TOPICS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + TODO(developer) - See https://developers.google.com/identity for + guides on implementing OAuth2 for your application. */ + GoogleCredentials credentials = + GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_TOPICS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials); // Create the classroom API client. - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom samples") - .build(); + Classroom service = + new Classroom.Builder( + new NetHttpTransport(), GsonFactory.getDefaultInstance(), requestInitializer) + .setApplicationName("Classroom samples") + .build(); // [START classroom_list_topic_code_snippet] @@ -63,10 +62,16 @@ public static List listTopics(String courseId) throws IOException { try { do { - ListTopicResponse response = service.courses().topics().list(courseId) - .setPageSize(100) - .setPageToken(pageToken) - .execute(); + ListTopicResponse response = + service + .courses() + .topics() + .list(courseId) + .setPageSize(100) + .setPageToken(pageToken) + .execute(); + + /* Ensure that the response is not null before retrieving data from it to avoid errors. */ if (response.getTopic() != null) { topics.addAll(response.getTopic()); pageToken = response.getNextPageToken(); @@ -81,7 +86,7 @@ public static List listTopics(String courseId) throws IOException { } } } catch (GoogleJsonResponseException e) { - //TODO (developer) - handle error appropriately + // TODO (developer) - handle error appropriately GoogleJsonError error = e.getDetails(); if (error.getCode() == 404) { System.out.printf("The courseId does not exist: %s.\n", courseId); diff --git a/classroom/snippets/src/test/java/BaseTest.java b/classroom/snippets/src/test/java/BaseTest.java index cc3996de..b0c5286e 100644 --- a/classroom/snippets/src/test/java/BaseTest.java +++ b/classroom/snippets/src/test/java/BaseTest.java @@ -1,28 +1,26 @@ -/* - * Copyright 2022 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. - */ +// Copyright 2022 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 +// +// https://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. -import com.google.api.client.http.HttpRequestInitializer; +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.classroom.Classroom; import com.google.api.services.classroom.ClassroomScopes; import com.google.api.services.classroom.model.Course; import com.google.api.services.classroom.model.CourseAlias; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.auth.oauth2.GoogleCredentials; +import java.util.Collections; +import java.util.List; import org.junit.After; import org.junit.Before; @@ -40,27 +38,24 @@ public class BaseTest { * @return an authorized Classroom client service * @throws IOException - if credentials file not found. */ - protected Classroom buildService() throws IOException { - /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() - .createScoped(ClassroomScopes.CLASSROOM_ROSTERS); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + protected Classroom buildService() throws Exception { + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + final List SCOPES = Collections.singletonList(ClassroomScopes.CLASSROOM_COURSES); // Create the classroom API client - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom Snippets") - .build(); - - return service; + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + return service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); } @Before - public void setup() throws IOException { + public void setup() throws Exception { this.service = buildService(); this.testCourse = CreateCourse.createCourse(); createAlias(this.testCourse.getId()); @@ -72,11 +67,10 @@ public void tearDown() throws IOException { this.testCourse = null; } - public CourseAlias createAlias(String courseId) throws IOException { + public void createAlias(String courseId) throws IOException { String alias = "p:" + UUID.randomUUID(); CourseAlias courseAlias = new CourseAlias().setAlias(alias); - courseAlias = this.service.courses().aliases().create(courseId, courseAlias).execute(); - return courseAlias; + this.service.courses().aliases().create(courseId, courseAlias).execute(); } public void deleteCourse(String courseId) throws IOException { diff --git a/classroom/snippets/src/test/java/TestCancelGuardianInvitation.java b/classroom/snippets/src/test/java/TestCancelGuardianInvitation.java new file mode 100644 index 00000000..d5ad35b4 --- /dev/null +++ b/classroom/snippets/src/test/java/TestCancelGuardianInvitation.java @@ -0,0 +1,37 @@ +// Copyright 2023 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 +// +// https://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. + +import com.google.api.services.classroom.model.GuardianInvitation; +import org.junit.Assert; +import org.junit.Test; + +// Unit test class for Cancel Guardian Invitation classroom snippet +public class TestCancelGuardianInvitation { + + @Test + public void testCancelGuardianInvitation() throws Exception { + String studentId = "insert_student_id"; + String guardianEmail = "insert_guardian_email"; + + GuardianInvitation invitation = + CreateGuardianInvitation.createGuardianInvitation(studentId, guardianEmail); + + GuardianInvitation guardianInvitation = + CancelGuardianInvitation.cancelGuardianInvitation(studentId, invitation.getInvitationId()); + + Assert.assertTrue("Guardian invitation not canceled.", guardianInvitation != null); + Assert.assertTrue( + "Guardian invitation state not updated.", guardianInvitation.getState().equals("COMPLETE")); + } +} diff --git a/classroom/snippets/src/test/java/TestCreateGuardianInvitation.java b/classroom/snippets/src/test/java/TestCreateGuardianInvitation.java new file mode 100644 index 00000000..bc98e2b9 --- /dev/null +++ b/classroom/snippets/src/test/java/TestCreateGuardianInvitation.java @@ -0,0 +1,31 @@ +// Copyright 2023 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 +// +// https://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. + +import com.google.api.services.classroom.model.GuardianInvitation; +import org.junit.Assert; +import org.junit.Test; + +// Unit test class for Create Guardian Invitation classroom snippet +public class TestCreateGuardianInvitation { + + @Test + public void testCreateGuardianInvitation() throws Exception { + String studentId = "insert_student_id"; + String guardianEmail = "insert_guardian_email"; + GuardianInvitation guardianInvitation = + CreateGuardianInvitation.createGuardianInvitation(studentId, guardianEmail); + + Assert.assertTrue("Guardian invitation not created.", guardianInvitation != null); + } +} diff --git a/classroom/snippets/src/test/java/TestDeleteGuardian.java b/classroom/snippets/src/test/java/TestDeleteGuardian.java new file mode 100644 index 00000000..fc70bd08 --- /dev/null +++ b/classroom/snippets/src/test/java/TestDeleteGuardian.java @@ -0,0 +1,31 @@ +// Copyright 2023 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 +// +// https://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. + +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import org.junit.Assert; +import org.junit.Test; + +// Unit test class for Delete Guardian classroom snippet +public class TestDeleteGuardian { + + @Test + public void testDeleteGuardian() throws Exception { + String studentId = "insert_student_id"; + String guardianId = "insert_guardian_id"; + DeleteGuardian.deleteGuardian(studentId, guardianId); + + Assert.assertThrows( + GoogleJsonResponseException.class, () -> GetGuardian.getGuardian(studentId, guardianId)); + } +} diff --git a/classroom/snippets/src/test/java/TestListGuardianInvitationsByStudent.java b/classroom/snippets/src/test/java/TestListGuardianInvitationsByStudent.java new file mode 100644 index 00000000..0ee3390f --- /dev/null +++ b/classroom/snippets/src/test/java/TestListGuardianInvitationsByStudent.java @@ -0,0 +1,31 @@ +// Copyright 2023 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 +// +// https://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. + +import com.google.api.services.classroom.model.GuardianInvitation; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; + +// Unit test class for List Guardian Invitations classroom snippet +public class TestListGuardianInvitationsByStudent { + + @Test + public void testListGuardianInvitationsByStudent() throws Exception { + String studentId = "insert_student_id"; + List invitationList = + ListGuardianInvitationsByStudent.listGuardianInvitationsByStudent(studentId); + + Assert.assertTrue("No guardian invitations returned.", invitationList.size() > 0); + } +} diff --git a/classroom/snippets/src/test/java/TestListGuardians.java b/classroom/snippets/src/test/java/TestListGuardians.java new file mode 100644 index 00000000..b1b5eb03 --- /dev/null +++ b/classroom/snippets/src/test/java/TestListGuardians.java @@ -0,0 +1,30 @@ +// Copyright 2023 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 +// +// https://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. + +import com.google.api.services.classroom.model.Guardian; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; + +// Unit test class for List Guardians classroom snippet +public class TestListGuardians { + + @Test + public void testListGuardians() throws Exception { + String studentId = "insert_student_id"; + List guardianList = ListGuardians.listGuardians(studentId); + + Assert.assertTrue("No guardians returned.", guardianList.size() > 0); + } +} From 079711b1913ae92f56764716b923a56e7c6b1cdd Mon Sep 17 00:00:00 2001 From: Mahima Desetty <45216855+mahima-desetty@users.noreply.github.com> Date: Tue, 28 Feb 2023 12:38:30 -0500 Subject: [PATCH 04/19] feat: updating authorization flow & added invitation resource Classroom code snippets. (#601) * add alias snippet and unit test * java snippets for topics, create coursework, create alias * updates based on team review * renamed alias methods, added devsite comments * added missing license header to TestDeleteTopic.java * Adding List, ModifyAttachments, Patch, Return StudentSubmission methods * minor fixes * adding comments for developer * modifications based on team review * modifications based on team review * Adding print statements and devsite tag to ListCourseAliases * added class templates for guardians and guardianInvitations * guardian and guardian invitation implementation * tests for list guardians and list guardian invitations * adding tests for guardians and guardian invites. removing use of ADC for auth. * base test updates * updates based on team feedback * fixing BaseTest.java * updating copyright year to 2023 for new files * testing google-java-format plugin to fix lint errors * updated files after running google-java-format plugin * updated BaseTest * fixing copyright header for BaseTest * updated auth for AddAlias and CreateCourse classes * removing unused imports * Fixing comment. * specifying errors in method signatures * updated BaseTest and AddStudent * Adding annotation for GeneralSecurityException * updating AddStudent method signature and test * updated AddTeacher and AddStudent test * updated auth for BatchAddStudents * updated auth for CreateCourseWork * updated auth for Topic related classes and tests * added link to CourseState info and updated GetTopic error handling * updated auth for remaining classes * updated auth for CreateCourseWithAlias * CreateInvitation code snippet * accept, create, delete invitation classes * list invitations class * listAssignedGrades method in ListStudentSubmissions class * deleting ListInvitations classes until bug is fixed * team review updates * google java format for tests * google-java-format on classes * google java format DeleteTopic * added test cases to CreateInvitation and DeleteInvitation classes * additional comment in accept invitation test case * fixing java formatting * google java format fix --- .../src/main/java/AcceptInvitation.java | 72 ++++++++++++++ .../src/main/java/AddAliasToCourse.java | 46 ++++----- .../snippets/src/main/java/AddStudent.java | 61 ++++++------ .../snippets/src/main/java/AddTeacher.java | 47 ++++----- .../src/main/java/BatchAddStudents.java | 64 ++++++------ .../snippets/src/main/java/CreateCourse.java | 67 +++++++------ .../src/main/java/CreateCourseWithAlias.java | 56 ++++++----- .../src/main/java/CreateCourseWork.java | 70 ++++++------- .../src/main/java/CreateInvitation.java | 89 +++++++++++++++++ .../snippets/src/main/java/CreateTopic.java | 40 ++++---- .../src/main/java/DeleteInvitation.java | 72 ++++++++++++++ .../snippets/src/main/java/DeleteTopic.java | 47 +++++---- .../snippets/src/main/java/GetCourse.java | 42 ++++---- .../snippets/src/main/java/GetInvitation.java | 76 +++++++++++++++ .../snippets/src/main/java/GetTopic.java | 44 +++++---- .../src/main/java/ListCourseAliases.java | 53 +++++----- .../snippets/src/main/java/ListCourses.java | 48 +++++---- .../src/main/java/ListStudentSubmissions.java | 97 ++++++++++++++++--- .../src/main/java/ListSubmissions.java | 27 +++--- .../snippets/src/main/java/ListTopics.java | 29 +++--- .../ModifyAttachmentsStudentSubmission.java | 69 +++++++------ .../snippets/src/main/java/PatchCourse.java | 51 +++++----- .../src/main/java/PatchStudentSubmission.java | 78 ++++++++------- .../main/java/ReturnStudentSubmission.java | 53 +++++----- .../snippets/src/main/java/UpdateCourse.java | 41 ++++---- .../snippets/src/main/java/UpdateTopic.java | 52 +++++----- .../snippets/src/test/java/BaseTest.java | 22 ++--- .../src/test/java/TestAcceptInvitation.java | 39 ++++++++ .../src/test/java/TestAddAliasToCourse.java | 13 +-- .../src/test/java/TestAddStudent.java | 22 +++-- .../src/test/java/TestAddTeacher.java | 18 ++-- .../src/test/java/TestBatchAddStudents.java | 11 ++- .../src/test/java/TestCreateCourse.java | 7 +- .../test/java/TestCreateCourseWithAlias.java | 12 +-- .../src/test/java/TestCreateCourseWork.java | 5 +- .../src/test/java/TestCreateInvitation.java | 43 ++++++++ .../src/test/java/TestCreateTopic.java | 4 +- .../src/test/java/TestDeleteInvitation.java | 42 ++++++++ .../src/test/java/TestDeleteTopic.java | 8 +- .../snippets/src/test/java/TestGetCourse.java | 6 +- .../snippets/src/test/java/TestGetTopic.java | 4 +- .../src/test/java/TestListCourseAliases.java | 10 +- .../src/test/java/TestListCourses.java | 7 +- .../src/test/java/TestListSubmissions.java | 8 +- .../src/test/java/TestListTopics.java | 4 +- .../src/test/java/TestPatchCourse.java | 6 +- .../src/test/java/TestUpdateCourse.java | 6 +- .../src/test/java/TestUpdateTopic.java | 6 +- 48 files changed, 1200 insertions(+), 594 deletions(-) create mode 100644 classroom/snippets/src/main/java/AcceptInvitation.java create mode 100644 classroom/snippets/src/main/java/CreateInvitation.java create mode 100644 classroom/snippets/src/main/java/DeleteInvitation.java create mode 100644 classroom/snippets/src/main/java/GetInvitation.java create mode 100644 classroom/snippets/src/test/java/TestAcceptInvitation.java create mode 100644 classroom/snippets/src/test/java/TestCreateInvitation.java create mode 100644 classroom/snippets/src/test/java/TestDeleteInvitation.java diff --git a/classroom/snippets/src/main/java/AcceptInvitation.java b/classroom/snippets/src/main/java/AcceptInvitation.java new file mode 100644 index 00000000..137a23a0 --- /dev/null +++ b/classroom/snippets/src/main/java/AcceptInvitation.java @@ -0,0 +1,72 @@ +// Copyright 2023 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 +// +// https://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 classroom_accept_invitation] + +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.classroom.Classroom; +import com.google.api.services.classroom.ClassroomScopes; +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; + +/* Class to demonstrate the use of Classroom Accept Invitation API. */ +public class AcceptInvitation { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_ROSTERS)); + + /** + * Accepts an invitation to a course. + * + * @param id - the identifier of the invitation to accept. + * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. + */ + public static void acceptInvitation(String id) throws GeneralSecurityException, IOException { + + // Create the classroom API client. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); + + // [START classroom_accept_invitation_code_snippet] + try { + service.invitations().accept(id).execute(); + System.out.printf("Invitation (%s) was accepted.\n", id); + } catch (GoogleJsonResponseException e) { + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("The invitation id (%s) does not exist.\n", id); + } + throw e; + } catch (Exception e) { + throw e; + } + // [END classroom_accept_invitation_code_snippet] + } +} +// [END classroom_accept_invitation] diff --git a/classroom/snippets/src/main/java/AddAliasToCourse.java b/classroom/snippets/src/main/java/AddAliasToCourse.java index 10434391..720dccec 100644 --- a/classroom/snippets/src/main/java/AddAliasToCourse.java +++ b/classroom/snippets/src/main/java/AddAliasToCourse.java @@ -12,61 +12,61 @@ // See the License for the specific language governing permissions and // limitations under the License. - // [START classroom_add_alias_to_course_class] +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.classroom.Classroom; import com.google.api.services.classroom.ClassroomScopes; import com.google.api.services.classroom.model.CourseAlias; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; -import java.util.Collections; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; /* Class to demonstrate the use of Classroom Create Alias API. */ public class AddAliasToCourse { + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_COURSES)); + /** * Add an alias on an existing course. * * @param courseId - id of the course to add an alias to. * @return - newly created course alias. * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. */ - public static CourseAlias addAliasToCourse(String courseId) throws IOException { - /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() - .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSES)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + public static CourseAlias addAliasToCourse(String courseId) + throws GeneralSecurityException, IOException { // Create the classroom API client. - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom samples") - .build(); + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); // [START classroom_add_alias_to_course_code_snippet] /* Create a new CourseAlias object with a project-wide alias. Project-wide aliases use a prefix of "p:" and can only be seen and used by the application that created them. */ - CourseAlias content = new CourseAlias() - .setAlias("p:biology_10"); + CourseAlias content = new CourseAlias().setAlias("p:biology_10"); CourseAlias courseAlias = null; try { - courseAlias = service.courses().aliases().create(courseId, content) - .execute(); + courseAlias = service.courses().aliases().create(courseId, content).execute(); System.out.printf("Course alias created: %s \n", courseAlias.getAlias()); } catch (GoogleJsonResponseException e) { - //TODO (developer) - handle error appropriately + // TODO (developer) - handle error appropriately GoogleJsonError error = e.getDetails(); if (error.getCode() == 409) { System.out.printf("The course alias already exists: %s.\n", content); diff --git a/classroom/snippets/src/main/java/AddStudent.java b/classroom/snippets/src/main/java/AddStudent.java index c04c38fb..6331f3ed 100644 --- a/classroom/snippets/src/main/java/AddStudent.java +++ b/classroom/snippets/src/main/java/AddStudent.java @@ -12,57 +12,64 @@ // See the License for the specific language governing permissions and // limitations under the License. - // [START classroom_add_student] +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.classroom.Classroom; import com.google.api.services.classroom.ClassroomScopes; import com.google.api.services.classroom.model.Student; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; -import java.util.Collections; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; /* Class to demonstrate the use of Classroom Add Student API */ public class AddStudent { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_ROSTERS)); + /** * Add a student in a specified course. * - * @param courseId - Id of the course. + * @param courseId - Id of the course. * @param enrollmentCode - Code of the course to enroll. * @return newly added student * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. */ - public static Student addStudent(String courseId, String enrollmentCode) - throws IOException { - /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() - .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_ROSTERS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + public static Student addStudent(String courseId, String enrollmentCode, String studentId) + throws GeneralSecurityException, IOException { - // Create the classroom API client - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom samples") - .build(); + // Create the classroom API client. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); - Student student = new Student().setUserId("gduser1@workspacesamples.dev"); + Student student = new Student().setUserId(studentId); try { // Enrolling a student to a specified course - student = service.courses().students().create(courseId, student) - .setEnrollmentCode(enrollmentCode) - .execute(); + student = + service + .courses() + .students() + .create(courseId, student) + .setEnrollmentCode(enrollmentCode) + .execute(); // Prints the course id with the Student name - System.out.printf("User '%s' was enrolled as a student in the course with ID '%s'.\n", + System.out.printf( + "User '%s' was enrolled as a student in the course with ID '%s'.\n", student.getProfile().getName().getFullName(), courseId); } catch (GoogleJsonResponseException e) { // TODO(developer) - handle error appropriately @@ -78,4 +85,4 @@ public static Student addStudent(String courseId, String enrollmentCode) return student; } } -// [END classroom_add_student] \ No newline at end of file +// [END classroom_add_student] diff --git a/classroom/snippets/src/main/java/AddTeacher.java b/classroom/snippets/src/main/java/AddTeacher.java index 9f5652e3..4c843721 100644 --- a/classroom/snippets/src/main/java/AddTeacher.java +++ b/classroom/snippets/src/main/java/AddTeacher.java @@ -12,55 +12,58 @@ // See the License for the specific language governing permissions and // limitations under the License. - // [START classroom_add_teacher] +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.classroom.Classroom; import com.google.api.services.classroom.ClassroomScopes; import com.google.api.services.classroom.model.Teacher; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; -import java.util.Collections; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; /* Class to demonstrate the use of Classroom Add Teacher API */ public class AddTeacher { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_ROSTERS)); + /** * Add teacher to a specific course. * - * @param courseId - Id of the course. + * @param courseId - Id of the course. * @param teacherEmail - Email address of the teacher. * @return newly created teacher * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. */ public static Teacher addTeacher(String courseId, String teacherEmail) - throws IOException { - /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() - .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_ROSTERS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + throws GeneralSecurityException, IOException { - // Create the classroom API client - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom samples") - .build(); + // Create the classroom API client. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); Teacher teacher = new Teacher().setUserId(teacherEmail); try { // Add a teacher to a specified course teacher = service.courses().teachers().create(courseId, teacher).execute(); // Prints the course id with the teacher name - System.out.printf("User '%s' was added as a teacher to the course with ID '%s'.\n", + System.out.printf( + "User '%s' was added as a teacher to the course with ID '%s'.\n", teacher.getProfile().getName().getFullName(), courseId); } catch (GoogleJsonResponseException e) { // TODO(developer) - handle error appropriately @@ -76,4 +79,4 @@ public static Teacher addTeacher(String courseId, String teacherEmail) return teacher; } } -// [END classroom_add_teacher] \ No newline at end of file +// [END classroom_add_teacher] diff --git a/classroom/snippets/src/main/java/BatchAddStudents.java b/classroom/snippets/src/main/java/BatchAddStudents.java index 9588ec3d..d4a54c2e 100644 --- a/classroom/snippets/src/main/java/BatchAddStudents.java +++ b/classroom/snippets/src/main/java/BatchAddStudents.java @@ -12,62 +12,66 @@ // See the License for the specific language governing permissions and // limitations under the License. - // [START classroom_batch_add_students] import com.google.api.client.googleapis.batch.BatchRequest; import com.google.api.client.googleapis.batch.json.JsonBatchCallback; +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.http.HttpHeaders; -import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.classroom.Classroom; import com.google.api.services.classroom.ClassroomScopes; import com.google.api.services.classroom.model.Student; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; -import java.util.Collections; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; import java.util.List; /* Class to demonstrate the use of Classroom Batch Add Students API */ public class BatchAddStudents { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_ROSTERS)); + /** * Add multiple students in a specified course. * - * @param courseId - Id of the course to add students. + * @param courseId - Id of the course to add students. * @param studentEmails - Email address of the students. * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. */ public static void batchAddStudents(String courseId, List studentEmails) - throws IOException { - /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() - .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_ROSTERS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + throws GeneralSecurityException, IOException { - // Create the classroom API client - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom samples") - .build(); + // Create the classroom API client. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); BatchRequest batch = service.batch(); - JsonBatchCallback callback = new JsonBatchCallback<>() { - public void onSuccess(Student student, HttpHeaders responseHeaders) { - System.out.printf("User '%s' was added as a student to the course.\n", - student.getProfile().getName().getFullName()); - } + JsonBatchCallback callback = + new JsonBatchCallback<>() { + public void onSuccess(Student student, HttpHeaders responseHeaders) { + System.out.printf( + "User '%s' was added as a student to the course.\n", + student.getProfile().getName().getFullName()); + } - public void onFailure(GoogleJsonError error, HttpHeaders responseHeaders) { - System.out.printf("Error adding student to the course: %s\n", error.getMessage()); - } - }; + public void onFailure(GoogleJsonError error, HttpHeaders responseHeaders) { + System.out.printf("Error adding student to the course: %s\n", error.getMessage()); + } + }; for (String studentEmail : studentEmails) { Student student = new Student().setUserId(studentEmail); service.courses().students().create(courseId, student).queue(batch, callback); @@ -75,4 +79,4 @@ public void onFailure(GoogleJsonError error, HttpHeaders responseHeaders) { batch.execute(); } } -// [END classroom_batch_add_students] \ No newline at end of file +// [END classroom_batch_add_students] diff --git a/classroom/snippets/src/main/java/CreateCourse.java b/classroom/snippets/src/main/java/CreateCourse.java index ce33dd4d..95f7353c 100644 --- a/classroom/snippets/src/main/java/CreateCourse.java +++ b/classroom/snippets/src/main/java/CreateCourse.java @@ -12,59 +12,64 @@ // See the License for the specific language governing permissions and // limitations under the License. - // [START classroom_create_course] +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.classroom.Classroom; import com.google.api.services.classroom.ClassroomScopes; import com.google.api.services.classroom.model.Course; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; -import java.util.Collections; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; /* Class to demonstrate the use of Classroom Create Course API */ public class CreateCourse { + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_COURSES)); + /** * Creates a course * * @return newly created course * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. */ - public static Course createCourse() throws IOException { - /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() - .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSES)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + public static Course createCourse() throws GeneralSecurityException, IOException { - // Create the classroom API client - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom samples") - .build(); + // Create the classroom API client. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); Course course = null; try { - // Adding a new course with description - course = new Course() - .setName("10th Grade Biology") - .setSection("Period 2") - .setDescriptionHeading("Welcome to 10th Grade Biology") - .setDescription("We'll be learning about about the structure of living creatures " - + "from a combination of textbooks, guest lectures, and lab work. Expect " - + "to be excited!") - .setRoom("301") - .setOwnerId("me") - .setCourseState("PROVISIONED"); + // Adding a new course with description. Set CourseState to `ACTIVE`. Possible values of + // CourseState can be found here: + // https://developers.google.com/classroom/reference/rest/v1/courses#coursestate + course = + new Course() + .setName("10th Grade Biology") + .setSection("Period 2") + .setDescriptionHeading("Welcome to 10th Grade Biology") + .setDescription( + "We'll be learning about about the structure of living creatures " + + "from a combination of textbooks, guest lectures, and lab work. Expect " + + "to be excited!") + .setRoom("301") + .setOwnerId("me") + .setCourseState("ACTIVE"); course = service.courses().create(course).execute(); // Prints the new created course Id and name System.out.printf("Course created: %s (%s)\n", course.getName(), course.getId()); @@ -79,4 +84,4 @@ public static Course createCourse() throws IOException { return course; } } -// [END classroom_create_course] \ No newline at end of file +// [END classroom_create_course] diff --git a/classroom/snippets/src/main/java/CreateCourseWithAlias.java b/classroom/snippets/src/main/java/CreateCourseWithAlias.java index 77a6521b..c676b973 100644 --- a/classroom/snippets/src/main/java/CreateCourseWithAlias.java +++ b/classroom/snippets/src/main/java/CreateCourseWithAlias.java @@ -12,44 +12,47 @@ // See the License for the specific language governing permissions and // limitations under the License. - // [START classroom_create_course_with_alias_class] + +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.classroom.Classroom; import com.google.api.services.classroom.ClassroomScopes; import com.google.api.services.classroom.model.Course; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; -import java.util.Collections; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; /* Class to demonstrate how to create a course with an alias. */ public class CreateCourseWithAlias { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_COURSES)); + /** * Create a new course with an alias. Set the new course id to the desired alias. * * @return - newly created course. * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. */ - public static Course createCourseWithAlias() throws IOException { - /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() - .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSES)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + public static Course createCourseWithAlias() throws GeneralSecurityException, IOException { // Create the classroom API client. - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom samples") - .build(); + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); // [START classroom_create_course_with_alias_code_snippet] @@ -57,20 +60,21 @@ public static Course createCourseWithAlias() throws IOException { /* Create a new Course with the alias set as the id field. Project-wide aliases use a prefix of "p:" and can only be seen and used by the application that created them. */ - Course content = new Course() - .setId("p:history_4_2022") - .setName("9th Grade History") - .setSection("Period 4") - .setDescriptionHeading("Welcome to 9th Grade History.") - .setOwnerId("me") - .setCourseState("PROVISIONED"); + Course content = + new Course() + .setId("p:history_4_2022") + .setName("9th Grade History") + .setSection("Period 4") + .setDescriptionHeading("Welcome to 9th Grade History.") + .setOwnerId("me") + .setCourseState("PROVISIONED"); try { course = service.courses().create(content).execute(); // Prints the new created course id and name System.out.printf("Course created: %s (%s)\n", course.getName(), course.getId()); } catch (GoogleJsonResponseException e) { - //TODO (developer) - handle error appropriately + // TODO (developer) - handle error appropriately GoogleJsonError error = e.getDetails(); if (error.getCode() == 409) { System.out.printf("The course alias already exists: %s.\n", content.getId()); diff --git a/classroom/snippets/src/main/java/CreateCourseWork.java b/classroom/snippets/src/main/java/CreateCourseWork.java index 7f9973ca..5d6c948d 100644 --- a/classroom/snippets/src/main/java/CreateCourseWork.java +++ b/classroom/snippets/src/main/java/CreateCourseWork.java @@ -12,60 +12,61 @@ // See the License for the specific language governing permissions and // limitations under the License. - // [START classroom_create_coursework_class] +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.classroom.Classroom; import com.google.api.services.classroom.ClassroomScopes; import com.google.api.services.classroom.model.CourseWork; -import com.google.api.services.classroom.model.Date; import com.google.api.services.classroom.model.Link; import com.google.api.services.classroom.model.Material; -import com.google.api.services.classroom.model.TimeOfDay; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.List; /* Class to demonstrate the use of Classroom Create CourseWork API. */ public class CreateCourseWork { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS)); + /** * Creates course work. * * @param courseId - id of the course to create coursework in. * @return - newly created CourseWork object. * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. */ - public static CourseWork createCourseWork(String courseId) throws IOException { - /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() - .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + public static CourseWork createCourseWork(String courseId) + throws GeneralSecurityException, IOException { // Create the classroom API client. - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom samples") - .build(); + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); // [START classroom_create_coursework_code_snippet] CourseWork courseWork = null; try { // Create a link to add as a material on course work. - Link articleLink = new Link() - .setTitle("SR-71 Blackbird") - .setUrl("https://www.lockheedmartin.com/en-us/news/features/history/blackbird.html"); + Link articleLink = + new Link() + .setTitle("SR-71 Blackbird") + .setUrl("https://www.lockheedmartin.com/en-us/news/features/history/blackbird.html"); // Create a list of Materials to add to course work. List materials = Arrays.asList(new Material().setLink(articleLink)); @@ -75,21 +76,22 @@ public static CourseWork createCourseWork(String courseId) throws IOException { https://developers.google.com/classroom/reference/rest/v1/CourseWorkType Set state to `PUBLISHED`. Possible values of state can be found here: https://developers.google.com/classroom/reference/rest/v1/courses.courseWork#courseworkstate */ - CourseWork content = new CourseWork() - .setTitle("Supersonic aviation") - .setDescription("Read about how the SR-71 Blackbird, the world’s fastest and " - + "highest-flying manned aircraft, was built.") - .setMaterials(materials) - .setWorkType("ASSIGNMENT") - .setState("PUBLISHED"); + CourseWork content = + new CourseWork() + .setTitle("Supersonic aviation") + .setDescription( + "Read about how the SR-71 Blackbird, the world’s fastest and " + + "highest-flying manned aircraft, was built.") + .setMaterials(materials) + .setWorkType("ASSIGNMENT") + .setState("PUBLISHED"); - courseWork = service.courses().courseWork().create(courseId, content) - .execute(); + courseWork = service.courses().courseWork().create(courseId, content).execute(); /* Prints the created courseWork. */ System.out.printf("CourseWork created: %s\n", courseWork.getTitle()); } catch (GoogleJsonResponseException e) { - //TODO (developer) - handle error appropriately + // TODO (developer) - handle error appropriately GoogleJsonError error = e.getDetails(); if (error.getCode() == 404) { System.out.printf("The courseId does not exist: %s.\n", courseId); @@ -105,4 +107,4 @@ public static CourseWork createCourseWork(String courseId) throws IOException { // [END classroom_create_coursework_code_snippet] } } -// [END classroom_create_coursework_class] \ No newline at end of file +// [END classroom_create_coursework_class] diff --git a/classroom/snippets/src/main/java/CreateInvitation.java b/classroom/snippets/src/main/java/CreateInvitation.java new file mode 100644 index 00000000..3e3d22ac --- /dev/null +++ b/classroom/snippets/src/main/java/CreateInvitation.java @@ -0,0 +1,89 @@ +// Copyright 2023 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 +// +// https://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 classroom_create_invitation] + +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.classroom.Classroom; +import com.google.api.services.classroom.ClassroomScopes; +import com.google.api.services.classroom.model.Invitation; +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; + +/* Class to demonstrate the use of Classroom Create Invitation API. */ +public class CreateInvitation { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_ROSTERS)); + + /** + * Create an invitation to allow a user to join a course. + * + * @param courseId - the course to invite the user to. + * @param userId - the user to be invited to the course. + * @return the created invitation. + * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. + */ + public static Invitation createInvitation(String courseId, String userId) + throws GeneralSecurityException, IOException { + + // Create the classroom API client. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); + + // [START classroom_create_invitation_code_snippet] + + Invitation invitation = null; + try { + /* Set the role the user is invited to have in the course. Possible values of CourseRole can be + found here: https://developers.google.com/classroom/reference/rest/v1/invitations#courserole.*/ + Invitation content = + new Invitation().setCourseId(courseId).setUserId(userId).setRole("TEACHER"); + + invitation = service.invitations().create(content).execute(); + + System.out.printf( + "User (%s) has been invited to course (%s).\n", + invitation.getUserId(), invitation.getCourseId()); + } catch (GoogleJsonResponseException e) { + // TODO (developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("The course or user does not exist.\n"); + } + throw e; + } catch (Exception e) { + throw e; + } + return invitation; + + // [END classroom_create_invitation_code_snippet] + } +} +// [END classroom_create_invitation] diff --git a/classroom/snippets/src/main/java/CreateTopic.java b/classroom/snippets/src/main/java/CreateTopic.java index a46e573f..1be964a3 100644 --- a/classroom/snippets/src/main/java/CreateTopic.java +++ b/classroom/snippets/src/main/java/CreateTopic.java @@ -12,46 +12,48 @@ // See the License for the specific language governing permissions and // limitations under the License. - // [START classroom_create_topic_class] +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.classroom.Classroom; import com.google.api.services.classroom.ClassroomScopes; import com.google.api.services.classroom.model.Topic; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; -import java.util.Collections; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; /* Class to demonstrate how to create a topic. */ public class CreateTopic { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_TOPICS)); + /** * Create a new topic in a course. * * @param courseId - the id of the course to create a topic in. * @return - newly created topic. * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. */ - public static Topic createTopic(String courseId) throws IOException { - /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() - .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_TOPICS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + public static Topic createTopic(String courseId) throws GeneralSecurityException, IOException { // Create the classroom API client. - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom samples") - .build(); + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); // [START classroom_create_topic_code_snippet] @@ -62,7 +64,7 @@ public static Topic createTopic(String courseId) throws IOException { topic = service.courses().topics().create(courseId, content).execute(); System.out.println("Topic id: " + topic.getTopicId() + "\n" + "Course id: " + courseId); } catch (GoogleJsonResponseException e) { - //TODO (developer) - handle error appropriately + // TODO (developer) - handle error appropriately GoogleJsonError error = e.getDetails(); if (error.getCode() == 404) { System.out.printf("The courseId does not exist: %s.\n", courseId); diff --git a/classroom/snippets/src/main/java/DeleteInvitation.java b/classroom/snippets/src/main/java/DeleteInvitation.java new file mode 100644 index 00000000..eca59e92 --- /dev/null +++ b/classroom/snippets/src/main/java/DeleteInvitation.java @@ -0,0 +1,72 @@ +// Copyright 2023 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 +// +// https://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 classroom_delete_invitation] + +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.classroom.Classroom; +import com.google.api.services.classroom.ClassroomScopes; +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; + +/* Class to demonstrate the use of Classroom Delete Invitation API. */ +public class DeleteInvitation { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_ROSTERS)); + + /** + * Deletes an invitation. + * + * @param id - the identifier of the invitation to delete. + * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. + */ + public static void deleteInvitation(String id) throws GeneralSecurityException, IOException { + + // Create the classroom API client. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); + + // [START classroom_delete_invitation_code_snippet] + try { + service.invitations().delete(id).execute(); + System.out.printf("Invitation (%s) was deleted.\n", id); + } catch (GoogleJsonResponseException e) { + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("The invitation id (%s) does not exist.\n", id); + } + throw e; + } catch (Exception e) { + throw e; + } + // [END classroom_delete_invitation_code_snippet] + } +} +// [END classroom_delete_invitation] diff --git a/classroom/snippets/src/main/java/DeleteTopic.java b/classroom/snippets/src/main/java/DeleteTopic.java index b8ee8f73..15188de6 100644 --- a/classroom/snippets/src/main/java/DeleteTopic.java +++ b/classroom/snippets/src/main/java/DeleteTopic.java @@ -12,23 +12,27 @@ // See the License for the specific language governing permissions and // limitations under the License. - // [START classroom_delete_topic_class] -import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.classroom.Classroom; import com.google.api.services.classroom.ClassroomScopes; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; -import java.util.Collections; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; /* Class to demonstrate how to delete a topic. */ public class DeleteTopic { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_TOPICS)); + /** * Delete a topic in a course. * @@ -36,22 +40,20 @@ public class DeleteTopic { * @param topicId - the id of the topic to delete. * @return - updated topic. * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. */ - public static void deleteTopic(String courseId, String topicId) throws IOException { - /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() - .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_TOPICS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + public static void deleteTopic(String courseId, String topicId) + throws GeneralSecurityException, IOException { // Create the classroom API client. - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom samples") - .build(); + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); // [START classroom_delete_topic_code_snippet] @@ -59,12 +61,7 @@ public static void deleteTopic(String courseId, String topicId) throws IOExcepti service.courses().topics().delete(courseId, topicId).execute(); } catch (GoogleJsonResponseException e) { // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 404) { - System.out.printf("The courseId or topicId does not exist: %s, %s.\n", courseId, topicId); - } else { - throw e; - } + throw e; } catch (Exception e) { throw e; } diff --git a/classroom/snippets/src/main/java/GetCourse.java b/classroom/snippets/src/main/java/GetCourse.java index 7955f1da..94d07f75 100644 --- a/classroom/snippets/src/main/java/GetCourse.java +++ b/classroom/snippets/src/main/java/GetCourse.java @@ -12,46 +12,48 @@ // See the License for the specific language governing permissions and // limitations under the License. - // [START classroom_get_course] +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.classroom.Classroom; import com.google.api.services.classroom.ClassroomScopes; import com.google.api.services.classroom.model.Course; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; -import java.util.Collections; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; /* Class to demonstrate the use of Classroom Get Course API */ public class GetCourse { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_COURSES)); + /** * Retrieve a single course's metadata. * * @param courseId - Id of the course to return. * @return a course * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. */ - public static Course getCourse(String courseId) throws IOException { - /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() - .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSES)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + public static Course getCourse(String courseId) throws GeneralSecurityException, IOException { - // Create the classroom API client - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom samples") - .build(); + // Create the classroom API client. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); Course course = null; try { @@ -69,4 +71,4 @@ public static Course getCourse(String courseId) throws IOException { return course; } } -// [END classroom_get_course] \ No newline at end of file +// [END classroom_get_course] diff --git a/classroom/snippets/src/main/java/GetInvitation.java b/classroom/snippets/src/main/java/GetInvitation.java new file mode 100644 index 00000000..77d0598f --- /dev/null +++ b/classroom/snippets/src/main/java/GetInvitation.java @@ -0,0 +1,76 @@ +// Copyright 2023 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 +// +// https://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 classroom_get_invitation] + +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; +import com.google.api.client.googleapis.json.GoogleJsonError; +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.classroom.Classroom; +import com.google.api.services.classroom.ClassroomScopes; +import com.google.api.services.classroom.model.Invitation; +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; + +/* Class to demonstrate the use of Classroom Get Invitation API. */ +public class GetInvitation { + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_ROSTERS)); + + /** + * Retrieves an invitation. + * + * @param id - the identifier of the invitation to retrieve. + * @return the specified invitation. + * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. + */ + public static Invitation getInvitation(String id) throws GeneralSecurityException, IOException { + // Create the classroom API client. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); + + // [START classroom_get_invitation_code_snippet] + Invitation invitation = null; + try { + invitation = service.invitations().get(id).execute(); + System.out.printf( + "Invitation (%s) for user (%s) in course (%s) retrieved.\n", + invitation.getId(), invitation.getUserId(), invitation.getCourseId()); + } catch (GoogleJsonResponseException e) { + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("The invitation id (%s) does not exist.\n", id); + } + throw e; + } catch (Exception e) { + throw e; + } + return invitation; + // [END classroom_get_invitation_code_snippet] + } +} +// [END classroom_get_invitation] diff --git a/classroom/snippets/src/main/java/GetTopic.java b/classroom/snippets/src/main/java/GetTopic.java index 140a0407..5fb42012 100644 --- a/classroom/snippets/src/main/java/GetTopic.java +++ b/classroom/snippets/src/main/java/GetTopic.java @@ -12,24 +12,29 @@ // See the License for the specific language governing permissions and // limitations under the License. - // [START classroom_get_topic_class] +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.classroom.Classroom; import com.google.api.services.classroom.ClassroomScopes; import com.google.api.services.classroom.model.Topic; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; -import java.util.Collections; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; /* Class to demonstrate how to get a topic. */ public class GetTopic { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_TOPICS)); + /** * Get a topic in a course. * @@ -37,22 +42,20 @@ public class GetTopic { * @param topicId - the id of the topic to retrieve. * @return - the topic to retrieve. * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. */ - public static Topic getTopic(String courseId, String topicId) throws IOException { - /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() - .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_TOPICS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + public static Topic getTopic(String courseId, String topicId) + throws GeneralSecurityException, IOException { // Create the classroom API client. - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom samples") - .build(); + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); // [START classroom_get_topic_code_snippet] @@ -62,13 +65,12 @@ public static Topic getTopic(String courseId, String topicId) throws IOException topic = service.courses().topics().get(courseId, topicId).execute(); System.out.printf("Topic '%s' found.\n", topic.getName()); } catch (GoogleJsonResponseException e) { - //TODO (developer) - handle error appropriately + // TODO (developer) - handle error appropriately GoogleJsonError error = e.getDetails(); if (error.getCode() == 404) { System.out.printf("The courseId or topicId does not exist: %s, %s.\n", courseId, topicId); - } else { - throw e; } + throw e; } catch (Exception e) { throw e; } diff --git a/classroom/snippets/src/main/java/ListCourseAliases.java b/classroom/snippets/src/main/java/ListCourseAliases.java index c3141cf1..dbec2299 100644 --- a/classroom/snippets/src/main/java/ListCourseAliases.java +++ b/classroom/snippets/src/main/java/ListCourseAliases.java @@ -12,50 +12,51 @@ // See the License for the specific language governing permissions and // limitations under the License. - // [START classroom_list_aliases_class] +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.classroom.Classroom; import com.google.api.services.classroom.ClassroomScopes; import com.google.api.services.classroom.model.CourseAlias; import com.google.api.services.classroom.model.ListCourseAliasesResponse; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; +import java.security.GeneralSecurityException; import java.util.ArrayList; -import java.util.Collections; +import java.util.Arrays; import java.util.List; /* Class to demonstrate the use of Classroom List Alias API */ public class ListCourseAliases { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_COURSES)); + /** * Retrieve the aliases for a course. * * @param courseId - id of the course. * @return list of course aliases * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. */ public static List listCourseAliases(String courseId) - throws IOException { - /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() - .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSES)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + throws GeneralSecurityException, IOException { - // Create the classroom API client - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom samples") - .build(); + // Create the classroom API client. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); // [START classroom_list_aliases_code_snippet] @@ -65,10 +66,14 @@ public static List listCourseAliases(String courseId) try { // List of aliases of specified course do { - ListCourseAliasesResponse response = service.courses().aliases().list(courseId) - .setPageSize(100) - .setPageToken(pageToken) - .execute(); + ListCourseAliasesResponse response = + service + .courses() + .aliases() + .list(courseId) + .setPageSize(100) + .setPageToken(pageToken) + .execute(); courseAliases.addAll(response.getAliases()); pageToken = response.getNextPageToken(); } while (pageToken != null); @@ -95,4 +100,4 @@ public static List listCourseAliases(String courseId) // [END classroom_list_aliases_code_snippet] } } -// [END classroom_list_aliases_class] \ No newline at end of file +// [END classroom_list_aliases_class] diff --git a/classroom/snippets/src/main/java/ListCourses.java b/classroom/snippets/src/main/java/ListCourses.java index 5b7bd58f..c5a00b25 100644 --- a/classroom/snippets/src/main/java/ListCourses.java +++ b/classroom/snippets/src/main/java/ListCourses.java @@ -12,57 +12,55 @@ // See the License for the specific language governing permissions and // limitations under the License. - // [START classroom_list_courses] -import com.google.api.client.http.HttpRequestInitializer; +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.classroom.Classroom; import com.google.api.services.classroom.ClassroomScopes; import com.google.api.services.classroom.model.Course; import com.google.api.services.classroom.model.ListCoursesResponse; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; +import java.security.GeneralSecurityException; import java.util.ArrayList; -import java.util.Collections; +import java.util.Arrays; import java.util.List; /* Class to demonstrate the use of Classroom List Course API */ public class ListCourses { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_COURSES)); + /** * Retrieves all courses with metadata * * @return list of courses with its metadata * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. */ - public static List listCourses() throws IOException { - /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() - .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSES)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + public static List listCourses() throws GeneralSecurityException, IOException { - // Create the classroom API client - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom samples") - .build(); + // Create the classroom API client. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); String pageToken = null; List courses = new ArrayList<>(); try { do { - ListCoursesResponse response = service.courses().list() - .setPageSize(100) - .setPageToken(pageToken) - .execute(); + ListCoursesResponse response = + service.courses().list().setPageSize(100).setPageToken(pageToken).execute(); courses.addAll(response.getCourses()); pageToken = response.getNextPageToken(); } while (pageToken != null); @@ -82,4 +80,4 @@ public static List listCourses() throws IOException { return courses; } } -// [END classroom_list_courses] \ No newline at end of file +// [END classroom_list_courses] diff --git a/classroom/snippets/src/main/java/ListStudentSubmissions.java b/classroom/snippets/src/main/java/ListStudentSubmissions.java index c5d8b29f..20e322a1 100644 --- a/classroom/snippets/src/main/java/ListStudentSubmissions.java +++ b/classroom/snippets/src/main/java/ListStudentSubmissions.java @@ -14,24 +14,29 @@ // [START classroom_list_student_submissions_class] +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.classroom.Classroom; import com.google.api.services.classroom.ClassroomScopes; import com.google.api.services.classroom.model.ListStudentSubmissionsResponse; import com.google.api.services.classroom.model.StudentSubmission; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; +import java.security.GeneralSecurityException; import java.util.ArrayList; -import java.util.Collections; +import java.util.Arrays; import java.util.List; /* Class to demonstrate the use of Classroom List StudentSubmissions API. */ public class ListStudentSubmissions { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS)); + /** * Retrieves a specific student's submissions for the specified course work. * @@ -40,26 +45,23 @@ public class ListStudentSubmissions { * @param userId - identifier of the student whose work to return. * @return - list of student submissions. * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. */ public static List listStudentSubmissions( - String courseId, String courseWorkId, String userId) throws IOException { - /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = - GoogleCredentials.getApplicationDefault() - .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials); + String courseId, String courseWorkId, String userId) + throws GeneralSecurityException, IOException { // Create the classroom API client. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); Classroom service = new Classroom.Builder( - new NetHttpTransport(), GsonFactory.getDefaultInstance(), requestInitializer) + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) .setApplicationName("Classroom samples") .build(); // [START classroom_list_student_submissions_code_snippet] - List studentSubmissions = new ArrayList<>(); String pageToken = null; @@ -90,6 +92,7 @@ public static List listStudentSubmissions( System.out.printf("Student submission: %s.\n", submission.getId()); } } + // [END classroom_list_student_submissions_code_snippet] } catch (GoogleJsonResponseException e) { // TODO (developer) - handle error appropriately GoogleJsonError error = e.getDetails(); @@ -104,9 +107,73 @@ public static List listStudentSubmissions( throw e; } return studentSubmissions; + } - // [END classroom_list_student_submissions_code_snippet] + /** + * Lists all assigned grades for a particular coursework item. + * + * @param courseId - identifier of the course. + * @param courseWorkId - identifier of the course work. + * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. + */ + public static void listAssignedGrades(String courseId, String courseWorkId) + throws GeneralSecurityException, IOException { + // Create the classroom API client. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); + + List studentSubmissions = new ArrayList<>(); + String pageToken = null; + + try { + do { + // [START classroom_list_assigned_grades_code_snippet] + ListStudentSubmissionsResponse response = + service + .courses() + .courseWork() + .studentSubmissions() + .list(courseId, courseWorkId) + .setPageToken(pageToken) + .execute(); + + /* Ensure that the response is not null before retrieving data from it to avoid errors. */ + if (response.getStudentSubmissions() != null) { + studentSubmissions.addAll(response.getStudentSubmissions()); + pageToken = response.getNextPageToken(); + } + } while (pageToken != null); + + if (studentSubmissions.isEmpty()) { + System.out.println("No student submissions found."); + } else { + for (StudentSubmission submission : studentSubmissions) { + System.out.printf( + "User ID %s, Assigned grade: %s\n", + submission.getUserId(), submission.getAssignedGrade()); + } + } + // [END classroom_list_assigned_grades_code_snippet] + } catch (GoogleJsonResponseException e) { + // TODO (developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf( + "The courseId (%s) or courseWorkId (%s) does not exist.\n", courseId, courseWorkId); + } else { + throw e; + } + } catch (Exception e) { + throw e; + } } } // [END classroom_list_student_submissions_class] diff --git a/classroom/snippets/src/main/java/ListSubmissions.java b/classroom/snippets/src/main/java/ListSubmissions.java index d5356d70..105c9b41 100644 --- a/classroom/snippets/src/main/java/ListSubmissions.java +++ b/classroom/snippets/src/main/java/ListSubmissions.java @@ -14,24 +14,28 @@ // [START classroom_list_submissions_class] +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.classroom.Classroom; import com.google.api.services.classroom.ClassroomScopes; import com.google.api.services.classroom.model.ListStudentSubmissionsResponse; import com.google.api.services.classroom.model.StudentSubmission; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; +import java.security.GeneralSecurityException; import java.util.ArrayList; -import java.util.Collections; +import java.util.Arrays; import java.util.List; /* Class to demonstrate the use of Classroom List StudentSubmissions API. */ public class ListSubmissions { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS)); /** * Retrieves submissions for all students for the specified course work in a course. * @@ -39,21 +43,18 @@ public class ListSubmissions { * @param courseWorkId - identifier of the course work. * @return - list of student submissions. * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. */ public static List listSubmissions(String courseId, String courseWorkId) - throws IOException { - /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = - GoogleCredentials.getApplicationDefault() - .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials); + throws GeneralSecurityException, IOException { // Create the classroom API client. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); Classroom service = new Classroom.Builder( - new NetHttpTransport(), GsonFactory.getDefaultInstance(), requestInitializer) + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) .setApplicationName("Classroom samples") .build(); diff --git a/classroom/snippets/src/main/java/ListTopics.java b/classroom/snippets/src/main/java/ListTopics.java index 6412a1cb..ea35cf90 100644 --- a/classroom/snippets/src/main/java/ListTopics.java +++ b/classroom/snippets/src/main/java/ListTopics.java @@ -14,44 +14,47 @@ // [START classroom_list_topic_class] +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.classroom.Classroom; import com.google.api.services.classroom.ClassroomScopes; import com.google.api.services.classroom.model.ListTopicResponse; import com.google.api.services.classroom.model.Topic; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; +import java.security.GeneralSecurityException; import java.util.ArrayList; -import java.util.Collections; +import java.util.Arrays; import java.util.List; /* Class to demonstrate how to list topics in a course. */ public class ListTopics { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_TOPICS)); + /** * List topics in a course. * * @param courseId - the id of the course to retrieve topics for. * @return - the list of topics in the course that the caller is permitted to view. * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. */ - public static List listTopics(String courseId) throws IOException { - /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = - GoogleCredentials.getApplicationDefault() - .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_TOPICS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials); + public static List listTopics(String courseId) + throws GeneralSecurityException, IOException { // Create the classroom API client. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); Classroom service = new Classroom.Builder( - new NetHttpTransport(), GsonFactory.getDefaultInstance(), requestInitializer) + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) .setApplicationName("Classroom samples") .build(); diff --git a/classroom/snippets/src/main/java/ModifyAttachmentsStudentSubmission.java b/classroom/snippets/src/main/java/ModifyAttachmentsStudentSubmission.java index 252f51f5..d047ac2b 100644 --- a/classroom/snippets/src/main/java/ModifyAttachmentsStudentSubmission.java +++ b/classroom/snippets/src/main/java/ModifyAttachmentsStudentSubmission.java @@ -12,12 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. - // [START classroom_modify_attachments_student_submissions_class] +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.classroom.Classroom; @@ -26,14 +25,19 @@ import com.google.api.services.classroom.model.Link; import com.google.api.services.classroom.model.ModifyAttachmentsRequest; import com.google.api.services.classroom.model.StudentSubmission; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; /* Class to demonstrate the use of Classroom ModifyAttachments StudentSubmissions API. */ public class ModifyAttachmentsStudentSubmission { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS)); + /** * Modify attachments on a student submission. * @@ -42,23 +46,20 @@ public class ModifyAttachmentsStudentSubmission { * @param id - identifier of the student submission. * @return - the modified student submission. * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. */ public static StudentSubmission modifyAttachments(String courseId, String courseWorkId, String id) - throws IOException { - /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() - .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + throws GeneralSecurityException, IOException { // Create the classroom API client. - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom samples") - .build(); + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); // [START classroom_modify_attachments_student_submissions_code_snippet] @@ -67,28 +68,34 @@ public static StudentSubmission modifyAttachments(String courseId, String course // Create ModifyAttachmentRequest object that includes a new attachment with a link. Link link = new Link().setUrl("https://en.wikipedia.org/wiki/Irrational_number"); Attachment attachment = new Attachment().setLink(link); - ModifyAttachmentsRequest modifyAttachmentsRequest = new ModifyAttachmentsRequest() - .setAddAttachments(Arrays.asList(attachment)); + ModifyAttachmentsRequest modifyAttachmentsRequest = + new ModifyAttachmentsRequest().setAddAttachments(Arrays.asList(attachment)); // The modified studentSubmission object is returned with the new attachment added to it. - studentSubmission = service.courses().courseWork().studentSubmissions().modifyAttachments( - courseId, courseWorkId, id, modifyAttachmentsRequest) - .execute(); + studentSubmission = + service + .courses() + .courseWork() + .studentSubmissions() + .modifyAttachments(courseId, courseWorkId, id, modifyAttachmentsRequest) + .execute(); /* Prints the modified student submission. */ - System.out.printf("Modified student submission attachments: '%s'.\n", studentSubmission - .getAssignmentSubmission() - .getAttachments()); + System.out.printf( + "Modified student submission attachments: '%s'.\n", + studentSubmission.getAssignmentSubmission().getAttachments()); } catch (GoogleJsonResponseException e) { - //TODO (developer) - handle error appropriately + // TODO (developer) - handle error appropriately GoogleJsonError error = e.getDetails(); if (error.getCode() == 404) { - System.out.printf("The courseId (%s), courseWorkId (%s), or studentSubmissionId (%s) does " - + "not exist.\n", courseId, courseWorkId, id); + System.out.printf( + "The courseId (%s), courseWorkId (%s), or studentSubmissionId (%s) does " + + "not exist.\n", + courseId, courseWorkId, id); } else { throw e; } - } catch(Exception e) { + } catch (Exception e) { throw e; } return studentSubmission; @@ -97,4 +104,4 @@ public static StudentSubmission modifyAttachments(String courseId, String course } } -// [END classroom_modify_attachments_student_submissions_class] \ No newline at end of file +// [END classroom_modify_attachments_student_submissions_class] diff --git a/classroom/snippets/src/main/java/PatchCourse.java b/classroom/snippets/src/main/java/PatchCourse.java index e8c5d31b..05bc71ac 100644 --- a/classroom/snippets/src/main/java/PatchCourse.java +++ b/classroom/snippets/src/main/java/PatchCourse.java @@ -12,54 +12,53 @@ // See the License for the specific language governing permissions and // limitations under the License. - // [START classroom_patch_course] +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.classroom.Classroom; import com.google.api.services.classroom.ClassroomScopes; import com.google.api.services.classroom.model.Course; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; -import java.util.Collections; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; /* Class to demonstrate the use of Classroom Patch Course API */ public class PatchCourse { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_COURSES)); + /** * Updates one or more fields in a course. * * @param courseId - Id of the course to update. * @return updated course * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. */ - public static Course patchCourse(String courseId) throws IOException { - /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() - .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSES)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + public static Course patchCourse(String courseId) throws GeneralSecurityException, IOException { + + // Create the classroom API client. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); - // Create the classroom API client - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom samples") - .build(); Course course = null; try { - course = new Course() - .setSection("Period 3") - .setRoom("302"); - course = service.courses().patch(courseId, course) - .setUpdateMask("section,room") - .execute(); + course = new Course().setSection("Period 3").setRoom("302"); + course = service.courses().patch(courseId, course).setUpdateMask("section,room").execute(); System.out.printf("Course '%s' updated.\n", course.getName()); } catch (GoogleJsonResponseException e) { // TODO(developer) - handle error appropriately @@ -73,4 +72,4 @@ public static Course patchCourse(String courseId) throws IOException { return course; } } -// [END classroom_patch_course] \ No newline at end of file +// [END classroom_patch_course] diff --git a/classroom/snippets/src/main/java/PatchStudentSubmission.java b/classroom/snippets/src/main/java/PatchStudentSubmission.java index 1690ef8e..33ed5165 100644 --- a/classroom/snippets/src/main/java/PatchStudentSubmission.java +++ b/classroom/snippets/src/main/java/PatchStudentSubmission.java @@ -12,24 +12,28 @@ // See the License for the specific language governing permissions and // limitations under the License. - // [START classroom_patch_student_submissions_class] +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.classroom.Classroom; import com.google.api.services.classroom.ClassroomScopes; import com.google.api.services.classroom.model.StudentSubmission; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; -import java.util.Collections; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; /* Class to demonstrate the use of Classroom Patch StudentSubmissions API. */ public class PatchStudentSubmission { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS)); /** * Updates the draft grade and/or assigned grade of a student submission. * @@ -38,51 +42,59 @@ public class PatchStudentSubmission { * @param id - identifier of the student submission. * @return - the updated student submission. * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. */ - public static StudentSubmission patchStudentSubmission(String courseId, String courseWorkId, - String id) throws IOException { - /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() - .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + public static StudentSubmission patchStudentSubmission( + String courseId, String courseWorkId, String id) + throws GeneralSecurityException, IOException { // Create the classroom API client. - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom samples") - .build(); + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); // [START classroom_patch_student_submissions_code_snippet] StudentSubmission studentSubmission = null; try { // Updating the draftGrade and assignedGrade fields for the specific student submission. - StudentSubmission content = service.courses().courseWork().studentSubmissions() - .get(courseId, courseWorkId, id) - .execute(); + StudentSubmission content = + service + .courses() + .courseWork() + .studentSubmissions() + .get(courseId, courseWorkId, id) + .execute(); content.setAssignedGrade(90.00); content.setDraftGrade(80.00); // The updated studentSubmission object is returned with the new draftGrade and assignedGrade. - studentSubmission = service.courses().courseWork().studentSubmissions() - .patch(courseId, courseWorkId, id, content) - .set("updateMask", "draftGrade,assignedGrade") - .execute(); + studentSubmission = + service + .courses() + .courseWork() + .studentSubmissions() + .patch(courseId, courseWorkId, id, content) + .set("updateMask", "draftGrade,assignedGrade") + .execute(); /* Prints the updated student submission. */ - System.out.printf("Updated student submission draft grade (%s) and assigned grade (%s).\n", - studentSubmission.getDraftGrade(), - studentSubmission.getAssignedGrade()); + System.out.printf( + "Updated student submission draft grade (%s) and assigned grade (%s).\n", + studentSubmission.getDraftGrade(), studentSubmission.getAssignedGrade()); } catch (GoogleJsonResponseException e) { - //TODO (developer) - handle error appropriately + // TODO (developer) - handle error appropriately GoogleJsonError error = e.getDetails(); if (error.getCode() == 404) { - System.out.printf("The courseId (%s), courseWorkId (%s), or studentSubmissionId (%s) does " - + "not exist.\n", courseId, courseWorkId, id); + System.out.printf( + "The courseId (%s), courseWorkId (%s), or studentSubmissionId (%s) does " + + "not exist.\n", + courseId, courseWorkId, id); } else { throw e; } @@ -95,4 +107,4 @@ public static StudentSubmission patchStudentSubmission(String courseId, String c } } -// [END classroom_patch_student_submissions_class] \ No newline at end of file +// [END classroom_patch_student_submissions_class] diff --git a/classroom/snippets/src/main/java/ReturnStudentSubmission.java b/classroom/snippets/src/main/java/ReturnStudentSubmission.java index 6b40fc96..61c891a0 100644 --- a/classroom/snippets/src/main/java/ReturnStudentSubmission.java +++ b/classroom/snippets/src/main/java/ReturnStudentSubmission.java @@ -12,60 +12,67 @@ // See the License for the specific language governing permissions and // limitations under the License. - // [START classroom_return_student_submissions_class] +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.classroom.Classroom; import com.google.api.services.classroom.ClassroomScopes; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; -import java.util.Collections; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; /* Class to demonstrate the use of Classroom Return StudentSubmissions API. */ public class ReturnStudentSubmission { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS)); /** - * Return a student submission back to the student which updates the submission state to `RETURNED`. + * Return a student submission back to the student which updates the submission state to + * `RETURNED`. * * @param courseId - identifier of the course. * @param courseWorkId - identifier of the course work. * @param id - identifier of the student submission. * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. */ public static void returnSubmission(String courseId, String courseWorkId, String id) - throws IOException { - /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() - .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + throws GeneralSecurityException, IOException { // Create the classroom API client. - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom samples") - .build(); + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); // [START classroom_return_student_submissions_code_snippet] try { - service.courses().courseWork().studentSubmissions() + service + .courses() + .courseWork() + .studentSubmissions() .classroomReturn(courseId, courseWorkId, id, null) .execute(); } catch (GoogleJsonResponseException e) { - //TODO (developer) - handle error appropriately + // TODO (developer) - handle error appropriately GoogleJsonError error = e.getDetails(); if (error.getCode() == 404) { - System.out.printf("The courseId (%s), courseWorkId (%s), or studentSubmissionId (%s) does " - + "not exist.\n", courseId, courseWorkId, id); + System.out.printf( + "The courseId (%s), courseWorkId (%s), or studentSubmissionId (%s) does " + + "not exist.\n", + courseId, courseWorkId, id); } else { throw e; } diff --git a/classroom/snippets/src/main/java/UpdateCourse.java b/classroom/snippets/src/main/java/UpdateCourse.java index 9e0d63ed..fdfd6062 100644 --- a/classroom/snippets/src/main/java/UpdateCourse.java +++ b/classroom/snippets/src/main/java/UpdateCourse.java @@ -12,46 +12,47 @@ // See the License for the specific language governing permissions and // limitations under the License. - // [START classroom_update_course] +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.classroom.Classroom; import com.google.api.services.classroom.ClassroomScopes; import com.google.api.services.classroom.model.Course; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; -import java.util.Collections; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; /* Class to demonstrate the use of Classroom Update Course API */ public class UpdateCourse { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_COURSES)); /** * Updates a course's metadata. * * @param courseId - Id of the course to update. * @return updated course * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. */ - public static Course updateCourse(String courseId) throws IOException { - /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() - .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_COURSES)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + public static Course updateCourse(String courseId) throws GeneralSecurityException, IOException { - // Create the classroom API client - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom samples") - .build(); + // Create the classroom API client. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); Course course = null; try { @@ -74,4 +75,4 @@ public static Course updateCourse(String courseId) throws IOException { return course; } } -// [END classroom_update_course] \ No newline at end of file +// [END classroom_update_course] diff --git a/classroom/snippets/src/main/java/UpdateTopic.java b/classroom/snippets/src/main/java/UpdateTopic.java index f45ffeca..e45c3cc8 100644 --- a/classroom/snippets/src/main/java/UpdateTopic.java +++ b/classroom/snippets/src/main/java/UpdateTopic.java @@ -12,24 +12,29 @@ // See the License for the specific language governing permissions and // limitations under the License. - // [START classroom_update_topic_class] +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.classroom.Classroom; import com.google.api.services.classroom.ClassroomScopes; import com.google.api.services.classroom.model.Topic; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; -import java.util.Collections; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; /* Class to demonstrate how to update one or more fields in a topic. */ public class UpdateTopic { + + /* Scopes required by this API call. If modifying these scopes, delete your previously saved + tokens/ folder. */ + static ArrayList SCOPES = + new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_TOPICS)); + /** * Update one or more fields in a topic in a course. * @@ -37,22 +42,19 @@ public class UpdateTopic { * @param topicId - the id of the topic to update. * @return - updated topic. * @throws IOException - if credentials file not found. + * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created. */ - public static Topic updateTopic(String courseId, String topicId) throws IOException { - /* Load pre-authorized user credentials from the environment. - TODO(developer) - See https://developers.google.com/identity for - guides on implementing OAuth2 for your application. */ - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() - .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_TOPICS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); - + public static Topic updateTopic(String courseId, String topicId) + throws GeneralSecurityException, IOException { // Create the classroom API client. - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom samples") - .build(); + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder( + HTTP_TRANSPORT, + GsonFactory.getDefaultInstance(), + ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES)) + .setApplicationName("Classroom samples") + .build(); // [START classroom_update_topic_code_snippet] @@ -65,10 +67,14 @@ public static Topic updateTopic(String courseId, String topicId) throws IOExcept topicToUpdate.setName("Semester 2"); /* Call the patch endpoint and set the updateMask query parameter to the field that needs to - be updated. */ - topic = service.courses().topics().patch(courseId, topicId, topicToUpdate) - .set("updateMask", "name") - .execute(); + be updated. */ + topic = + service + .courses() + .topics() + .patch(courseId, topicId, topicToUpdate) + .set("updateMask", "name") + .execute(); /* Prints the updated topic. */ System.out.printf("Topic '%s' updated.\n", topic.getName()); diff --git a/classroom/snippets/src/test/java/BaseTest.java b/classroom/snippets/src/test/java/BaseTest.java index b0c5286e..1b2eb04d 100644 --- a/classroom/snippets/src/test/java/BaseTest.java +++ b/classroom/snippets/src/test/java/BaseTest.java @@ -19,13 +19,11 @@ import com.google.api.services.classroom.ClassroomScopes; import com.google.api.services.classroom.model.Course; import com.google.api.services.classroom.model.CourseAlias; -import java.util.Collections; -import java.util.List; -import org.junit.After; -import org.junit.Before; - import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.ArrayList; import java.util.UUID; +import org.junit.After; // Base class for integration tests. public class BaseTest { @@ -38,10 +36,11 @@ public class BaseTest { * @return an authorized Classroom client service * @throws IOException - if credentials file not found. */ - protected Classroom buildService() throws Exception { + protected Classroom buildService(ArrayList SCOPES) + throws GeneralSecurityException, IOException { /* Scopes required by this API call. If modifying these scopes, delete your previously saved tokens/ folder. */ - final List SCOPES = Collections.singletonList(ClassroomScopes.CLASSROOM_COURSES); + SCOPES.add(ClassroomScopes.CLASSROOM_COURSES); // Create the classroom API client final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); @@ -54,16 +53,17 @@ protected Classroom buildService() throws Exception { .build(); } - @Before - public void setup() throws Exception { - this.service = buildService(); + public void setup(ArrayList scopes) throws GeneralSecurityException, IOException { + this.service = buildService(scopes); this.testCourse = CreateCourse.createCourse(); createAlias(this.testCourse.getId()); } @After public void tearDown() throws IOException { - deleteCourse(this.testCourse.getId()); + if (this.testCourse != null) { + deleteCourse(this.testCourse.getId()); + } this.testCourse = null; } diff --git a/classroom/snippets/src/test/java/TestAcceptInvitation.java b/classroom/snippets/src/test/java/TestAcceptInvitation.java new file mode 100644 index 00000000..98a6fec3 --- /dev/null +++ b/classroom/snippets/src/test/java/TestAcceptInvitation.java @@ -0,0 +1,39 @@ +// Copyright 2023 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 +// +// https://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. + +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import java.io.IOException; +import java.security.GeneralSecurityException; +import org.junit.Assert; +import org.junit.Test; + +public class TestAcceptInvitation { + + private String invitationId = "insert_invitation_id"; + + @Test + public void testAcceptInvitation() throws GeneralSecurityException, IOException { + AcceptInvitation.acceptInvitation(invitationId); + /* Once an invitation is accepted, it is removed and the user is added to the course as a + teacher or a student. */ + Assert.assertThrows( + GoogleJsonResponseException.class, () -> GetInvitation.getInvitation(invitationId)); + } + + @Test + public void testAcceptInvitationWithInvalidId() { + Assert.assertThrows( + GoogleJsonResponseException.class, () -> AcceptInvitation.acceptInvitation("invalid-id")); + } +} diff --git a/classroom/snippets/src/test/java/TestAddAliasToCourse.java b/classroom/snippets/src/test/java/TestAddAliasToCourse.java index c5b85777..4eb659eb 100644 --- a/classroom/snippets/src/test/java/TestAddAliasToCourse.java +++ b/classroom/snippets/src/test/java/TestAddAliasToCourse.java @@ -14,6 +14,7 @@ import com.google.api.services.classroom.model.CourseAlias; import java.io.IOException; +import java.security.GeneralSecurityException; import java.util.List; import org.junit.Assert; import org.junit.Test; @@ -22,13 +23,13 @@ public class TestAddAliasToCourse extends BaseTest { @Test - public void testAddCourseAlias() throws IOException { + public void testAddCourseAlias() throws GeneralSecurityException, IOException { + // Include the scopes required to run the code example for testing purposes. + setup(AddAliasToCourse.SCOPES); CourseAlias courseAlias = AddAliasToCourse.addAliasToCourse(testCourse.getId()); - List courseAliases = service.courses().aliases() - .list(testCourse.getId() - ).execute() - .getAliases(); + List courseAliases = + service.courses().aliases().list(testCourse.getId()).execute().getAliases(); Assert.assertNotNull("Course alias not returned.", courseAlias); Assert.assertTrue("No course aliases exist.", courseAliases.size() > 0); } -} \ No newline at end of file +} diff --git a/classroom/snippets/src/test/java/TestAddStudent.java b/classroom/snippets/src/test/java/TestAddStudent.java index f023989a..2b185c9a 100644 --- a/classroom/snippets/src/test/java/TestAddStudent.java +++ b/classroom/snippets/src/test/java/TestAddStudent.java @@ -12,22 +12,26 @@ // See the License for the specific language governing permissions and // limitations under the License. -import com.google.api.services.classroom.model.Course; import com.google.api.services.classroom.model.Student; +import java.io.IOException; +import java.security.GeneralSecurityException; import org.junit.Assert; import org.junit.Test; -import java.io.IOException; // Unit test class for Add Student classroom snippet public class TestAddStudent extends BaseTest { + private String studentId = "insert_student_id"; + @Test - public void testAddStudent() throws IOException { - Course course = CreateCourse.createCourse(); - Student student = AddStudent.addStudent(course.getId(), course.getEnrollmentCode()); - deleteCourse(course.getId()); + public void testAddStudent() throws GeneralSecurityException, IOException { + // Include the scopes required to run the code example for testing purposes. + setup(AddStudent.SCOPES); + Student student = + AddStudent.addStudent(testCourse.getId(), testCourse.getEnrollmentCode(), this.studentId); Assert.assertNotNull("Student not returned.", student); - Assert.assertEquals("Student added to wrong course.", course.getId(), - student.getCourseId()); + Assert.assertNotNull("Course not returned.", student.getCourseId()); + Assert.assertEquals( + "Student added to wrong course.", testCourse.getId(), student.getCourseId()); } -} \ No newline at end of file +} diff --git a/classroom/snippets/src/test/java/TestAddTeacher.java b/classroom/snippets/src/test/java/TestAddTeacher.java index f2846ddf..58eaae57 100644 --- a/classroom/snippets/src/test/java/TestAddTeacher.java +++ b/classroom/snippets/src/test/java/TestAddTeacher.java @@ -13,19 +13,23 @@ // limitations under the License. import com.google.api.services.classroom.model.Teacher; +import java.io.IOException; +import java.security.GeneralSecurityException; import org.junit.Assert; import org.junit.Test; -import java.io.IOException; // Unit test class for Add Teacher classroom snippet public class TestAddTeacher extends BaseTest { - private String otherUser = "gduser1@workspacesamples.dev"; + + private String teacherEmail = "insert_teacher_email"; @Test - public void testAddTeacher() throws IOException { - Teacher teacher = AddTeacher.addTeacher(testCourse.getId(), this.otherUser); + public void testAddTeacher() throws GeneralSecurityException, IOException { + // Include the scopes required to run the code example for testing purposes. + setup(AddTeacher.SCOPES); + Teacher teacher = AddTeacher.addTeacher(testCourse.getId(), this.teacherEmail); Assert.assertNotNull("Teacher not returned.", teacher); - Assert.assertEquals("Teacher added to wrong course.", testCourse.getId(), - teacher.getCourseId()); + Assert.assertEquals( + "Teacher added to wrong course.", testCourse.getId(), teacher.getCourseId()); } -} \ No newline at end of file +} diff --git a/classroom/snippets/src/test/java/TestBatchAddStudents.java b/classroom/snippets/src/test/java/TestBatchAddStudents.java index 04ee930e..1f66874a 100644 --- a/classroom/snippets/src/test/java/TestBatchAddStudents.java +++ b/classroom/snippets/src/test/java/TestBatchAddStudents.java @@ -12,18 +12,19 @@ // See the License for the specific language governing permissions and // limitations under the License. -import org.junit.Test; import java.io.IOException; +import java.security.GeneralSecurityException; import java.util.Arrays; import java.util.List; +import org.junit.Test; // Unit test class for Batch Add Students classroom snippet public class TestBatchAddStudents extends BaseTest { @Test - public void testBatchAddStudents() throws IOException { - List studentEmails = Arrays.asList("gduser2@workpsacesamples.dev", - "gduser3@workpsacesamples.dev"); + public void testBatchAddStudents() throws GeneralSecurityException, IOException { + setup(BatchAddStudents.SCOPES); + List studentEmails = Arrays.asList("insert_student_1_email", "insert_student_2_email"); BatchAddStudents.batchAddStudents(testCourse.getId(), studentEmails); } -} \ No newline at end of file +} diff --git a/classroom/snippets/src/test/java/TestCreateCourse.java b/classroom/snippets/src/test/java/TestCreateCourse.java index 381f2c2c..a251f15c 100644 --- a/classroom/snippets/src/test/java/TestCreateCourse.java +++ b/classroom/snippets/src/test/java/TestCreateCourse.java @@ -13,15 +13,18 @@ // limitations under the License. import com.google.api.services.classroom.model.Course; +import java.io.IOException; +import java.security.GeneralSecurityException; import org.junit.Assert; import org.junit.Test; -import java.io.IOException; // Unit test class for Create Course classroom snippet public class TestCreateCourse extends BaseTest { @Test - public void testCreateCourse() throws IOException { + public void testCreateCourse() throws GeneralSecurityException, IOException { + // Include the scopes required to run the code example for testing purposes. + setup(CreateCourse.SCOPES); Course course = CreateCourse.createCourse(); Assert.assertNotNull("Course not returned.", course); deleteCourse(course.getId()); diff --git a/classroom/snippets/src/test/java/TestCreateCourseWithAlias.java b/classroom/snippets/src/test/java/TestCreateCourseWithAlias.java index 5152b984..2d906fbf 100644 --- a/classroom/snippets/src/test/java/TestCreateCourseWithAlias.java +++ b/classroom/snippets/src/test/java/TestCreateCourseWithAlias.java @@ -15,6 +15,7 @@ import com.google.api.services.classroom.model.Course; import com.google.api.services.classroom.model.CourseAlias; import java.io.IOException; +import java.security.GeneralSecurityException; import java.util.List; import org.junit.Assert; import org.junit.Test; @@ -23,14 +24,13 @@ public class TestCreateCourseWithAlias extends BaseTest { @Test - public void testCreateCourseWithAlias() throws IOException { + public void testCreateCourseWithAlias() throws GeneralSecurityException, IOException { + setup(CreateCourseWithAlias.SCOPES); Course course = CreateCourseWithAlias.createCourseWithAlias(); - List courseAliases = service.courses().aliases() - .list(course.getId() - ).execute() - .getAliases(); + List courseAliases = + service.courses().aliases().list(course.getId()).execute().getAliases(); Assert.assertNotNull("Course not returned.", course); Assert.assertTrue("No course aliases exist.", courseAliases.size() > 0); deleteCourse(course.getId()); } -} \ No newline at end of file +} diff --git a/classroom/snippets/src/test/java/TestCreateCourseWork.java b/classroom/snippets/src/test/java/TestCreateCourseWork.java index e3a25b6b..5a160af0 100644 --- a/classroom/snippets/src/test/java/TestCreateCourseWork.java +++ b/classroom/snippets/src/test/java/TestCreateCourseWork.java @@ -14,6 +14,7 @@ import com.google.api.services.classroom.model.CourseWork; import java.io.IOException; +import java.security.GeneralSecurityException; import org.junit.Assert; import org.junit.Test; @@ -21,7 +22,9 @@ public class TestCreateCourseWork extends BaseTest { @Test - public void testCreateCoursework() throws IOException { + public void testCreateCoursework() throws GeneralSecurityException, IOException { + // Include the scopes required to run the code example for testing purposes. + setup(CreateCourseWork.SCOPES); CourseWork courseWork = CreateCourseWork.createCourseWork(testCourse.getId()); Assert.assertNotNull("Coursework not returned.", courseWork); } diff --git a/classroom/snippets/src/test/java/TestCreateInvitation.java b/classroom/snippets/src/test/java/TestCreateInvitation.java new file mode 100644 index 00000000..13095342 --- /dev/null +++ b/classroom/snippets/src/test/java/TestCreateInvitation.java @@ -0,0 +1,43 @@ +// Copyright 2023 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 +// +// https://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. + +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.services.classroom.model.Invitation; +import java.io.IOException; +import java.security.GeneralSecurityException; +import org.junit.Assert; +import org.junit.Test; + +public class TestCreateInvitation extends BaseTest { + + private String userId = "insert_user_id"; + + @Test + public void testCreateInvitation() throws GeneralSecurityException, IOException { + setup(CreateInvitation.SCOPES); + Invitation invitation = CreateInvitation.createInvitation(testCourse.getId(), userId); + Assert.assertNotNull("Invitation not created", invitation); + Assert.assertEquals(invitation.getCourseId(), testCourse.getId()); + Assert.assertEquals(invitation.getUserId(), userId); + } + + @Test + public void testCreateInvitationWithInvalidCourseId() + throws GeneralSecurityException, IOException { + setup(CreateInvitation.SCOPES); + Assert.assertThrows( + GoogleJsonResponseException.class, + () -> CreateInvitation.createInvitation("invalid-course-id", userId)); + } +} diff --git a/classroom/snippets/src/test/java/TestCreateTopic.java b/classroom/snippets/src/test/java/TestCreateTopic.java index e2d77586..381921d9 100644 --- a/classroom/snippets/src/test/java/TestCreateTopic.java +++ b/classroom/snippets/src/test/java/TestCreateTopic.java @@ -14,6 +14,7 @@ import com.google.api.services.classroom.model.Topic; import java.io.IOException; +import java.security.GeneralSecurityException; import org.junit.Assert; import org.junit.Test; @@ -21,7 +22,8 @@ public class TestCreateTopic extends BaseTest { @Test - public void testCreateTopic() throws IOException { + public void testCreateTopic() throws GeneralSecurityException, IOException { + setup(CreateTopic.SCOPES); Topic topic = CreateTopic.createTopic(testCourse.getId()); Assert.assertNotNull("Topic not returned.", topic); } diff --git a/classroom/snippets/src/test/java/TestDeleteInvitation.java b/classroom/snippets/src/test/java/TestDeleteInvitation.java new file mode 100644 index 00000000..84448189 --- /dev/null +++ b/classroom/snippets/src/test/java/TestDeleteInvitation.java @@ -0,0 +1,42 @@ +// Copyright 2023 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 +// +// https://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. + +import com.google.api.client.googleapis.json.GoogleJsonResponseException; +import com.google.api.services.classroom.model.Invitation; +import java.io.IOException; +import java.security.GeneralSecurityException; +import org.junit.Assert; +import org.junit.Test; + +public class TestDeleteInvitation extends BaseTest { + + private String userId = "insert_user_id"; + + @Test + public void testDeleteInvitation() throws GeneralSecurityException, IOException { + setup(DeleteInvitation.SCOPES); + Invitation invitation = CreateInvitation.createInvitation(testCourse.getId(), userId); + DeleteInvitation.deleteInvitation(invitation.getId()); + Assert.assertThrows( + GoogleJsonResponseException.class, () -> GetInvitation.getInvitation(invitation.getId())); + } + + @Test + public void testDeleteInvitationWithInvalidId() throws GeneralSecurityException, IOException { + setup(DeleteInvitation.SCOPES); + Assert.assertThrows( + GoogleJsonResponseException.class, + () -> DeleteInvitation.deleteInvitation("invalid-invitation-id")); + } +} diff --git a/classroom/snippets/src/test/java/TestDeleteTopic.java b/classroom/snippets/src/test/java/TestDeleteTopic.java index b093865c..bffff20d 100644 --- a/classroom/snippets/src/test/java/TestDeleteTopic.java +++ b/classroom/snippets/src/test/java/TestDeleteTopic.java @@ -15,15 +15,19 @@ import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.services.classroom.model.Topic; import java.io.IOException; +import java.security.GeneralSecurityException; import org.junit.Assert; import org.junit.Test; public class TestDeleteTopic extends BaseTest { + @Test - public void testDeleteTopic() throws IOException { + public void testDeleteTopic() throws GeneralSecurityException, IOException { + setup(DeleteTopic.SCOPES); Topic topic = CreateTopic.createTopic(testCourse.getId()); DeleteTopic.deleteTopic(testCourse.getId(), topic.getTopicId()); - Assert.assertThrows(GoogleJsonResponseException.class, + Assert.assertThrows( + GoogleJsonResponseException.class, () -> GetTopic.getTopic(testCourse.getId(), topic.getTopicId())); } } diff --git a/classroom/snippets/src/test/java/TestGetCourse.java b/classroom/snippets/src/test/java/TestGetCourse.java index c43059f7..ac95bda5 100644 --- a/classroom/snippets/src/test/java/TestGetCourse.java +++ b/classroom/snippets/src/test/java/TestGetCourse.java @@ -13,15 +13,17 @@ // limitations under the License. import com.google.api.services.classroom.model.Course; +import java.io.IOException; +import java.security.GeneralSecurityException; import org.junit.Assert; import org.junit.Test; -import java.io.IOException; // Unit test class for Get Course classroom snippet public class TestGetCourse extends BaseTest { @Test - public void testGetCourse() throws IOException { + public void testGetCourse() throws GeneralSecurityException, IOException { + setup(GetCourse.SCOPES); Course course = GetCourse.getCourse(testCourse.getId()); Assert.assertNotNull("Course not returned.", course); Assert.assertEquals("Wrong course returned.", testCourse.getId(), course.getId()); diff --git a/classroom/snippets/src/test/java/TestGetTopic.java b/classroom/snippets/src/test/java/TestGetTopic.java index b7cb7840..39775ff2 100644 --- a/classroom/snippets/src/test/java/TestGetTopic.java +++ b/classroom/snippets/src/test/java/TestGetTopic.java @@ -14,6 +14,7 @@ import com.google.api.services.classroom.model.Topic; import java.io.IOException; +import java.security.GeneralSecurityException; import org.junit.Assert; import org.junit.Test; @@ -21,7 +22,8 @@ public class TestGetTopic extends BaseTest { @Test - public void testGetTopic() throws IOException { + public void testGetTopic() throws GeneralSecurityException, IOException { + setup(GetTopic.SCOPES); Topic topic = CreateTopic.createTopic(testCourse.getId()); Topic getTopic = GetTopic.getTopic(testCourse.getId(), topic.getTopicId()); Assert.assertNotNull("Topic could not be created.", topic); diff --git a/classroom/snippets/src/test/java/TestListCourseAliases.java b/classroom/snippets/src/test/java/TestListCourseAliases.java index f18c1cce..d3e357b5 100644 --- a/classroom/snippets/src/test/java/TestListCourseAliases.java +++ b/classroom/snippets/src/test/java/TestListCourseAliases.java @@ -13,17 +13,19 @@ // limitations under the License. import com.google.api.services.classroom.model.CourseAlias; -import org.junit.Assert; -import org.junit.Test; import java.io.IOException; +import java.security.GeneralSecurityException; import java.util.List; +import org.junit.Assert; +import org.junit.Test; // Unit test class for List Course Aliases classroom snippet public class TestListCourseAliases extends BaseTest { @Test - public void testListCourseAliases() throws IOException { + public void testListCourseAliases() throws GeneralSecurityException, IOException { + setup(ListCourseAliases.SCOPES); List courseAliases = ListCourseAliases.listCourseAliases(testCourse.getId()); Assert.assertTrue("Incorrect number of course aliases returned.", courseAliases.size() == 1); } -} \ No newline at end of file +} diff --git a/classroom/snippets/src/test/java/TestListCourses.java b/classroom/snippets/src/test/java/TestListCourses.java index fe254b76..7a4dd553 100644 --- a/classroom/snippets/src/test/java/TestListCourses.java +++ b/classroom/snippets/src/test/java/TestListCourses.java @@ -13,16 +13,17 @@ // limitations under the License. import com.google.api.services.classroom.model.Course; -import org.junit.Assert; -import org.junit.Test; import java.io.IOException; +import java.security.GeneralSecurityException; import java.util.List; +import org.junit.Assert; +import org.junit.Test; // Unit test class for List Course classroom snippet public class TestListCourses { @Test - public void testListCourses() throws IOException { + public void testListCourses() throws GeneralSecurityException, IOException { List courses = ListCourses.listCourses(); Assert.assertTrue("No courses returned.", courses.size() > 0); } diff --git a/classroom/snippets/src/test/java/TestListSubmissions.java b/classroom/snippets/src/test/java/TestListSubmissions.java index 148e9529..1649e926 100644 --- a/classroom/snippets/src/test/java/TestListSubmissions.java +++ b/classroom/snippets/src/test/java/TestListSubmissions.java @@ -14,6 +14,7 @@ import com.google.api.services.classroom.model.StudentSubmission; import java.io.IOException; +import java.security.GeneralSecurityException; import java.util.List; import org.junit.Assert; import org.junit.Test; @@ -22,10 +23,9 @@ public class TestListSubmissions extends BaseTest { @Test - public void testListSubmissions() throws IOException { - List submissions = ListSubmissions.listSubmissions( - testCourse.getId(), - "-"); + public void testListSubmissions() throws GeneralSecurityException, IOException { + setup(ListSubmissions.SCOPES); + List submissions = ListSubmissions.listSubmissions(testCourse.getId(), "-"); Assert.assertNotNull("No submissions returned.", submissions); } } diff --git a/classroom/snippets/src/test/java/TestListTopics.java b/classroom/snippets/src/test/java/TestListTopics.java index 081be57b..f0b0bc85 100644 --- a/classroom/snippets/src/test/java/TestListTopics.java +++ b/classroom/snippets/src/test/java/TestListTopics.java @@ -14,6 +14,7 @@ import com.google.api.services.classroom.model.Topic; import java.io.IOException; +import java.security.GeneralSecurityException; import java.util.List; import org.junit.Assert; import org.junit.Test; @@ -22,7 +23,8 @@ public class TestListTopics extends BaseTest { @Test - public void testListTopics() throws IOException { + public void testListTopics() throws GeneralSecurityException, IOException { + setup(ListTopics.SCOPES); CreateTopic.createTopic(testCourse.getId()); List listTopics = ListTopics.listTopics(testCourse.getId()); Assert.assertNotNull("Topics could not be retrieved.", listTopics); diff --git a/classroom/snippets/src/test/java/TestPatchCourse.java b/classroom/snippets/src/test/java/TestPatchCourse.java index 51e05a43..a7d0d92f 100644 --- a/classroom/snippets/src/test/java/TestPatchCourse.java +++ b/classroom/snippets/src/test/java/TestPatchCourse.java @@ -13,15 +13,17 @@ // limitations under the License. import com.google.api.services.classroom.model.Course; +import java.io.IOException; +import java.security.GeneralSecurityException; import org.junit.Assert; import org.junit.Test; -import java.io.IOException; // Unit test class for Patch Course classroom snippet public class TestPatchCourse extends BaseTest { @Test - public void testPatchCourse() throws IOException { + public void testPatchCourse() throws GeneralSecurityException, IOException { + setup(PatchCourse.SCOPES); Course course = PatchCourse.patchCourse(testCourse.getId()); Assert.assertNotNull("Course not returned.", course); Assert.assertEquals("Wrong course returned.", testCourse.getId(), course.getId()); diff --git a/classroom/snippets/src/test/java/TestUpdateCourse.java b/classroom/snippets/src/test/java/TestUpdateCourse.java index f5e0080d..3c7cbda2 100644 --- a/classroom/snippets/src/test/java/TestUpdateCourse.java +++ b/classroom/snippets/src/test/java/TestUpdateCourse.java @@ -13,15 +13,17 @@ // limitations under the License. import com.google.api.services.classroom.model.Course; +import java.io.IOException; +import java.security.GeneralSecurityException; import org.junit.Assert; import org.junit.Test; -import java.io.IOException; // Unit test class for Update Course classroom snippet public class TestUpdateCourse extends BaseTest { @Test - public void testUpdateCourse() throws IOException { + public void testUpdateCourse() throws GeneralSecurityException, IOException { + setup(UpdateCourse.SCOPES); Course course = UpdateCourse.updateCourse(testCourse.getId()); Assert.assertNotNull("Course not returned.", course); Assert.assertEquals("Wrong course returned.", testCourse.getId(), course.getId()); diff --git a/classroom/snippets/src/test/java/TestUpdateTopic.java b/classroom/snippets/src/test/java/TestUpdateTopic.java index 5b1b9eec..3144ff2d 100644 --- a/classroom/snippets/src/test/java/TestUpdateTopic.java +++ b/classroom/snippets/src/test/java/TestUpdateTopic.java @@ -11,15 +11,19 @@ // 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. + import com.google.api.services.classroom.model.Topic; import java.io.IOException; +import java.security.GeneralSecurityException; import org.junit.Assert; import org.junit.Test; // Unit test class for Update Topic classroom snippet public class TestUpdateTopic extends BaseTest { + @Test - public void testUpdateTopic() throws IOException { + public void testUpdateTopic() throws GeneralSecurityException, IOException { + setup(UpdateTopic.SCOPES); Topic topic = CreateTopic.createTopic(testCourse.getId()); System.out.println("New topic created: " + topic.getName()); Topic updatedTopic = UpdateTopic.updateTopic(testCourse.getId(), topic.getTopicId()); From e3102ab486f0c278d7d0fcc020f6dea02e286b3e Mon Sep 17 00:00:00 2001 From: Justin Poehnelt Date: Tue, 2 May 2023 11:06:51 -0600 Subject: [PATCH 05/19] fix: correct typo (#634) --- calendar/quickstart/src/main/java/CalendarQuickstart.java | 2 +- docs/quickstart/src/main/java/DocsQuickstart.java | 2 +- .../quickstart/src/main/java/DriveActivityQuickstart.java | 2 +- drive/quickstart/src/main/java/DriveQuickstart.java | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/calendar/quickstart/src/main/java/CalendarQuickstart.java b/calendar/quickstart/src/main/java/CalendarQuickstart.java index 3eb09e6d..19a50114 100644 --- a/calendar/quickstart/src/main/java/CalendarQuickstart.java +++ b/calendar/quickstart/src/main/java/CalendarQuickstart.java @@ -38,7 +38,7 @@ import java.util.Collections; import java.util.List; -/* class to demonstarte use of Calendar events list API */ +/* class to demonstrate use of Calendar events list API */ public class CalendarQuickstart { /** * Application name. diff --git a/docs/quickstart/src/main/java/DocsQuickstart.java b/docs/quickstart/src/main/java/DocsQuickstart.java index 431c8394..531e044b 100644 --- a/docs/quickstart/src/main/java/DocsQuickstart.java +++ b/docs/quickstart/src/main/java/DocsQuickstart.java @@ -36,7 +36,7 @@ import java.util.Collections; import java.util.List; -/* class to demonstarte use of Docs get documents API */ +/* class to demonstrate use of Docs get documents API */ public class DocsQuickstart { /** * Application name. diff --git a/drive/activity/quickstart/src/main/java/DriveActivityQuickstart.java b/drive/activity/quickstart/src/main/java/DriveActivityQuickstart.java index e72a2c24..4a5e4657 100644 --- a/drive/activity/quickstart/src/main/java/DriveActivityQuickstart.java +++ b/drive/activity/quickstart/src/main/java/DriveActivityQuickstart.java @@ -34,7 +34,7 @@ import java.util.Arrays; import java.util.List; -/* class to demonstarte use of Drive Activity list API */ +/* class to demonstrate use of Drive Activity list API */ public class DriveActivityQuickstart { /** * Application name. diff --git a/drive/quickstart/src/main/java/DriveQuickstart.java b/drive/quickstart/src/main/java/DriveQuickstart.java index c88f9063..62db72b8 100644 --- a/drive/quickstart/src/main/java/DriveQuickstart.java +++ b/drive/quickstart/src/main/java/DriveQuickstart.java @@ -36,7 +36,7 @@ import java.util.Collections; import java.util.List; -/* class to demonstarte use of Drive files list API */ +/* class to demonstrate use of Drive files list API */ public class DriveQuickstart { /** * Application name. From d492e92baf7a23b54b54b36f6f7fc386a28dfd14 Mon Sep 17 00:00:00 2001 From: Steve Bazyl Date: Thu, 7 Mar 2024 12:02:45 -0700 Subject: [PATCH 06/19] Feat: Meet API quickstart --- meet/README.md | 1 + meet/quickstart/build.gradle | 17 ++ meet/quickstart/settings.gradle | 18 ++ .../src/main/java/MeetQuickstart.java | 174 ++++++++++++++++++ 4 files changed, 210 insertions(+) create mode 100644 meet/README.md create mode 100644 meet/quickstart/build.gradle create mode 100644 meet/quickstart/settings.gradle create mode 100644 meet/quickstart/src/main/java/MeetQuickstart.java diff --git a/meet/README.md b/meet/README.md new file mode 100644 index 00000000..edc158da --- /dev/null +++ b/meet/README.md @@ -0,0 +1 @@ +Additional samples can be found at https://github.com/googleapis/google-cloud-java/tree/main/java-meet/google-cloud-meet \ No newline at end of file diff --git a/meet/quickstart/build.gradle b/meet/quickstart/build.gradle new file mode 100644 index 00000000..fbb8bc29 --- /dev/null +++ b/meet/quickstart/build.gradle @@ -0,0 +1,17 @@ +apply plugin: 'java' +apply plugin: 'application' + +mainClassName = 'MeetQuickstart' +sourceCompatibility = 11 +targetCompatibility = 11 +version = '1.0' + +repositories { + mavenCentral() +} + +dependencies { + implementation 'com.google.cloud:google-cloud-meet:0.3.0' + implementation 'com.google.auth:google-auth-library-oauth2-http:1.19.0' + implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' +} diff --git a/meet/quickstart/settings.gradle b/meet/quickstart/settings.gradle new file mode 100644 index 00000000..7bcc727d --- /dev/null +++ b/meet/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/meet/quickstart/src/main/java/MeetQuickstart.java b/meet/quickstart/src/main/java/MeetQuickstart.java new file mode 100644 index 00000000..cd8aec6b --- /dev/null +++ b/meet/quickstart/src/main/java/MeetQuickstart.java @@ -0,0 +1,174 @@ +// 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 meet_quickstart] + +import java.awt.Desktop; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Collections; +import java.util.List; + +import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; +import com.google.api.gax.core.FixedCredentialsProvider; +import com.google.apps.meet.v2.CreateSpaceRequest; +import com.google.apps.meet.v2.Space; +import com.google.apps.meet.v2.SpacesServiceClient; +import com.google.apps.meet.v2.SpacesServiceSettings; +import com.google.auth.Credentials; +import com.google.auth.oauth2.ClientId; +import com.google.auth.oauth2.DefaultPKCEProvider; +import com.google.auth.oauth2.TokenStore; +import com.google.auth.oauth2.UserAuthorizer; + +/* class to demonstrate use of Drive files list API */ +public class MeetQuickstart { + /** + * 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/meetings.space.created"); + + private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; + + private static final String USER = "default"; + + // Simple file-based token storage for storing oauth tokens + private static final TokenStore TOKEN_STORE = new TokenStore() { + private Path pathFor(String id) { + return Paths.get(".", TOKENS_DIRECTORY_PATH, id + ".json"); + } + + @Override + public String load(String id) throws IOException { + if (!Files.exists(pathFor(id))) { + return null; + } + return Files.readString(pathFor(id)); + } + + @Override + public void store(String id, String token) throws IOException { + Files.createDirectories(Paths.get(".", TOKENS_DIRECTORY_PATH)); + Files.writeString(pathFor(id), token); + } + + @Override + public void delete(String id) throws IOException { + if (!Files.exists(pathFor(id))) { + return; + } + Files.delete(pathFor(id)); + } + }; + + /** + * Initialize a UserAuthorizer for local authorization. + * + * @param callbackUri + * @return + */ + private static UserAuthorizer getAuthorizer(URI callbackUri) throws IOException { + // Load client secrets. + try (InputStream in = MeetQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH)) { + if (in == null) { + throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH); + } + + ClientId clientId = ClientId.fromStream(in); + + UserAuthorizer authorizer = UserAuthorizer.newBuilder() + .setClientId(clientId) + .setCallbackUri(callbackUri) + .setScopes(SCOPES) + .setPKCEProvider(new DefaultPKCEProvider() { + // Temporary fix for https://github.com/googleapis/google-auth-library-java/issues/1373 + @Override + public String getCodeChallenge() { + return super.getCodeChallenge().split("=")[0]; + } + }) + .setTokenStore(TOKEN_STORE).build(); + return authorizer; + } + } + + /** + * 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 { + + LocalServerReceiver receiver = new LocalServerReceiver.Builder().build(); + try { + URI callbackUri = URI.create(receiver.getRedirectUri()); + UserAuthorizer authorizer = getAuthorizer(callbackUri); + + Credentials credentials = authorizer.getCredentials(USER); + if (credentials != null) { + return credentials; + } + + URL authorizationUrl = authorizer.getAuthorizationUrl(USER, "", null); + if (Desktop.isDesktopSupported() && + Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { + Desktop.getDesktop().browse(authorizationUrl.toURI()); + } else { + System.out.printf("Open the following URL to authorize access: %s\n", + authorizationUrl.toExternalForm()); + } + + String code = receiver.waitForCode(); + credentials = authorizer.getAndStoreCredentialsFromCode(USER, code, callbackUri); + return credentials; + } finally { + receiver.stop(); + } + } + + public static void main(String... args) throws Exception { + // Override default service settings to supply user credentials. + Credentials credentials = getCredentials(); + SpacesServiceSettings settings = SpacesServiceSettings.newBuilder() + .setCredentialsProvider(FixedCredentialsProvider.create(credentials)) + .build(); + + try (SpacesServiceClient spacesServiceClient = SpacesServiceClient.create(settings)) { + CreateSpaceRequest request = CreateSpaceRequest.newBuilder() + .setSpace(Space.newBuilder().build()) + .build(); + Space response = spacesServiceClient.createSpace(request); + System.out.printf("Space created: %s\n", response.getMeetingUri()); + } catch (IOException e) { + // TODO(developer): Handle errors + e.printStackTrace(); + } + } +} +// [END meet_quickstart] 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 07/19] 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] From b59745f664d959d3d39fdf1b935d812e67c01c13 Mon Sep 17 00:00:00 2001 From: Pierrick Voulet <6769971+PierrickVoulet@users.noreply.github.com> Date: Fri, 16 Aug 2024 21:24:09 -0400 Subject: [PATCH 08/19] feat: add Cloud Client library samples for Chat (#1078) * feat: add Cloud Client library samples for Chat * README improvements --------- Co-authored-by: pierrick --- chat/client-libraries/cloud/README.md | 28 ++++ chat/client-libraries/cloud/build.gradle | 20 +++ chat/client-libraries/cloud/pom.xml | 59 +++++++++ .../api/chat/samples/AuthenticationUtils.java | 121 ++++++++++++++++++ .../samples/CreateMembershipUserCred.java | 60 +++++++++ .../CreateMembershipUserCredForApp.java | 60 +++++++++ .../chat/samples/CreateMessageAppCred.java | 46 +++++++ .../CreateMessageAppCredAtMention.java | 50 ++++++++ .../CreateMessageAppCredWithCards.java | 66 ++++++++++ .../chat/samples/CreateMessageUserCred.java | 52 ++++++++ .../CreateMessageUserCredWithMessageId.java | 56 ++++++++ .../CreateMessageUserCredWithRequestId.java | 55 ++++++++ .../CreateMessageUserCredWithThreadKey.java | 61 +++++++++ .../CreateMessageUserCredWithThreadName.java | 62 +++++++++ .../chat/samples/DeleteMessageAppCred.java | 38 ++++++ .../chat/samples/DeleteMessageUserCred.java | 44 +++++++ .../chat/samples/GetMembershipAppCred.java | 42 ++++++ .../chat/samples/GetMembershipUserCred.java | 47 +++++++ .../api/chat/samples/GetMessageAppCred.java | 42 ++++++ .../api/chat/samples/GetMessageUserCred.java | 47 +++++++ .../api/chat/samples/GetSpaceAppCred.java | 42 ++++++ .../api/chat/samples/GetSpaceUserCred.java | 47 +++++++ .../chat/samples/ListMembershipsAppCred.java | 51 ++++++++ .../chat/samples/ListMembershipsUserCred.java | 56 ++++++++ .../chat/samples/ListMessagesUserCred.java | 53 ++++++++ .../api/chat/samples/ListSpacesAppCred.java | 49 +++++++ .../api/chat/samples/ListSpacesUserCred.java | 54 ++++++++ .../chat/samples/UpdateMessageAppCred.java | 51 ++++++++ .../chat/samples/UpdateMessageUserCred.java | 56 ++++++++ .../api/chat/samples/UpdateSpaceUserCred.java | 56 ++++++++ 30 files changed, 1571 insertions(+) create mode 100644 chat/client-libraries/cloud/README.md create mode 100644 chat/client-libraries/cloud/build.gradle create mode 100644 chat/client-libraries/cloud/pom.xml create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/AuthenticationUtils.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCred.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCredForApp.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCred.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCredAtMention.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCredWithCards.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCred.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithMessageId.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithRequestId.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithThreadKey.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithThreadName.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/DeleteMessageAppCred.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/DeleteMessageUserCred.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMembershipAppCred.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMembershipUserCred.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageAppCred.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageUserCred.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetSpaceAppCred.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetSpaceUserCred.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsAppCred.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsUserCred.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMessagesUserCred.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesAppCred.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesUserCred.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageAppCred.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageUserCred.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateSpaceUserCred.java diff --git a/chat/client-libraries/cloud/README.md b/chat/client-libraries/cloud/README.md new file mode 100644 index 00000000..7ec1fce9 --- /dev/null +++ b/chat/client-libraries/cloud/README.md @@ -0,0 +1,28 @@ +# Google Chat API - Cloud Client library samples + +## Set up + +Add `service_account.json` and/or `client_secrets.json` to the current +folder depending on the credentials used by the samples to run: + +1. `service_account.json` for + [app credentials](https://developers.google.com/workspace/chat/authenticate-authorize-chat-app) + +1. `client_secrets.json` for + [user credentials](https://developers.google.com/workspace/chat/authenticate-authorize-chat-user) + +## Run with Maven + +Execute +`mvn exec:java -Dexec.mainClass="replace.with.the.sample.mainClass"` +wih the main class of the sample. + +For example, to run the sample `CreateMessageAppCred`, run +`mvn exec:java -Dexec.mainClass="com.google.workspace.api.chat.samples.CreateMessageAppCred"`. + +## Run with Gradle + +Execute `gradle run` after setting the main class of the sample in the `build.gradle` file. + +For example, to run the sample `CreateMessageAppCred`, use +`com.google.workspace.api.chat.samples.CreateMessageAppCred`. diff --git a/chat/client-libraries/cloud/build.gradle b/chat/client-libraries/cloud/build.gradle new file mode 100644 index 00000000..470b5e81 --- /dev/null +++ b/chat/client-libraries/cloud/build.gradle @@ -0,0 +1,20 @@ +apply plugin: 'java' +apply plugin: 'application' + +mainClassName = 'com.google.workspace.api.chat.samples.CreateMessageAppCred' +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.apis:google-api-services-chat:v1-rev20240509-2.0.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/client-libraries/cloud/pom.xml b/chat/client-libraries/cloud/pom.xml new file mode 100644 index 00000000..06af9826 --- /dev/null +++ b/chat/client-libraries/cloud/pom.xml @@ -0,0 +1,59 @@ + + 4.0.0 + + com.google.workspace.api.chat.samples + chat-api-samples + 0.0.1 + Google API Client Library Chat Samples For Java + + + + 21 + 1.8 + 1.8 + + + + + + + com.google.auth + google-auth-library-oauth2-http + 1.23.0 + + + com.google.oauth-client + google-oauth-client-jetty + 1.34.1 + + + + + + com.google.apis + google-api-services-chat + v1-rev20240509-2.0.0 + + + + + + com.google.api.grpc + proto-google-cloud-chat-v1 + 0.8.0 + + + com.google.api + gax + 2.48.1 + + + + com.google.cloud + google-cloud-chat + 0.1.0 + + + + + diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/AuthenticationUtils.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/AuthenticationUtils.java new file mode 100644 index 00000000..5ffd2ff2 --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/AuthenticationUtils.java @@ -0,0 +1,121 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.auth.oauth2.AccessToken; +import com.google.auth.oauth2.GoogleCredentials; +import com.google.auth.oauth2.ServiceAccountCredentials; +import com.google.auth.oauth2.UserCredentials; +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.json.gson.GsonFactory; +import com.google.api.client.json.JsonFactory; +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.gax.core.GoogleCredentialsProvider; +import com.google.api.gax.core.FixedCredentialsProvider; +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.ChatServiceSettings; +import com.google.common.collect.ImmutableList; + +import java.io.FileInputStream; +import java.io.FileReader; +import java.util.Collections; +import java.util.Date; + +public class AuthenticationUtils{ + + private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); + private static final String SERVICE_ACCOUNT_FILE = "service_account.json"; + private static final String CLIENT_SECRET_FILE = "client_secrets.json"; + private static final String APP_AUTH_OAUTH_SCOPE = + "https://www.googleapis.com/auth/chat.bot"; + + public static ChatServiceClient createClientWithAppCredentials() + throws Exception { + // For more information on service account authentication, see + // https://developers.google.com/workspace/chat/authenticate-authorize-chat-app + GoogleCredentials credential = ServiceAccountCredentials.fromStream( + new FileInputStream(SERVICE_ACCOUNT_FILE)) + .createScoped(ImmutableList.of(APP_AUTH_OAUTH_SCOPE)); + + // Create the ChatServiceSettings with the app credentials + ChatServiceSettings chatServiceSettings = + ChatServiceSettings.newBuilder() + .setCredentialsProvider( + FixedCredentialsProvider.create(credential)) + .build(); + + return ChatServiceClient.create(chatServiceSettings); + } + + public static ChatServiceClient createClientWithUserCredentials( + ImmutableList scopes) throws Exception { + // For more information on user authentication, see + // https://developers.google.com/workspace/chat/authenticate-authorize-chat-user + GoogleClientSecrets clientSecrets = GoogleClientSecrets.load( + JSON_FACTORY, new FileReader(CLIENT_SECRET_FILE)); + + Credential credential = authorize(scopes, clientSecrets); + + AccessToken accessToken = new AccessToken( + credential.getAccessToken(), + new Date( + // put the actual expiry date of access token here + System.currentTimeMillis())); + UserCredentials googleCredentials = + UserCredentials + .newBuilder() + .setAccessToken(accessToken) + .setRefreshToken(credential.getRefreshToken()) + .setClientId(clientSecrets.getInstalled().getClientId()) + .setClientSecret(clientSecrets.getInstalled().getClientSecret()) + .build(); + + // Create the ChatServiceSettings with the credentials + ChatServiceSettings chatServiceSettings = + ChatServiceSettings + .newBuilder() + .setCredentialsProvider( + FixedCredentialsProvider.create(googleCredentials)) + .build(); + + return ChatServiceClient.create(chatServiceSettings); + } + + // Generate access token and refresh token using scopes and client secrets. + private static Credential authorize( + ImmutableList scopes, GoogleClientSecrets clientSecrets) + throws Exception { + // 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. + .setAccessType("offline") + .setApprovalPrompt("force") + .build(); + + // Authorize. + return new AuthorizationCodeInstalledApp( + flow, new LocalServerReceiver()).authorize("user"); + } +} diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCred.java new file mode 100644 index 00000000..790a05eb --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCred.java @@ -0,0 +1,60 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.common.collect.ImmutableList; +import com.google.protobuf.util.JsonFormat; +// [START chat_CreateMembershipUserCred] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.CreateMembershipRequest; +import com.google.chat.v1.Membership; +import com.google.chat.v1.SpaceName; +import com.google.chat.v1.User; + +// This sample shows how to create membership with user credential for a human +// user. +public class CreateMembershipUserCred { + + private static final String SCOPE = + "https://www.googleapis.com/auth/chat.memberships"; + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithUserCredentials( + ImmutableList.of(SCOPE))) { + CreateMembershipRequest request = + CreateMembershipRequest.newBuilder() + // replace SPACE_NAME here + .setParent("spaces/SPACE_NAME") + .setMembership( + Membership.newBuilder() + .setMember( + User.newBuilder() + // replace USER_NAME here + .setName("users/USER_NAME") + // user type for the membership + .setType(User.Type.HUMAN) + .build()) + .build()) + .build(); + Membership response = chatServiceClient.createMembership(request); + + System.out.println(JsonFormat.printer().print(response)); + } + } +} +// [END chat_CreateMembershipUserCred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCredForApp.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCredForApp.java new file mode 100644 index 00000000..e751f20b --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCredForApp.java @@ -0,0 +1,60 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.common.collect.ImmutableList; +import com.google.protobuf.util.JsonFormat; +// [START chat_CreateMembershipUserCredForApp] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.CreateMembershipRequest; +import com.google.chat.v1.Membership; +import com.google.chat.v1.SpaceName; +import com.google.chat.v1.User; + +// This sample shows how to create membership with user credential for the +// calling app. +public class CreateMembershipUserCredForApp { + + private static final String SCOPE = + "https://www.googleapis.com/auth/chat.memberships.app"; + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithUserCredentials( + ImmutableList.of(SCOPE))) { + CreateMembershipRequest request = + CreateMembershipRequest.newBuilder() + // replace SPACE_NAME here + .setParent("spaces/SPACE_NAME") + .setMembership( + Membership.newBuilder() + .setMember( + User.newBuilder() + // member name for app membership, do not change this. + .setName("users/app") + // user type for the membership + .setType(User.Type.BOT) + .build()) + .build()) + .build(); + Membership response = chatServiceClient.createMembership(request); + + System.out.println(JsonFormat.printer().print(response)); + } + } +} +// [END chat_CreateMembershipUserCredForApp] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCred.java new file mode 100644 index 00000000..24b85bca --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCred.java @@ -0,0 +1,46 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.protobuf.util.JsonFormat; +// [START chat_CreateMessageAppCred] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.CreateMessageRequest; +import com.google.chat.v1.Message; + +// This sample shows how to create message with app credential. +public class CreateMessageAppCred { + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithAppCredentials()) { + CreateMessageRequest request = + CreateMessageRequest.newBuilder() + // Replace SPACE_NAME here. + .setParent("spaces/SPACE_NAME") + .setMessage( + Message.newBuilder() + .setText("Hello with app credentials!") + .build()) + .build(); + Message response = chatServiceClient.createMessage(request); + + System.out.println(JsonFormat.printer().print(response)); + } + } +} +// [END chat_CreateMessageAppCred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCredAtMention.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCredAtMention.java new file mode 100644 index 00000000..b8fb8291 --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCredAtMention.java @@ -0,0 +1,50 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.protobuf.util.JsonFormat; +// [START chat_CreateMessageAppCredAtMention] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.CreateMessageRequest; +import com.google.chat.v1.Message; + +// This sample shows how to create message that mentions a user with app +// credential. +public class CreateMessageAppCredAtMention { + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithAppCredentials()) { + CreateMessageRequest request = + CreateMessageRequest.newBuilder() + // Replace SPACE_NAME here. + .setParent("spaces/SPACE_NAME") + .setMessage( + Message.newBuilder() + // The user with USER_NAME will be mentioned if they are in the + // space. + // Replace USER_NAME here + .setText("Hello !") + .build()) + .build(); + Message response = chatServiceClient.createMessage(request); + + System.out.println(JsonFormat.printer().print(response)); + } + } +} +// [END chat_CreateMessageAppCredAtMention] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCredWithCards.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCredWithCards.java new file mode 100644 index 00000000..c47e3169 --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCredWithCards.java @@ -0,0 +1,66 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.protobuf.util.JsonFormat; +// [START chat_CreateMessageAppCredWithCards] +import com.google.apps.card.v1.Card; +import com.google.apps.card.v1.Card.CardHeader; +import com.google.apps.card.v1.Card.Section; +import com.google.apps.card.v1.TextParagraph; +import com.google.apps.card.v1.Widget; +import com.google.chat.v1.CardWithId; +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.CreateMessageRequest; +import com.google.chat.v1.Message; + +// This sample shows how to create message with a card with app credential. +public class CreateMessageAppCredWithCards { + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithAppCredentials()) { + CreateMessageRequest request = + CreateMessageRequest.newBuilder() + // Replace SPACE_NAME here. + .setParent("spaces/SPACE_NAME") + .setMessage( + Message.newBuilder() + .setText("Hello with app credentials!") + .addCardsV2( + CardWithId.newBuilder().setCard( + Card.newBuilder() + .addSections( + Section.newBuilder() + .addWidgets( + Widget.newBuilder() + .setTextParagraph( + TextParagraph.newBuilder().setText("Hello")) + .build()) + .build()) + .build() + ) + ) + .build()) + .build(); + Message response = chatServiceClient.createMessage(request); + + System.out.println(JsonFormat.printer().print(response)); + } + } +} +// [END chat_CreateMessageAppCredWithCards] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCred.java new file mode 100644 index 00000000..fe08c4b1 --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCred.java @@ -0,0 +1,52 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.common.collect.ImmutableList; +import com.google.protobuf.util.JsonFormat; +// [START chat_CreateMessageUserCred] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.CreateMessageRequest; +import com.google.chat.v1.Message; + +// This sample shows how to create message with user credential. +public class CreateMessageUserCred { + + private static final String SCOPE = + "https://www.googleapis.com/auth/chat.messages.create"; + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithUserCredentials( + ImmutableList.of(SCOPE))) { + CreateMessageRequest request = + CreateMessageRequest.newBuilder() + // Replace SPACE_NAME here. + .setParent("spaces/SPACE_NAME") + .setMessage( + Message + .newBuilder() + .setText("Hello with user credentials!") + .build()) + .build(); + Message response = chatServiceClient.createMessage(request); + + System.out.println(JsonFormat.printer().print(response)); + } + } +} +// [END chat_CreateMessageUserCred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithMessageId.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithMessageId.java new file mode 100644 index 00000000..0e37bbe3 --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithMessageId.java @@ -0,0 +1,56 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.common.collect.ImmutableList; +import com.google.protobuf.util.JsonFormat; +// [START chat_CreateMessageUserCredWithMessageId] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.CreateMessageRequest; +import com.google.chat.v1.Message; + +// This sample shows how to create message with message id specified with user +// credential. +public class CreateMessageUserCredWithMessageId { + + private static final String SCOPE = + "https://www.googleapis.com/auth/chat.messages.create"; + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithUserCredentials( + ImmutableList.of(SCOPE))) { + CreateMessageRequest request = + CreateMessageRequest.newBuilder() + // Replace SPACE_NAME here. + .setParent("spaces/SPACE_NAME") + .setMessage( + Message.newBuilder() + .setText("Hello with user credentials!") + .build()) + // Message ID lets chat apps get, update or delete a message without + // needing to store the system assigned ID in the message's resource + // name. + .setMessageId("client-MESSAGE-ID") + .build(); + Message response = chatServiceClient.createMessage(request); + + System.out.println(JsonFormat.printer().print(response)); + } + } +} +// [END chat_CreateMessageUserCredWithMessageId] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithRequestId.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithRequestId.java new file mode 100644 index 00000000..fe46232a --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithRequestId.java @@ -0,0 +1,55 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.common.collect.ImmutableList; +import com.google.protobuf.util.JsonFormat; +// [START chat_CreateMessageUserCredWithRequestId] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.CreateMessageRequest; +import com.google.chat.v1.Message; + +// This sample shows how to create message with request id specified with user +// credential. +public class CreateMessageUserCredWithRequestId { + + private static final String SCOPE = + "https://www.googleapis.com/auth/chat.messages.create"; + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithUserCredentials( + ImmutableList.of(SCOPE))) { + CreateMessageRequest request = + CreateMessageRequest.newBuilder() + // Replace SPACE_NAME here. + .setParent("spaces/SPACE_NAME") + .setMessage( + Message.newBuilder() + .setText("Hello with user credentials!") + .build()) + // Specifying an existing request ID returns the message created with + // that ID instead of creating a new message. + .setRequestId("REQUEST_ID") + .build(); + Message response = chatServiceClient.createMessage(request); + + System.out.println(JsonFormat.printer().print(response)); + } + } +} +// [END chat_CreateMessageUserCredWithRequestId] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithThreadKey.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithThreadKey.java new file mode 100644 index 00000000..40aa327f --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithThreadKey.java @@ -0,0 +1,61 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.common.collect.ImmutableList; +import com.google.protobuf.util.JsonFormat; +// [START chat_CreateMessageUserCredWithThreadKey] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.CreateMessageRequest; +import com.google.chat.v1.CreateMessageRequest.MessageReplyOption; +import com.google.chat.v1.Message; +import com.google.chat.v1.Thread; + +// This sample shows how to create message with a thread key with user +// credential. +public class CreateMessageUserCredWithThreadKey { + + private static final String SCOPE = + "https://www.googleapis.com/auth/chat.messages.create"; + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithUserCredentials( + ImmutableList.of(SCOPE))) { + CreateMessageRequest request = + CreateMessageRequest.newBuilder() + // Replace SPACE_NAME here. + .setParent("spaces/SPACE_NAME") + // Creates the message as a reply to the thread specified by thread_key. + // If it fails, the message starts a new thread instead. + .setMessageReplyOption( + MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD) + .setMessage( + Message.newBuilder() + .setText("Hello with user credentials!") + // Thread key specifies a thread and is unique to the chat app + // that sets it. + .setThread(Thread.newBuilder().setThreadKey("THREAD_KEY").build()) + .build()) + .build(); + Message response = chatServiceClient.createMessage(request); + + System.out.println(JsonFormat.printer().print(response)); + } + } +} +// [END chat_CreateMessageUserCredWithThreadKey] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithThreadName.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithThreadName.java new file mode 100644 index 00000000..3c8f10c5 --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithThreadName.java @@ -0,0 +1,62 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.common.collect.ImmutableList; +import com.google.protobuf.util.JsonFormat; +// [START chat_CreateMessageUserCredWithThreadName] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.CreateMessageRequest; +import com.google.chat.v1.CreateMessageRequest.MessageReplyOption; +import com.google.chat.v1.Message; +import com.google.chat.v1.Thread; + +// This sample shows how to create message with thread name specified with user +// credential. +public class CreateMessageUserCredWithThreadName { + + private static final String SCOPE = + "https://www.googleapis.com/auth/chat.messages.create"; + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithUserCredentials( + ImmutableList.of(SCOPE))) { + CreateMessageRequest request = + CreateMessageRequest.newBuilder() + // Replace SPACE_NAME here. + .setParent("spaces/SPACE_NAME") + // Creates the message as a reply to the thread specified by thread name. + // If it fails, the message starts a new thread instead. + .setMessageReplyOption( + MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD) + .setMessage( + Message.newBuilder() + .setText("Hello with user credentials!") + // Resource name of a thread that uniquely identify a thread. + .setThread(Thread.newBuilder().setName( + // replace SPACE_NAME and THREAD_NAME here + "spaces/SPACE_NAME/threads/THREAD_NAME").build()) + .build()) + .build(); + Message response = chatServiceClient.createMessage(request); + + System.out.println(JsonFormat.printer().print(response)); + } + } +} +// [END chat_CreateMessageUserCredWithThreadName] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/DeleteMessageAppCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/DeleteMessageAppCred.java new file mode 100644 index 00000000..66e44af8 --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/DeleteMessageAppCred.java @@ -0,0 +1,38 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +// [START chat_DeleteMessageAppCred] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.DeleteMessageRequest; + +// This sample shows how to delete message with app credential. +public class DeleteMessageAppCred { + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithAppCredentials()) { + DeleteMessageRequest request = + DeleteMessageRequest.newBuilder() + // replace SPACE_NAME and MESSAGE_NAME here + .setName("spaces/SPACE_NAME/messages/MESSAGE_NAME") + .build(); + chatServiceClient.deleteMessage(request); + } + } +} +// [END chat_DeleteMessageAppCred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/DeleteMessageUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/DeleteMessageUserCred.java new file mode 100644 index 00000000..43f7f713 --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/DeleteMessageUserCred.java @@ -0,0 +1,44 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.common.collect.ImmutableList; +// [START chat_DeleteMessageUserCred] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.DeleteMessageRequest; +import com.google.chat.v1.SpaceName; + +// This sample shows how to delete message with user credential. +public class DeleteMessageUserCred { + + private static final String SCOPE = + "https://www.googleapis.com/auth/chat.messages"; + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithUserCredentials( + ImmutableList.of(SCOPE))) { + DeleteMessageRequest request = + DeleteMessageRequest.newBuilder() + // replace SPACE_NAME and MESSAGE_NAME here + .setName("spaces/SPACE_NAME/messages/MESSAGE_NAME") + .build(); + chatServiceClient.deleteMessage(request); + } + } +} +// [END chat_DeleteMessageUserCred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMembershipAppCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMembershipAppCred.java new file mode 100644 index 00000000..fd5bb8ca --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMembershipAppCred.java @@ -0,0 +1,42 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.protobuf.util.JsonFormat; +// [START chat_GetMembershipAppCred] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.GetMembershipRequest; +import com.google.chat.v1.Membership; + +// This sample shows how to get membership with app credential. +public class GetMembershipAppCred { + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithAppCredentials()) { + GetMembershipRequest request = + GetMembershipRequest.newBuilder() + // replace SPACE_NAME and MEMBERSHIP_NAME here + .setName("spaces/SPACE_NAME/members/MEMBERSHIP_NAME") + .build(); + Membership response = chatServiceClient.getMembership(request); + + System.out.println(JsonFormat.printer().print(response)); + } + } +} +// [END chat_GetMembershipAppCred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMembershipUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMembershipUserCred.java new file mode 100644 index 00000000..d4cb18d5 --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMembershipUserCred.java @@ -0,0 +1,47 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.common.collect.ImmutableList; +import com.google.protobuf.util.JsonFormat; +// [START chat_GetMembershipUserCred] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.GetMembershipRequest; +import com.google.chat.v1.Membership; + +// This sample shows how to get membership with user credential. +public class GetMembershipUserCred { + + private static final String SCOPE = + "https://www.googleapis.com/auth/chat.memberships.readonly"; + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithUserCredentials( + ImmutableList.of(SCOPE))) { + GetMembershipRequest request = + GetMembershipRequest.newBuilder() + // replace SPACE_NAME and MEMBERSHIP_NAME here + .setName("spaces/SPACE_NAME/members/MEMBERSHIP_NAME") + .build(); + Membership response = chatServiceClient.getMembership(request); + + System.out.println(JsonFormat.printer().print(response)); + } + } +} +// [END chat_GetMembershipUserCred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageAppCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageAppCred.java new file mode 100644 index 00000000..c505680e --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageAppCred.java @@ -0,0 +1,42 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.protobuf.util.JsonFormat; +// [START chat_GetMessageAppCred] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.GetMessageRequest; +import com.google.chat.v1.Message; + +// This sample shows how to get message with app credential. +public class GetMessageAppCred { + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithAppCredentials()) { + GetMessageRequest request = + GetMessageRequest.newBuilder() + // replace SPACE_NAME and MESSAGE_NAME here + .setName("spaces/SPACE_NAME/members/MESSAGE_NAME") + .build(); + Message response = chatServiceClient.getMessage(request); + + System.out.println(JsonFormat.printer().print(response)); + } + } +} +// [END chat_GetMessageAppCred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageUserCred.java new file mode 100644 index 00000000..e58872d6 --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageUserCred.java @@ -0,0 +1,47 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.common.collect.ImmutableList; +import com.google.protobuf.util.JsonFormat; +// [START chat_GetMessageUserCred] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.GetMessageRequest; +import com.google.chat.v1.Message; + +// This sample shows how to get message with user credential. +public class GetMessageUserCred { + + private static final String SCOPE = + "https://www.googleapis.com/auth/chat.messages.readonly"; + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithUserCredentials( + ImmutableList.of(SCOPE))) { + GetMessageRequest request = + GetMessageRequest.newBuilder() + // replace SPACE_NAME and MESSAGE_NAME here + .setName("spaces/SPACE_NAME/members/MESSAGE_NAME") + .build(); + Message response = chatServiceClient.getMessage(request); + + System.out.println(JsonFormat.printer().print(response)); + } + } +} +// [END chat_GetMessageUserCred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetSpaceAppCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetSpaceAppCred.java new file mode 100644 index 00000000..df5da3d4 --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetSpaceAppCred.java @@ -0,0 +1,42 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.protobuf.util.JsonFormat; +// [START chat_GetSpaceAppCred] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.GetSpaceRequest; +import com.google.chat.v1.Space; + +// This sample shows how to get space with app credential. +public class GetSpaceAppCred { + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithAppCredentials()) { + GetSpaceRequest request = + GetSpaceRequest.newBuilder() + // Replace SPACE_NAME here + .setName("spaces/SPACE_NAME") + .build(); + Space response = chatServiceClient.getSpace(request); + + System.out.println(JsonFormat.printer().print(response)); + } + } +} +// [END chat_GetSpaceAppCred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetSpaceUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetSpaceUserCred.java new file mode 100644 index 00000000..e9ed0a45 --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetSpaceUserCred.java @@ -0,0 +1,47 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.common.collect.ImmutableList; +import com.google.protobuf.util.JsonFormat; +// [START chat_GetSpaceUserCred] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.GetSpaceRequest; +import com.google.chat.v1.Space; + +// This sample shows how to get space with user credential. +public class GetSpaceUserCred { + + private static final String SCOPE = + "https://www.googleapis.com/auth/chat.spaces.readonly"; + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithUserCredentials( + ImmutableList.of(SCOPE))) { + GetSpaceRequest request = + GetSpaceRequest.newBuilder() + // Replace SPACE_NAME here + .setName("spaces/SPACE_NAME") + .build(); + Space response = chatServiceClient.getSpace(request); + + System.out.println(JsonFormat.printer().print(response)); + } + } +} +// [END chat_GetSpaceUserCred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsAppCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsAppCred.java new file mode 100644 index 00000000..cae23771 --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsAppCred.java @@ -0,0 +1,51 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.protobuf.util.JsonFormat; +// [START chat_ListMembershipsAppCred] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.ListMembershipsRequest; +import com.google.chat.v1.ListMembershipsResponse; +import com.google.chat.v1.Membership; + +// This sample shows how to list memberships with app credential. +public class ListMembershipsAppCred { + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithAppCredentials()) { + ListMembershipsRequest request = + ListMembershipsRequest.newBuilder() + // Replace SPACE_NAME here. + .setParent("spaces/SPACE_NAME") + // Filter membership by type (HUMAN or BOT) or role + // (ROLE_MEMBER or ROLE_MANAGER). + .setFilter("member.type = \"HUMAN\"") + // Number of results that will be returned at once. + .setPageSize(10) + .build(); + + // Iterate over results and resolve additional pages automatically. + for (Membership response : + chatServiceClient.listMemberships(request).iterateAll()) { + System.out.println(JsonFormat.printer().print(response)); + } + } + } +} +// [END chat_ListMembershipsAppCred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsUserCred.java new file mode 100644 index 00000000..d60e2725 --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsUserCred.java @@ -0,0 +1,56 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.common.collect.ImmutableList; +import com.google.protobuf.util.JsonFormat; +// [START chat_ListMembershipsUserCred] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.ListMembershipsRequest; +import com.google.chat.v1.ListMembershipsResponse; +import com.google.chat.v1.Membership; + +// This sample shows how to list memberships with user credential. +public class ListMembershipsUserCred { + + private static final String SCOPE = + "https://www.googleapis.com/auth/chat.memberships.readonly"; + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithUserCredentials( + ImmutableList.of(SCOPE))) { + ListMembershipsRequest request = + ListMembershipsRequest.newBuilder() + // Replace SPACE_NAME here. + .setParent("spaces/SPACE_NAME") + // Filter membership by type (HUMAN or BOT) or role + // (ROLE_MEMBER or ROLE_MANAGER). + .setFilter("member.type = \"HUMAN\"") + // Number of results that will be returned at once. + .setPageSize(10) + .build(); + + // Iterating over results and resolve additional pages automatically. + for (Membership response : + chatServiceClient.listMemberships(request).iterateAll()) { + System.out.println(JsonFormat.printer().print(response)); + } + } + } +} +// [END chat_ListMembershipsUserCred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMessagesUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMessagesUserCred.java new file mode 100644 index 00000000..1a984607 --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMessagesUserCred.java @@ -0,0 +1,53 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.common.collect.ImmutableList; +import com.google.protobuf.util.JsonFormat; +// [START chat_ListMessagesUserCred] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.ListMessagesRequest; +import com.google.chat.v1.ListMessagesResponse; +import com.google.chat.v1.Message; + +// This sample shows how to list messages with user credential. +public class ListMessagesUserCred { + + private static final String SCOPE = + "https://www.googleapis.com/auth/chat.messages.readonly"; + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithUserCredentials( + ImmutableList.of(SCOPE))) { + ListMessagesRequest request = + ListMessagesRequest.newBuilder() + // Replace SPACE_NAME here. + .setParent("spaces/SPACE_NAME") + // Number of results that will be returned at once. + .setPageSize(10) + .build(); + + // Iterate over results and resolve additional pages automatically. + for (Message response : + chatServiceClient.listMessages(request).iterateAll()) { + System.out.println(JsonFormat.printer().print(response)); + } + } + } +} +// [END chat_ListMessagesUserCred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesAppCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesAppCred.java new file mode 100644 index 00000000..00494729 --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesAppCred.java @@ -0,0 +1,49 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.protobuf.util.JsonFormat; +// [START chat_ListSpacesAppCred] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.ListSpacesRequest; +import com.google.chat.v1.ListSpacesResponse; +import com.google.chat.v1.Space; + +// This sample shows how to list spaces with app credential. +public class ListSpacesAppCred { + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithAppCredentials()) { + ListSpacesRequest request = + ListSpacesRequest.newBuilder() + // Filter spaces by space type (SPACE or GROUP_CHAT or + // DIRECT_MESSAGE). + .setFilter("spaceType = \"SPACE\"") + // Number of results that will be returned at once. + .setPageSize(10) + .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_ListSpacesAppCred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesUserCred.java new file mode 100644 index 00000000..2d9410aa --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesUserCred.java @@ -0,0 +1,54 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.common.collect.ImmutableList; +import com.google.protobuf.util.JsonFormat; +// [START chat_ListSpacesUserCred] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.ListSpacesRequest; +import com.google.chat.v1.ListSpacesResponse; +import com.google.chat.v1.Space; + +// This sample shows how to list spaces with user credential. +public class ListSpacesUserCred{ + + private static final String SCOPE = + "https://www.googleapis.com/auth/chat.spaces.readonly"; + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithUserCredentials( + ImmutableList.of(SCOPE))) { + ListSpacesRequest request = + ListSpacesRequest.newBuilder() + // Filter spaces by space type (SPACE or GROUP_CHAT or + // DIRECT_MESSAGE). + .setFilter("spaceType = \"SPACE\"") + // Number of results that will be returned at once. + .setPageSize(10) + .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_ListSpacesUserCred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageAppCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageAppCred.java new file mode 100644 index 00000000..5f946545 --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageAppCred.java @@ -0,0 +1,51 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.protobuf.util.JsonFormat; +// [START chat_UpdateMessageAppCred] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.UpdateMessageRequest; +import com.google.chat.v1.Message; +import com.google.protobuf.FieldMask; + +// This sample shows how to update message with app credential. +public class UpdateMessageAppCred { + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithAppCredentials()) { + UpdateMessageRequest request = + UpdateMessageRequest.newBuilder() + .setMessage( + Message.newBuilder() + // replace SPACE_NAME and MESSAGE_NAME here + .setName("spaces/SPACE_NAME/messages/MESSAGE_NAME") + .setText("Updated with app credential!") + .build() + ) + .setUpdateMask( + // The field paths to update. + FieldMask.newBuilder().addPaths("text").build()) + .build(); + Message response = chatServiceClient.updateMessage(request); + + System.out.println(JsonFormat.printer().print(response)); + } + } +} +// [END chat_UpdateMessageAppCred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageUserCred.java new file mode 100644 index 00000000..9f2dd016 --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageUserCred.java @@ -0,0 +1,56 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.common.collect.ImmutableList; +import com.google.protobuf.util.JsonFormat; +// [START chat_UpdateMessageUserCred] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.UpdateMessageRequest; +import com.google.chat.v1.Message; +import com.google.protobuf.FieldMask; + +// This sample shows how to update message with user credential. +public class UpdateMessageUserCred { + + private static final String SCOPE = + "https://www.googleapis.com/auth/chat.messages"; + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithUserCredentials( + ImmutableList.of(SCOPE))) { + UpdateMessageRequest request = + UpdateMessageRequest.newBuilder() + .setMessage( + Message.newBuilder() + // replace SPACE_NAME and MESSAGE_NAME here + .setName("spaces/SPACE_NAME/messages/MESSAGE_NAME") + .setText("Updated with user credential!") + .build() + ) + .setUpdateMask( + // The field paths to update. + FieldMask.newBuilder().addPaths("text").build()) + .build(); + Message response = chatServiceClient.updateMessage(request); + + System.out.println(JsonFormat.printer().print(response)); + } + } +} +// [END chat_UpdateMessageUserCred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateSpaceUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateSpaceUserCred.java new file mode 100644 index 00000000..cd5d67cd --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateSpaceUserCred.java @@ -0,0 +1,56 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.common.collect.ImmutableList; +import com.google.protobuf.util.JsonFormat; +// [START chat_UpdateSpaceUserCred] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.UpdateSpaceRequest; +import com.google.chat.v1.Space; +import com.google.protobuf.FieldMask; + +// This sample shows how to update space with user credential. +public class UpdateSpaceUserCred { + + private static final String SCOPE = + "https://www.googleapis.com/auth/chat.spaces"; + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithUserCredentials( + ImmutableList.of(SCOPE))) { + UpdateSpaceRequest request = + UpdateSpaceRequest.newBuilder() + .setSpace( + Space.newBuilder() + // Replace SPACE_NAME here. + .setName("spaces/SPACE_NAME") + .setDisplayName("New space display name") + .build() + ) + .setUpdateMask( + // The field paths to update. + FieldMask.newBuilder().addPaths("display_name").build()) + .build(); + Space response = chatServiceClient.updateSpace(request); + + System.out.println(JsonFormat.printer().print(response)); + } + } +} +// [END chat_UpdateSpaceUserCred] From 22656cb15988abaf546e5606e0f4cc47ac6d8e18 Mon Sep 17 00:00:00 2001 From: Pierrick Voulet <6769971+PierrickVoulet@users.noreply.github.com> Date: Wed, 21 Aug 2024 13:45:07 -0400 Subject: [PATCH 09/19] feat: update GAPIC samples to be featured in create message guide (#1092) * feat: update GAPIC samples to be featured in create message guide * Fix style --------- Co-authored-by: pierrick --- .../chat/samples/CreateMessageAppCred.java | 60 ++++++++++++++--- .../CreateMessageAppCredWithCards.java | 66 ------------------- .../chat/samples/CreateMessageUserCred.java | 20 +++--- 3 files changed, 63 insertions(+), 83 deletions(-) delete mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCredWithCards.java diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCred.java index 24b85bca..c17303f2 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCred.java @@ -18,6 +18,19 @@ import com.google.protobuf.util.JsonFormat; // [START chat_CreateMessageAppCred] +import com.google.apps.card.v1.Button; +import com.google.apps.card.v1.ButtonList; +import com.google.apps.card.v1.Card; +import com.google.apps.card.v1.Icon; +import com.google.apps.card.v1.MaterialIcon; +import com.google.apps.card.v1.OnClick; +import com.google.apps.card.v1.OpenLink; +import com.google.apps.card.v1.TextParagraph; +import com.google.apps.card.v1.Widget; +import com.google.apps.card.v1.Card.CardHeader; +import com.google.apps.card.v1.Card.Section; +import com.google.chat.v1.AccessoryWidget; +import com.google.chat.v1.CardWithId; import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.CreateMessageRequest; import com.google.chat.v1.Message; @@ -28,16 +41,47 @@ public class CreateMessageAppCred { public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithAppCredentials()) { - CreateMessageRequest request = - CreateMessageRequest.newBuilder() + CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder() // Replace SPACE_NAME here. .setParent("spaces/SPACE_NAME") - .setMessage( - Message.newBuilder() - .setText("Hello with app credentials!") - .build()) - .build(); - Message response = chatServiceClient.createMessage(request); + .setMessage(Message.newBuilder() + .setText( "👋🌎 Hello world! I created this message by calling " + + "the Chat API\'s `messages.create()` method.") + .addCardsV2(CardWithId.newBuilder().setCard(Card.newBuilder() + .setHeader(CardHeader.newBuilder() + .setTitle("About this message") + .setImageUrl("https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg")) + .addSections(Section.newBuilder() + .setHeader("Contents") + .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText( + "🔡 Text which can include " + + "hyperlinks 🔗, emojis 😄🎉, and @mentions 🗣️."))) + .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText( + "🖼️ A card to display visual elements " + + "and request information such as text 🔤, " + + "dates and times 📅, and selections ☑️."))) + .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText( + "👉🔘 An accessory widget which adds " + + "a button to the bottom of a message.")))) + .addSections(Section.newBuilder() + .setHeader("What's next") + .setCollapsible(true) + .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText( + "❤️ Add a reaction."))) + .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText( + "🔄 Update " + + "or ❌ delete " + + "the message.")))))) + .addAccessoryWidgets(AccessoryWidget.newBuilder() + .setButtonList(ButtonList.newBuilder() + .addButtons(Button.newBuilder() + .setText("View documentation") + .setIcon(Icon.newBuilder() + .setMaterialIcon(MaterialIcon.newBuilder().setName("link"))) + .setOnClick(OnClick.newBuilder() + .setOpenLink(OpenLink.newBuilder() + .setUrl("https://developers.google.com/workspace/chat/create-messages"))))))); + Message response = chatServiceClient.createMessage(request.build()); System.out.println(JsonFormat.printer().print(response)); } diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCredWithCards.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCredWithCards.java deleted file mode 100644 index c47e3169..00000000 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCredWithCards.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * 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 - * - * https://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. - */ - -package com.google.workspace.api.chat.samples; - -import com.google.protobuf.util.JsonFormat; -// [START chat_CreateMessageAppCredWithCards] -import com.google.apps.card.v1.Card; -import com.google.apps.card.v1.Card.CardHeader; -import com.google.apps.card.v1.Card.Section; -import com.google.apps.card.v1.TextParagraph; -import com.google.apps.card.v1.Widget; -import com.google.chat.v1.CardWithId; -import com.google.chat.v1.ChatServiceClient; -import com.google.chat.v1.CreateMessageRequest; -import com.google.chat.v1.Message; - -// This sample shows how to create message with a card with app credential. -public class CreateMessageAppCredWithCards { - - public static void main(String[] args) throws Exception { - try (ChatServiceClient chatServiceClient = - AuthenticationUtils.createClientWithAppCredentials()) { - CreateMessageRequest request = - CreateMessageRequest.newBuilder() - // Replace SPACE_NAME here. - .setParent("spaces/SPACE_NAME") - .setMessage( - Message.newBuilder() - .setText("Hello with app credentials!") - .addCardsV2( - CardWithId.newBuilder().setCard( - Card.newBuilder() - .addSections( - Section.newBuilder() - .addWidgets( - Widget.newBuilder() - .setTextParagraph( - TextParagraph.newBuilder().setText("Hello")) - .build()) - .build()) - .build() - ) - ) - .build()) - .build(); - Message response = chatServiceClient.createMessage(request); - - System.out.println(JsonFormat.printer().print(response)); - } - } -} -// [END chat_CreateMessageAppCredWithCards] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCred.java index fe08c4b1..fa53ed57 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCred.java @@ -33,17 +33,19 @@ public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithUserCredentials( ImmutableList.of(SCOPE))) { - CreateMessageRequest request = - CreateMessageRequest.newBuilder() + CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder() // Replace SPACE_NAME here. .setParent("spaces/SPACE_NAME") - .setMessage( - Message - .newBuilder() - .setText("Hello with user credentials!") - .build()) - .build(); - Message response = chatServiceClient.createMessage(request); + .setMessage(Message.newBuilder() + .setText( "👋🌎 Hello world!" + + "Text messages can contain things like:\n\n" + + "* Hyperlinks 🔗\n" + + "* Emojis 😄🎉\n" + + "* Mentions of other Chat users `@` \n\n" + + "For details, see the " + + ".")); + Message response = chatServiceClient.createMessage(request.build()); System.out.println(JsonFormat.printer().print(response)); } From 9d94f3a5d98ae8544f6b6ac20b1e8d564735fb9d Mon Sep 17 00:00:00 2001 From: Pierrick Voulet <6769971+PierrickVoulet@users.noreply.github.com> Date: Wed, 21 Aug 2024 16:24:44 -0400 Subject: [PATCH 10/19] feat: fix style for builders (#1093) Co-authored-by: pierrick --- .../samples/CreateMembershipUserCred.java | 26 +++++++------------ .../CreateMembershipUserCredForApp.java | 26 +++++++------------ .../CreateMessageAppCredAtMention.java | 18 +++++-------- .../CreateMessageUserCredWithMessageId.java | 14 ++++------ .../CreateMessageUserCredWithRequestId.java | 14 ++++------ .../CreateMessageUserCredWithThreadKey.java | 20 ++++++-------- .../CreateMessageUserCredWithThreadName.java | 22 +++++++--------- .../chat/samples/DeleteMessageAppCred.java | 10 +++---- .../chat/samples/DeleteMessageUserCred.java | 10 +++---- .../chat/samples/GetMembershipAppCred.java | 10 +++---- .../chat/samples/GetMembershipUserCred.java | 10 +++---- .../api/chat/samples/GetMessageAppCred.java | 10 +++---- .../api/chat/samples/GetMessageUserCred.java | 10 +++---- .../api/chat/samples/GetSpaceAppCred.java | 8 +++--- .../api/chat/samples/GetSpaceUserCred.java | 8 +++--- .../chat/samples/ListMembershipsAppCred.java | 20 +++++++------- .../chat/samples/ListMembershipsUserCred.java | 20 +++++++------- .../chat/samples/ListMessagesUserCred.java | 14 +++++----- .../api/chat/samples/ListSpacesAppCred.java | 16 +++++------- .../api/chat/samples/ListSpacesUserCred.java | 16 +++++------- .../chat/samples/UpdateMessageAppCred.java | 23 +++++++--------- .../chat/samples/UpdateMessageUserCred.java | 23 +++++++--------- .../api/chat/samples/UpdateSpaceUserCred.java | 23 +++++++--------- 23 files changed, 149 insertions(+), 222 deletions(-) diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCred.java index 790a05eb..c04b15fc 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCred.java @@ -36,22 +36,16 @@ public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithUserCredentials( ImmutableList.of(SCOPE))) { - CreateMembershipRequest request = - CreateMembershipRequest.newBuilder() - // replace SPACE_NAME here - .setParent("spaces/SPACE_NAME") - .setMembership( - Membership.newBuilder() - .setMember( - User.newBuilder() - // replace USER_NAME here - .setName("users/USER_NAME") - // user type for the membership - .setType(User.Type.HUMAN) - .build()) - .build()) - .build(); - Membership response = chatServiceClient.createMembership(request); + CreateMembershipRequest.Builder request = CreateMembershipRequest.newBuilder() + // replace SPACE_NAME here + .setParent("spaces/SPACE_NAME") + .setMembership(Membership.newBuilder() + .setMember(User.newBuilder() + // replace USER_NAME here + .setName("users/USER_NAME") + // user type for the membership + .setType(User.Type.HUMAN))); + Membership response = chatServiceClient.createMembership(request.build()); System.out.println(JsonFormat.printer().print(response)); } diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCredForApp.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCredForApp.java index e751f20b..3edb889d 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCredForApp.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCredForApp.java @@ -36,22 +36,16 @@ public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithUserCredentials( ImmutableList.of(SCOPE))) { - CreateMembershipRequest request = - CreateMembershipRequest.newBuilder() - // replace SPACE_NAME here - .setParent("spaces/SPACE_NAME") - .setMembership( - Membership.newBuilder() - .setMember( - User.newBuilder() - // member name for app membership, do not change this. - .setName("users/app") - // user type for the membership - .setType(User.Type.BOT) - .build()) - .build()) - .build(); - Membership response = chatServiceClient.createMembership(request); + CreateMembershipRequest.Builder request = CreateMembershipRequest.newBuilder() + // replace SPACE_NAME here + .setParent("spaces/SPACE_NAME") + .setMembership(Membership.newBuilder() + .setMember(User.newBuilder() + // member name for app membership, do not change this. + .setName("users/app") + // user type for the membership + .setType(User.Type.BOT))); + Membership response = chatServiceClient.createMembership(request.build()); System.out.println(JsonFormat.printer().print(response)); } diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCredAtMention.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCredAtMention.java index b8fb8291..5830de3c 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCredAtMention.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCredAtMention.java @@ -29,19 +29,15 @@ public class CreateMessageAppCredAtMention { public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithAppCredentials()) { - CreateMessageRequest request = - CreateMessageRequest.newBuilder() + CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder() // Replace SPACE_NAME here. .setParent("spaces/SPACE_NAME") - .setMessage( - Message.newBuilder() - // The user with USER_NAME will be mentioned if they are in the - // space. - // Replace USER_NAME here - .setText("Hello !") - .build()) - .build(); - Message response = chatServiceClient.createMessage(request); + .setMessage(Message.newBuilder() + // The user with USER_NAME will be mentioned if they are in the + // space. + // Replace USER_NAME here + .setText("Hello !")); + Message response = chatServiceClient.createMessage(request.build()); System.out.println(JsonFormat.printer().print(response)); } diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithMessageId.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithMessageId.java index 0e37bbe3..d76475c7 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithMessageId.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithMessageId.java @@ -34,20 +34,16 @@ public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithUserCredentials( ImmutableList.of(SCOPE))) { - CreateMessageRequest request = - CreateMessageRequest.newBuilder() + CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder() // Replace SPACE_NAME here. .setParent("spaces/SPACE_NAME") - .setMessage( - Message.newBuilder() - .setText("Hello with user credentials!") - .build()) + .setMessage(Message.newBuilder() + .setText("Hello with user credentials!")) // Message ID lets chat apps get, update or delete a message without // needing to store the system assigned ID in the message's resource // name. - .setMessageId("client-MESSAGE-ID") - .build(); - Message response = chatServiceClient.createMessage(request); + .setMessageId("client-MESSAGE-ID"); + Message response = chatServiceClient.createMessage(request.build()); System.out.println(JsonFormat.printer().print(response)); } diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithRequestId.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithRequestId.java index fe46232a..1d05d950 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithRequestId.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithRequestId.java @@ -34,19 +34,15 @@ public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithUserCredentials( ImmutableList.of(SCOPE))) { - CreateMessageRequest request = - CreateMessageRequest.newBuilder() + CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder() // Replace SPACE_NAME here. .setParent("spaces/SPACE_NAME") - .setMessage( - Message.newBuilder() - .setText("Hello with user credentials!") - .build()) + .setMessage(Message.newBuilder() + .setText("Hello with user credentials!")) // Specifying an existing request ID returns the message created with // that ID instead of creating a new message. - .setRequestId("REQUEST_ID") - .build(); - Message response = chatServiceClient.createMessage(request); + .setRequestId("REQUEST_ID"); + Message response = chatServiceClient.createMessage(request.build()); System.out.println(JsonFormat.printer().print(response)); } diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithThreadKey.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithThreadKey.java index 40aa327f..897df800 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithThreadKey.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithThreadKey.java @@ -36,23 +36,19 @@ public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithUserCredentials( ImmutableList.of(SCOPE))) { - CreateMessageRequest request = - CreateMessageRequest.newBuilder() + CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder() // Replace SPACE_NAME here. .setParent("spaces/SPACE_NAME") // Creates the message as a reply to the thread specified by thread_key. // If it fails, the message starts a new thread instead. .setMessageReplyOption( - MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD) - .setMessage( - Message.newBuilder() - .setText("Hello with user credentials!") - // Thread key specifies a thread and is unique to the chat app - // that sets it. - .setThread(Thread.newBuilder().setThreadKey("THREAD_KEY").build()) - .build()) - .build(); - Message response = chatServiceClient.createMessage(request); + MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD) + .setMessage(Message.newBuilder() + .setText("Hello with user credentials!") + // Thread key specifies a thread and is unique to the chat app + // that sets it. + .setThread(Thread.newBuilder().setThreadKey("THREAD_KEY"))); + Message response = chatServiceClient.createMessage(request.build()); System.out.println(JsonFormat.printer().print(response)); } diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithThreadName.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithThreadName.java index 3c8f10c5..69bfba1e 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithThreadName.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithThreadName.java @@ -36,24 +36,20 @@ public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithUserCredentials( ImmutableList.of(SCOPE))) { - CreateMessageRequest request = - CreateMessageRequest.newBuilder() + CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder() // Replace SPACE_NAME here. .setParent("spaces/SPACE_NAME") // Creates the message as a reply to the thread specified by thread name. // If it fails, the message starts a new thread instead. .setMessageReplyOption( - MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD) - .setMessage( - Message.newBuilder() - .setText("Hello with user credentials!") - // Resource name of a thread that uniquely identify a thread. - .setThread(Thread.newBuilder().setName( - // replace SPACE_NAME and THREAD_NAME here - "spaces/SPACE_NAME/threads/THREAD_NAME").build()) - .build()) - .build(); - Message response = chatServiceClient.createMessage(request); + MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD) + .setMessage(Message.newBuilder() + .setText("Hello with user credentials!") + // Resource name of a thread that uniquely identify a thread. + .setThread(Thread.newBuilder().setName( + // replace SPACE_NAME and THREAD_NAME here + "spaces/SPACE_NAME/threads/THREAD_NAME"))); + Message response = chatServiceClient.createMessage(request.build()); System.out.println(JsonFormat.printer().print(response)); } diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/DeleteMessageAppCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/DeleteMessageAppCred.java index 66e44af8..abda2ae1 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/DeleteMessageAppCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/DeleteMessageAppCred.java @@ -26,12 +26,10 @@ public class DeleteMessageAppCred { public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithAppCredentials()) { - DeleteMessageRequest request = - DeleteMessageRequest.newBuilder() - // replace SPACE_NAME and MESSAGE_NAME here - .setName("spaces/SPACE_NAME/messages/MESSAGE_NAME") - .build(); - chatServiceClient.deleteMessage(request); + DeleteMessageRequest.Builder request = DeleteMessageRequest.newBuilder() + // replace SPACE_NAME and MESSAGE_NAME here + .setName("spaces/SPACE_NAME/messages/MESSAGE_NAME"); + chatServiceClient.deleteMessage(request.build()); } } } diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/DeleteMessageUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/DeleteMessageUserCred.java index 43f7f713..491a3dd6 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/DeleteMessageUserCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/DeleteMessageUserCred.java @@ -32,12 +32,10 @@ public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithUserCredentials( ImmutableList.of(SCOPE))) { - DeleteMessageRequest request = - DeleteMessageRequest.newBuilder() - // replace SPACE_NAME and MESSAGE_NAME here - .setName("spaces/SPACE_NAME/messages/MESSAGE_NAME") - .build(); - chatServiceClient.deleteMessage(request); + DeleteMessageRequest.Builder request = DeleteMessageRequest.newBuilder() + // replace SPACE_NAME and MESSAGE_NAME here + .setName("spaces/SPACE_NAME/messages/MESSAGE_NAME"); + chatServiceClient.deleteMessage(request.build()); } } } diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMembershipAppCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMembershipAppCred.java index fd5bb8ca..fcd7ae69 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMembershipAppCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMembershipAppCred.java @@ -28,12 +28,10 @@ public class GetMembershipAppCred { public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithAppCredentials()) { - GetMembershipRequest request = - GetMembershipRequest.newBuilder() - // replace SPACE_NAME and MEMBERSHIP_NAME here - .setName("spaces/SPACE_NAME/members/MEMBERSHIP_NAME") - .build(); - Membership response = chatServiceClient.getMembership(request); + GetMembershipRequest.Builder request = GetMembershipRequest.newBuilder() + // replace SPACE_NAME and MEMBERSHIP_NAME here + .setName("spaces/SPACE_NAME/members/MEMBERSHIP_NAME"); + Membership response = chatServiceClient.getMembership(request.build()); System.out.println(JsonFormat.printer().print(response)); } diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMembershipUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMembershipUserCred.java index d4cb18d5..f54b8633 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMembershipUserCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMembershipUserCred.java @@ -33,12 +33,10 @@ public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithUserCredentials( ImmutableList.of(SCOPE))) { - GetMembershipRequest request = - GetMembershipRequest.newBuilder() - // replace SPACE_NAME and MEMBERSHIP_NAME here - .setName("spaces/SPACE_NAME/members/MEMBERSHIP_NAME") - .build(); - Membership response = chatServiceClient.getMembership(request); + GetMembershipRequest.Builder request = GetMembershipRequest.newBuilder() + // replace SPACE_NAME and MEMBERSHIP_NAME here + .setName("spaces/SPACE_NAME/members/MEMBERSHIP_NAME"); + Membership response = chatServiceClient.getMembership(request.build()); System.out.println(JsonFormat.printer().print(response)); } diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageAppCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageAppCred.java index c505680e..b80a28e9 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageAppCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageAppCred.java @@ -28,12 +28,10 @@ public class GetMessageAppCred { public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithAppCredentials()) { - GetMessageRequest request = - GetMessageRequest.newBuilder() - // replace SPACE_NAME and MESSAGE_NAME here - .setName("spaces/SPACE_NAME/members/MESSAGE_NAME") - .build(); - Message response = chatServiceClient.getMessage(request); + GetMessageRequest.Builder request = GetMessageRequest.newBuilder() + // replace SPACE_NAME and MESSAGE_NAME here + .setName("spaces/SPACE_NAME/members/MESSAGE_NAME"); + Message response = chatServiceClient.getMessage(request.build()); System.out.println(JsonFormat.printer().print(response)); } diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageUserCred.java index e58872d6..7db70657 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageUserCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageUserCred.java @@ -33,12 +33,10 @@ public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithUserCredentials( ImmutableList.of(SCOPE))) { - GetMessageRequest request = - GetMessageRequest.newBuilder() - // replace SPACE_NAME and MESSAGE_NAME here - .setName("spaces/SPACE_NAME/members/MESSAGE_NAME") - .build(); - Message response = chatServiceClient.getMessage(request); + GetMessageRequest.Builder request = GetMessageRequest.newBuilder() + // replace SPACE_NAME and MESSAGE_NAME here + .setName("spaces/SPACE_NAME/members/MESSAGE_NAME"); + Message response = chatServiceClient.getMessage(request.build()); System.out.println(JsonFormat.printer().print(response)); } diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetSpaceAppCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetSpaceAppCred.java index df5da3d4..a01027a1 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetSpaceAppCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetSpaceAppCred.java @@ -28,12 +28,10 @@ public class GetSpaceAppCred { public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithAppCredentials()) { - GetSpaceRequest request = - GetSpaceRequest.newBuilder() + GetSpaceRequest.Builder request = GetSpaceRequest.newBuilder() // Replace SPACE_NAME here - .setName("spaces/SPACE_NAME") - .build(); - Space response = chatServiceClient.getSpace(request); + .setName("spaces/SPACE_NAME"); + Space response = chatServiceClient.getSpace(request.build()); System.out.println(JsonFormat.printer().print(response)); } diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetSpaceUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetSpaceUserCred.java index e9ed0a45..c84cce81 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetSpaceUserCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetSpaceUserCred.java @@ -33,12 +33,10 @@ public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithUserCredentials( ImmutableList.of(SCOPE))) { - GetSpaceRequest request = - GetSpaceRequest.newBuilder() + GetSpaceRequest.Builder request = GetSpaceRequest.newBuilder() // Replace SPACE_NAME here - .setName("spaces/SPACE_NAME") - .build(); - Space response = chatServiceClient.getSpace(request); + .setName("spaces/SPACE_NAME"); + Space response = chatServiceClient.getSpace(request.build()); System.out.println(JsonFormat.printer().print(response)); } diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsAppCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsAppCred.java index cae23771..7618ce43 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsAppCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsAppCred.java @@ -29,20 +29,18 @@ public class ListMembershipsAppCred { public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithAppCredentials()) { - ListMembershipsRequest request = - ListMembershipsRequest.newBuilder() - // Replace SPACE_NAME here. - .setParent("spaces/SPACE_NAME") - // Filter membership by type (HUMAN or BOT) or role - // (ROLE_MEMBER or ROLE_MANAGER). - .setFilter("member.type = \"HUMAN\"") - // Number of results that will be returned at once. - .setPageSize(10) - .build(); + ListMembershipsRequest.Builder request = ListMembershipsRequest.newBuilder() + // Replace SPACE_NAME here. + .setParent("spaces/SPACE_NAME") + // Filter membership by type (HUMAN or BOT) or role + // (ROLE_MEMBER or ROLE_MANAGER). + .setFilter("member.type = \"HUMAN\"") + // Number of results that will be returned at once. + .setPageSize(10); // Iterate over results and resolve additional pages automatically. for (Membership response : - chatServiceClient.listMemberships(request).iterateAll()) { + chatServiceClient.listMemberships(request.build()).iterateAll()) { System.out.println(JsonFormat.printer().print(response)); } } diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsUserCred.java index d60e2725..08f772de 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsUserCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsUserCred.java @@ -34,20 +34,18 @@ public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithUserCredentials( ImmutableList.of(SCOPE))) { - ListMembershipsRequest request = - ListMembershipsRequest.newBuilder() - // Replace SPACE_NAME here. - .setParent("spaces/SPACE_NAME") - // Filter membership by type (HUMAN or BOT) or role - // (ROLE_MEMBER or ROLE_MANAGER). - .setFilter("member.type = \"HUMAN\"") - // Number of results that will be returned at once. - .setPageSize(10) - .build(); + ListMembershipsRequest.Builder request = ListMembershipsRequest.newBuilder() + // Replace SPACE_NAME here. + .setParent("spaces/SPACE_NAME") + // Filter membership by type (HUMAN or BOT) or role + // (ROLE_MEMBER or ROLE_MANAGER). + .setFilter("member.type = \"HUMAN\"") + // Number of results that will be returned at once. + .setPageSize(10); // Iterating over results and resolve additional pages automatically. for (Membership response : - chatServiceClient.listMemberships(request).iterateAll()) { + chatServiceClient.listMemberships(request.build()).iterateAll()) { System.out.println(JsonFormat.printer().print(response)); } } diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMessagesUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMessagesUserCred.java index 1a984607..b99b0abf 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMessagesUserCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMessagesUserCred.java @@ -34,17 +34,15 @@ public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithUserCredentials( ImmutableList.of(SCOPE))) { - ListMessagesRequest request = - ListMessagesRequest.newBuilder() - // Replace SPACE_NAME here. - .setParent("spaces/SPACE_NAME") - // Number of results that will be returned at once. - .setPageSize(10) - .build(); + ListMessagesRequest.Builder request = ListMessagesRequest.newBuilder() + // Replace SPACE_NAME here. + .setParent("spaces/SPACE_NAME") + // Number of results that will be returned at once. + .setPageSize(10); // Iterate over results and resolve additional pages automatically. for (Message response : - chatServiceClient.listMessages(request).iterateAll()) { + chatServiceClient.listMessages(request.build()).iterateAll()) { System.out.println(JsonFormat.printer().print(response)); } } diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesAppCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesAppCred.java index 00494729..cb35a5b0 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesAppCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesAppCred.java @@ -29,18 +29,16 @@ public class ListSpacesAppCred { public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithAppCredentials()) { - ListSpacesRequest request = - ListSpacesRequest.newBuilder() - // Filter spaces by space type (SPACE or GROUP_CHAT or - // DIRECT_MESSAGE). - .setFilter("spaceType = \"SPACE\"") - // Number of results that will be returned at once. - .setPageSize(10) - .build(); + ListSpacesRequest.Builder request = ListSpacesRequest.newBuilder() + // Filter spaces by space type (SPACE or GROUP_CHAT or + // DIRECT_MESSAGE). + .setFilter("spaceType = \"SPACE\"") + // Number of results that will be returned at once. + .setPageSize(10); // Iterate over results and resolve additional pages automatically. for (Space response : - chatServiceClient.listSpaces(request).iterateAll()) { + chatServiceClient.listSpaces(request.build()).iterateAll()) { System.out.println(JsonFormat.printer().print(response)); } } diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesUserCred.java index 2d9410aa..ea3af6f9 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesUserCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesUserCred.java @@ -34,18 +34,16 @@ public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithUserCredentials( ImmutableList.of(SCOPE))) { - ListSpacesRequest request = - ListSpacesRequest.newBuilder() - // Filter spaces by space type (SPACE or GROUP_CHAT or - // DIRECT_MESSAGE). - .setFilter("spaceType = \"SPACE\"") - // Number of results that will be returned at once. - .setPageSize(10) - .build(); + ListSpacesRequest.Builder request = ListSpacesRequest.newBuilder() + // Filter spaces by space type (SPACE or GROUP_CHAT or + // DIRECT_MESSAGE). + .setFilter("spaceType = \"SPACE\"") + // Number of results that will be returned at once. + .setPageSize(10); // Iterate over results and resolve additional pages automatically. for (Space response : - chatServiceClient.listSpaces(request).iterateAll()) { + chatServiceClient.listSpaces(request.build()).iterateAll()) { System.out.println(JsonFormat.printer().print(response)); } } diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageAppCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageAppCred.java index 5f946545..fc62c5c0 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageAppCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageAppCred.java @@ -29,20 +29,15 @@ public class UpdateMessageAppCred { public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithAppCredentials()) { - UpdateMessageRequest request = - UpdateMessageRequest.newBuilder() - .setMessage( - Message.newBuilder() - // replace SPACE_NAME and MESSAGE_NAME here - .setName("spaces/SPACE_NAME/messages/MESSAGE_NAME") - .setText("Updated with app credential!") - .build() - ) - .setUpdateMask( - // The field paths to update. - FieldMask.newBuilder().addPaths("text").build()) - .build(); - Message response = chatServiceClient.updateMessage(request); + UpdateMessageRequest.Builder request = UpdateMessageRequest.newBuilder() + .setMessage(Message.newBuilder() + // replace SPACE_NAME and MESSAGE_NAME here + .setName("spaces/SPACE_NAME/messages/MESSAGE_NAME") + .setText("Updated with app credential!")) + .setUpdateMask(FieldMask.newBuilder() + // The field paths to update. + .addPaths("text")); + Message response = chatServiceClient.updateMessage(request.build()); System.out.println(JsonFormat.printer().print(response)); } diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageUserCred.java index 9f2dd016..5d0b4908 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageUserCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageUserCred.java @@ -34,20 +34,15 @@ public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithUserCredentials( ImmutableList.of(SCOPE))) { - UpdateMessageRequest request = - UpdateMessageRequest.newBuilder() - .setMessage( - Message.newBuilder() - // replace SPACE_NAME and MESSAGE_NAME here - .setName("spaces/SPACE_NAME/messages/MESSAGE_NAME") - .setText("Updated with user credential!") - .build() - ) - .setUpdateMask( - // The field paths to update. - FieldMask.newBuilder().addPaths("text").build()) - .build(); - Message response = chatServiceClient.updateMessage(request); + UpdateMessageRequest.Builder request = UpdateMessageRequest.newBuilder() + .setMessage(Message.newBuilder() + // replace SPACE_NAME and MESSAGE_NAME here + .setName("spaces/SPACE_NAME/messages/MESSAGE_NAME") + .setText("Updated with user credential!")) + .setUpdateMask(FieldMask.newBuilder() + // The field paths to update. + .addPaths("text")); + Message response = chatServiceClient.updateMessage(request.build()); System.out.println(JsonFormat.printer().print(response)); } diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateSpaceUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateSpaceUserCred.java index cd5d67cd..8b009703 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateSpaceUserCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateSpaceUserCred.java @@ -34,20 +34,15 @@ public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithUserCredentials( ImmutableList.of(SCOPE))) { - UpdateSpaceRequest request = - UpdateSpaceRequest.newBuilder() - .setSpace( - Space.newBuilder() - // Replace SPACE_NAME here. - .setName("spaces/SPACE_NAME") - .setDisplayName("New space display name") - .build() - ) - .setUpdateMask( - // The field paths to update. - FieldMask.newBuilder().addPaths("display_name").build()) - .build(); - Space response = chatServiceClient.updateSpace(request); + UpdateSpaceRequest.Builder request = UpdateSpaceRequest.newBuilder() + .setSpace(Space.newBuilder() + // Replace SPACE_NAME here. + .setName("spaces/SPACE_NAME") + .setDisplayName("New space display name")) + .setUpdateMask(FieldMask.newBuilder() + // The field paths to update. + .addPaths("display_name")); + Space response = chatServiceClient.updateSpace(request.build()); System.out.println(JsonFormat.printer().print(response)); } From 67f9f30c878b6fe16d9a3febf974e29afdcabb0a Mon Sep 17 00:00:00 2001 From: Pierrick Voulet <6769971+PierrickVoulet@users.noreply.github.com> Date: Thu, 22 Aug 2024 16:39:44 -0400 Subject: [PATCH 11/19] feat: fix class names and region tags for consistency (#1094) Co-authored-by: pierrick --- .../chat/samples/CreateMembershipUserCred.java | 4 ++-- .../samples/CreateMembershipUserCredForApp.java | 4 ++-- .../api/chat/samples/CreateMessageAppCred.java | 4 ++-- .../api/chat/samples/CreateMessageUserCred.java | 4 ++-- ...java => CreateMessageUserCredAtMention.java} | 17 +++++++++++------ ...java => CreateMessageUserCredMessageId.java} | 6 +++--- ...java => CreateMessageUserCredRequestId.java} | 6 +++--- ...java => CreateMessageUserCredThreadKey.java} | 6 +++--- ...ava => CreateMessageUserCredThreadName.java} | 6 +++--- .../api/chat/samples/DeleteMessageAppCred.java | 4 ++-- .../api/chat/samples/DeleteMessageUserCred.java | 4 ++-- .../api/chat/samples/GetMembershipAppCred.java | 4 ++-- .../api/chat/samples/GetMembershipUserCred.java | 4 ++-- .../api/chat/samples/GetMessageAppCred.java | 4 ++-- .../api/chat/samples/GetMessageUserCred.java | 4 ++-- .../api/chat/samples/GetSpaceAppCred.java | 4 ++-- .../api/chat/samples/GetSpaceUserCred.java | 4 ++-- .../chat/samples/ListMembershipsAppCred.java | 4 ++-- .../chat/samples/ListMembershipsUserCred.java | 4 ++-- .../api/chat/samples/ListMessagesUserCred.java | 4 ++-- .../api/chat/samples/ListSpacesAppCred.java | 4 ++-- .../api/chat/samples/ListSpacesUserCred.java | 4 ++-- .../api/chat/samples/UpdateMessageAppCred.java | 4 ++-- .../api/chat/samples/UpdateMessageUserCred.java | 4 ++-- .../api/chat/samples/UpdateSpaceUserCred.java | 4 ++-- 25 files changed, 63 insertions(+), 58 deletions(-) rename chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/{CreateMessageAppCredAtMention.java => CreateMessageUserCredAtMention.java} (75%) rename chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/{CreateMessageUserCredWithMessageId.java => CreateMessageUserCredMessageId.java} (92%) rename chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/{CreateMessageUserCredWithRequestId.java => CreateMessageUserCredRequestId.java} (92%) rename chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/{CreateMessageUserCredWithThreadKey.java => CreateMessageUserCredThreadKey.java} (93%) rename chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/{CreateMessageUserCredWithThreadName.java => CreateMessageUserCredThreadName.java} (93%) diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCred.java index c04b15fc..c10605bd 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCred.java @@ -18,7 +18,7 @@ import com.google.common.collect.ImmutableList; import com.google.protobuf.util.JsonFormat; -// [START chat_CreateMembershipUserCred] +// [START chat_create_membership_user_cred] import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.CreateMembershipRequest; import com.google.chat.v1.Membership; @@ -51,4 +51,4 @@ public static void main(String[] args) throws Exception { } } } -// [END chat_CreateMembershipUserCred] +// [END chat_create_membership_user_cred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCredForApp.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCredForApp.java index 3edb889d..1572da40 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCredForApp.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCredForApp.java @@ -18,7 +18,7 @@ import com.google.common.collect.ImmutableList; import com.google.protobuf.util.JsonFormat; -// [START chat_CreateMembershipUserCredForApp] +// [START chat_create_membership_user_cred_for_app] import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.CreateMembershipRequest; import com.google.chat.v1.Membership; @@ -51,4 +51,4 @@ public static void main(String[] args) throws Exception { } } } -// [END chat_CreateMembershipUserCredForApp] +// [END chat_create_membership_user_cred_for_app] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCred.java index c17303f2..b32bd8dd 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCred.java @@ -17,7 +17,7 @@ package com.google.workspace.api.chat.samples; import com.google.protobuf.util.JsonFormat; -// [START chat_CreateMessageAppCred] +// [START chat_create_message_app_cred] import com.google.apps.card.v1.Button; import com.google.apps.card.v1.ButtonList; import com.google.apps.card.v1.Card; @@ -87,4 +87,4 @@ public static void main(String[] args) throws Exception { } } } -// [END chat_CreateMessageAppCred] +// [END chat_create_message_app_cred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCred.java index fa53ed57..cef822a1 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCred.java @@ -18,7 +18,7 @@ import com.google.common.collect.ImmutableList; import com.google.protobuf.util.JsonFormat; -// [START chat_CreateMessageUserCred] +// [START chat_create_message_user_cred] import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.CreateMessageRequest; import com.google.chat.v1.Message; @@ -51,4 +51,4 @@ public static void main(String[] args) throws Exception { } } } -// [END chat_CreateMessageUserCred] +// [END chat_create_message_user_cred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCredAtMention.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredAtMention.java similarity index 75% rename from chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCredAtMention.java rename to chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredAtMention.java index 5830de3c..a52874bd 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCredAtMention.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredAtMention.java @@ -16,19 +16,24 @@ package com.google.workspace.api.chat.samples; +import com.google.common.collect.ImmutableList; import com.google.protobuf.util.JsonFormat; -// [START chat_CreateMessageAppCredAtMention] +// [START chat_create_message_user_cred_at_mention] import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.CreateMessageRequest; import com.google.chat.v1.Message; -// This sample shows how to create message that mentions a user with app -// credential. -public class CreateMessageAppCredAtMention { +// This sample shows how to create message with user credential with a user +// mention. +public class CreateMessageUserCredAtMention { + + private static final String SCOPE = + "https://www.googleapis.com/auth/chat.messages.create"; public static void main(String[] args) throws Exception { try (ChatServiceClient chatServiceClient = - AuthenticationUtils.createClientWithAppCredentials()) { + AuthenticationUtils.createClientWithUserCredentials( + ImmutableList.of(SCOPE))) { CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder() // Replace SPACE_NAME here. .setParent("spaces/SPACE_NAME") @@ -43,4 +48,4 @@ public static void main(String[] args) throws Exception { } } } -// [END chat_CreateMessageAppCredAtMention] +// [END chat_create_message_user_cred_at_mention] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithMessageId.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredMessageId.java similarity index 92% rename from chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithMessageId.java rename to chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredMessageId.java index d76475c7..0312ce07 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithMessageId.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredMessageId.java @@ -18,14 +18,14 @@ import com.google.common.collect.ImmutableList; import com.google.protobuf.util.JsonFormat; -// [START chat_CreateMessageUserCredWithMessageId] +// [START chat_create_message_user_cred_message_id] import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.CreateMessageRequest; import com.google.chat.v1.Message; // This sample shows how to create message with message id specified with user // credential. -public class CreateMessageUserCredWithMessageId { +public class CreateMessageUserCredMessageId { private static final String SCOPE = "https://www.googleapis.com/auth/chat.messages.create"; @@ -49,4 +49,4 @@ public static void main(String[] args) throws Exception { } } } -// [END chat_CreateMessageUserCredWithMessageId] +// [END chat_create_message_user_cred_message_id] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithRequestId.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredRequestId.java similarity index 92% rename from chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithRequestId.java rename to chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredRequestId.java index 1d05d950..c9acce76 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithRequestId.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredRequestId.java @@ -18,14 +18,14 @@ import com.google.common.collect.ImmutableList; import com.google.protobuf.util.JsonFormat; -// [START chat_CreateMessageUserCredWithRequestId] +// [START chat_create_message_user_cred_request_id] import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.CreateMessageRequest; import com.google.chat.v1.Message; // This sample shows how to create message with request id specified with user // credential. -public class CreateMessageUserCredWithRequestId { +public class CreateMessageUserCredRequestId { private static final String SCOPE = "https://www.googleapis.com/auth/chat.messages.create"; @@ -48,4 +48,4 @@ public static void main(String[] args) throws Exception { } } } -// [END chat_CreateMessageUserCredWithRequestId] +// [END chat_create_message_user_cred_request_id] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithThreadKey.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredThreadKey.java similarity index 93% rename from chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithThreadKey.java rename to chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredThreadKey.java index 897df800..8fa51135 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithThreadKey.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredThreadKey.java @@ -18,7 +18,7 @@ import com.google.common.collect.ImmutableList; import com.google.protobuf.util.JsonFormat; -// [START chat_CreateMessageUserCredWithThreadKey] +// [START chat_create_message_user_cred_thread_key] import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.CreateMessageRequest; import com.google.chat.v1.CreateMessageRequest.MessageReplyOption; @@ -27,7 +27,7 @@ // This sample shows how to create message with a thread key with user // credential. -public class CreateMessageUserCredWithThreadKey { +public class CreateMessageUserCredThreadKey { private static final String SCOPE = "https://www.googleapis.com/auth/chat.messages.create"; @@ -54,4 +54,4 @@ public static void main(String[] args) throws Exception { } } } -// [END chat_CreateMessageUserCredWithThreadKey] +// [END chat_create_message_user_cred_thread_key] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithThreadName.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredThreadName.java similarity index 93% rename from chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithThreadName.java rename to chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredThreadName.java index 69bfba1e..e27387fb 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredWithThreadName.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredThreadName.java @@ -18,7 +18,7 @@ import com.google.common.collect.ImmutableList; import com.google.protobuf.util.JsonFormat; -// [START chat_CreateMessageUserCredWithThreadName] +// [START chat_create_message_user_cred_thread_name] import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.CreateMessageRequest; import com.google.chat.v1.CreateMessageRequest.MessageReplyOption; @@ -27,7 +27,7 @@ // This sample shows how to create message with thread name specified with user // credential. -public class CreateMessageUserCredWithThreadName { +public class CreateMessageUserCredThreadName { private static final String SCOPE = "https://www.googleapis.com/auth/chat.messages.create"; @@ -55,4 +55,4 @@ public static void main(String[] args) throws Exception { } } } -// [END chat_CreateMessageUserCredWithThreadName] +// [END chat_create_message_user_cred_thread_name] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/DeleteMessageAppCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/DeleteMessageAppCred.java index abda2ae1..f0fea33b 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/DeleteMessageAppCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/DeleteMessageAppCred.java @@ -16,7 +16,7 @@ package com.google.workspace.api.chat.samples; -// [START chat_DeleteMessageAppCred] +// [START chat_delete_message_app_cred] import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.DeleteMessageRequest; @@ -33,4 +33,4 @@ public static void main(String[] args) throws Exception { } } } -// [END chat_DeleteMessageAppCred] +// [END chat_delete_message_app_cred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/DeleteMessageUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/DeleteMessageUserCred.java index 491a3dd6..34d5adc2 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/DeleteMessageUserCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/DeleteMessageUserCred.java @@ -17,7 +17,7 @@ package com.google.workspace.api.chat.samples; import com.google.common.collect.ImmutableList; -// [START chat_DeleteMessageUserCred] +// [START chat_delete_message_user_cred] import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.DeleteMessageRequest; import com.google.chat.v1.SpaceName; @@ -39,4 +39,4 @@ public static void main(String[] args) throws Exception { } } } -// [END chat_DeleteMessageUserCred] +// [END chat_delete_message_user_cred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMembershipAppCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMembershipAppCred.java index fcd7ae69..52c2e86f 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMembershipAppCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMembershipAppCred.java @@ -17,7 +17,7 @@ package com.google.workspace.api.chat.samples; import com.google.protobuf.util.JsonFormat; -// [START chat_GetMembershipAppCred] +// [START chat_get_membership_app_cred] import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.GetMembershipRequest; import com.google.chat.v1.Membership; @@ -37,4 +37,4 @@ public static void main(String[] args) throws Exception { } } } -// [END chat_GetMembershipAppCred] +// [END chat_get_membership_app_cred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMembershipUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMembershipUserCred.java index f54b8633..55637384 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMembershipUserCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMembershipUserCred.java @@ -18,7 +18,7 @@ import com.google.common.collect.ImmutableList; import com.google.protobuf.util.JsonFormat; -// [START chat_GetMembershipUserCred] +// [START chat_get_membership_user_cred] import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.GetMembershipRequest; import com.google.chat.v1.Membership; @@ -42,4 +42,4 @@ public static void main(String[] args) throws Exception { } } } -// [END chat_GetMembershipUserCred] +// [END chat_get_membership_user_cred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageAppCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageAppCred.java index b80a28e9..f79e8a79 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageAppCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageAppCred.java @@ -17,7 +17,7 @@ package com.google.workspace.api.chat.samples; import com.google.protobuf.util.JsonFormat; -// [START chat_GetMessageAppCred] +// [START chat_get_message_app_cred] import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.GetMessageRequest; import com.google.chat.v1.Message; @@ -37,4 +37,4 @@ public static void main(String[] args) throws Exception { } } } -// [END chat_GetMessageAppCred] +// [END chat_get_message_app_cred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageUserCred.java index 7db70657..f8a99a70 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageUserCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageUserCred.java @@ -18,7 +18,7 @@ import com.google.common.collect.ImmutableList; import com.google.protobuf.util.JsonFormat; -// [START chat_GetMessageUserCred] +// [START chat_get_message_user_cred] import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.GetMessageRequest; import com.google.chat.v1.Message; @@ -42,4 +42,4 @@ public static void main(String[] args) throws Exception { } } } -// [END chat_GetMessageUserCred] +// [END chat_get_message_user_cred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetSpaceAppCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetSpaceAppCred.java index a01027a1..4b76c13d 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetSpaceAppCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetSpaceAppCred.java @@ -17,7 +17,7 @@ package com.google.workspace.api.chat.samples; import com.google.protobuf.util.JsonFormat; -// [START chat_GetSpaceAppCred] +// [START chat_get_space_app_cred] import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.GetSpaceRequest; import com.google.chat.v1.Space; @@ -37,4 +37,4 @@ public static void main(String[] args) throws Exception { } } } -// [END chat_GetSpaceAppCred] +// [END chat_get_space_app_cred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetSpaceUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetSpaceUserCred.java index c84cce81..ab85d9ce 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetSpaceUserCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetSpaceUserCred.java @@ -18,7 +18,7 @@ import com.google.common.collect.ImmutableList; import com.google.protobuf.util.JsonFormat; -// [START chat_GetSpaceUserCred] +// [START chat_get_space_user_cred] import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.GetSpaceRequest; import com.google.chat.v1.Space; @@ -42,4 +42,4 @@ public static void main(String[] args) throws Exception { } } } -// [END chat_GetSpaceUserCred] +// [END chat_get_space_user_cred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsAppCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsAppCred.java index 7618ce43..8a4a56f0 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsAppCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsAppCred.java @@ -17,7 +17,7 @@ package com.google.workspace.api.chat.samples; import com.google.protobuf.util.JsonFormat; -// [START chat_ListMembershipsAppCred] +// [START chat_list_memberships_app_cred] import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.ListMembershipsRequest; import com.google.chat.v1.ListMembershipsResponse; @@ -46,4 +46,4 @@ public static void main(String[] args) throws Exception { } } } -// [END chat_ListMembershipsAppCred] +// [END chat_list_memberships_app_cred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsUserCred.java index 08f772de..8ddeb7dd 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsUserCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMembershipsUserCred.java @@ -18,7 +18,7 @@ import com.google.common.collect.ImmutableList; import com.google.protobuf.util.JsonFormat; -// [START chat_ListMembershipsUserCred] +// [START chat_list_memberships_user_cred] import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.ListMembershipsRequest; import com.google.chat.v1.ListMembershipsResponse; @@ -51,4 +51,4 @@ public static void main(String[] args) throws Exception { } } } -// [END chat_ListMembershipsUserCred] +// [END chat_list_memberships_user_cred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMessagesUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMessagesUserCred.java index b99b0abf..d9081b24 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMessagesUserCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMessagesUserCred.java @@ -18,7 +18,7 @@ import com.google.common.collect.ImmutableList; import com.google.protobuf.util.JsonFormat; -// [START chat_ListMessagesUserCred] +// [START chat_list_messages_user_cred] import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.ListMessagesRequest; import com.google.chat.v1.ListMessagesResponse; @@ -48,4 +48,4 @@ public static void main(String[] args) throws Exception { } } } -// [END chat_ListMessagesUserCred] +// [END chat_list_messages_user_cred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesAppCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesAppCred.java index cb35a5b0..8fd15cc3 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesAppCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesAppCred.java @@ -17,7 +17,7 @@ package com.google.workspace.api.chat.samples; import com.google.protobuf.util.JsonFormat; -// [START chat_ListSpacesAppCred] +// [START chat_list_spaces_app_cred] import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.ListSpacesRequest; import com.google.chat.v1.ListSpacesResponse; @@ -44,4 +44,4 @@ public static void main(String[] args) throws Exception { } } } -// [END chat_ListSpacesAppCred] +// [END chat_list_spaces_app_cred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesUserCred.java index ea3af6f9..bffdf6cb 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesUserCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesUserCred.java @@ -18,7 +18,7 @@ import com.google.common.collect.ImmutableList; import com.google.protobuf.util.JsonFormat; -// [START chat_ListSpacesUserCred] +// [START chat_list_spaces_user_cred] import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.ListSpacesRequest; import com.google.chat.v1.ListSpacesResponse; @@ -49,4 +49,4 @@ public static void main(String[] args) throws Exception { } } } -// [END chat_ListSpacesUserCred] +// [END chat_list_spaces_user_cred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageAppCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageAppCred.java index fc62c5c0..8eaf3dd7 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageAppCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageAppCred.java @@ -17,7 +17,7 @@ package com.google.workspace.api.chat.samples; import com.google.protobuf.util.JsonFormat; -// [START chat_UpdateMessageAppCred] +// [START chat_update_message_app_cred] import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.UpdateMessageRequest; import com.google.chat.v1.Message; @@ -43,4 +43,4 @@ public static void main(String[] args) throws Exception { } } } -// [END chat_UpdateMessageAppCred] +// [END chat_update_message_app_cred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageUserCred.java index 5d0b4908..abda65c7 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageUserCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageUserCred.java @@ -18,7 +18,7 @@ import com.google.common.collect.ImmutableList; import com.google.protobuf.util.JsonFormat; -// [START chat_UpdateMessageUserCred] +// [START chat_update_message_user_cred] import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.UpdateMessageRequest; import com.google.chat.v1.Message; @@ -48,4 +48,4 @@ public static void main(String[] args) throws Exception { } } } -// [END chat_UpdateMessageUserCred] +// [END chat_update_message_user_cred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateSpaceUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateSpaceUserCred.java index 8b009703..73b5cec3 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateSpaceUserCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateSpaceUserCred.java @@ -18,7 +18,7 @@ import com.google.common.collect.ImmutableList; import com.google.protobuf.util.JsonFormat; -// [START chat_UpdateSpaceUserCred] +// [START chat_update_space_user_cred] import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.UpdateSpaceRequest; import com.google.chat.v1.Space; @@ -48,4 +48,4 @@ public static void main(String[] args) throws Exception { } } } -// [END chat_UpdateSpaceUserCred] +// [END chat_update_space_user_cred] From b2f6faef4fb7b1cf2d9b35dfb5206736e1e0bb11 Mon Sep 17 00:00:00 2001 From: Pierrick Voulet <6769971+PierrickVoulet@users.noreply.github.com> Date: Wed, 2 Oct 2024 20:52:19 -0400 Subject: [PATCH 12/19] feat: add create membership for group code sample (#1164) Co-authored-by: pierrick --- .../CreateMembershipUserCredForGroup.java | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCredForGroup.java diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCredForGroup.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCredForGroup.java new file mode 100644 index 00000000..43e20ac0 --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCredForGroup.java @@ -0,0 +1,51 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.common.collect.ImmutableList; +import com.google.protobuf.util.JsonFormat; +// [START chat_create_membership_user_cred_for_group] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.CreateMembershipRequest; +import com.google.chat.v1.Membership; +import com.google.chat.v1.SpaceName; +import com.google.chat.v1.Group; + +// This sample shows how to create membership with user credential for a group. +public class CreateMembershipUserCredForGroup { + + private static final String SCOPE = + "https://www.googleapis.com/auth/chat.memberships"; + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithUserCredentials( + ImmutableList.of(SCOPE))) { + CreateMembershipRequest.Builder request = CreateMembershipRequest.newBuilder() + // replace SPACE_NAME here + .setParent("spaces/SPACE_NAME") + .setMembership(Membership.newBuilder() + .setGroupMember(Group.newBuilder() + // replace GROUP_NAME here + .setName("groups/GROUP_NAME"))); + Membership response = chatServiceClient.createMembership(request.build()); + + System.out.println(JsonFormat.printer().print(response)); + } + } +} +// [END chat_create_membership_user_cred_for_group] From cfb3a31befe7e5c90bbcd3dd5ef4cb7d9548378d Mon Sep 17 00:00:00 2001 From: Pierrick Voulet <6769971+PierrickVoulet@users.noreply.github.com> Date: Thu, 3 Oct 2024 10:11:01 -0400 Subject: [PATCH 13/19] feat: add create and set up space code samples (#1165) * feat: add create and set up space code samples * Change for immutable list --------- Co-authored-by: pierrick --- .../api/chat/samples/CreateSpaceUserCred.java | 47 ++++++++++++++++ .../api/chat/samples/SetUpSpaceUserCred.java | 56 +++++++++++++++++++ 2 files changed, 103 insertions(+) create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateSpaceUserCred.java create mode 100644 chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/SetUpSpaceUserCred.java diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateSpaceUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateSpaceUserCred.java new file mode 100644 index 00000000..713f64a9 --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateSpaceUserCred.java @@ -0,0 +1,47 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.common.collect.ImmutableList; +import com.google.protobuf.util.JsonFormat; +// [START chat_create_space_user_cred] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.CreateSpaceRequest; +import com.google.chat.v1.Space; + +// This sample shows how to create space with user credential. +public class CreateSpaceUserCred { + + private static final String SCOPE = + "https://www.googleapis.com/auth/chat.spaces.create"; + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithUserCredentials( + ImmutableList.of(SCOPE))) { + CreateSpaceRequest.Builder request = CreateSpaceRequest.newBuilder() + .setSpace(Space.newBuilder() + .setSpaceType(Space.SpaceType.SPACE) + // Replace DISPLAY_NAME here. + .setDisplayName("DISPLAY_NAME")); + Space response = chatServiceClient.createSpace(request.build()); + + System.out.println(JsonFormat.printer().print(response)); + } + } +} +// [END chat_create_space_user_cred] diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/SetUpSpaceUserCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/SetUpSpaceUserCred.java new file mode 100644 index 00000000..d39b6192 --- /dev/null +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/SetUpSpaceUserCred.java @@ -0,0 +1,56 @@ +/* + * 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 + * + * https://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. + */ + +package com.google.workspace.api.chat.samples; + +import com.google.common.collect.ImmutableList; +import com.google.protobuf.util.JsonFormat; + +// [START chat_set_up_space_user_cred] +import com.google.chat.v1.ChatServiceClient; +import com.google.chat.v1.Membership; +import com.google.chat.v1.SetUpSpaceRequest; +import com.google.chat.v1.Space; +import com.google.chat.v1.User; + +// This sample shows how to set up a named space with one initial member with +// user credential. +public class SetUpSpaceUserCred { + + private static final String SCOPE = + "https://www.googleapis.com/auth/chat.spaces.create"; + + public static void main(String[] args) throws Exception { + try (ChatServiceClient chatServiceClient = + AuthenticationUtils.createClientWithUserCredentials( + ImmutableList.of(SCOPE))) { + SetUpSpaceRequest.Builder request = SetUpSpaceRequest.newBuilder() + .setSpace(Space.newBuilder() + .setSpaceType(Space.SpaceType.SPACE) + // Replace DISPLAY_NAME here. + .setDisplayName("DISPLAY_NAME")) + .addAllMemberships(ImmutableList.of(Membership.newBuilder() + .setMember(User.newBuilder() + // Replace USER_NAME here. + .setName("users/USER_NAME") + .setType(User.Type.HUMAN)).build())); + Space response = chatServiceClient.setUpSpace(request.build()); + + System.out.println(JsonFormat.printer().print(response)); + } + } +} +// [END chat_set_up_space_user_cred] From 26cb124371d51cb5cb8e6c4a3db6422bbef586fb Mon Sep 17 00:00:00 2001 From: Pierrick Voulet <6769971+PierrickVoulet@users.noreply.github.com> Date: Thu, 3 Oct 2024 13:49:43 -0400 Subject: [PATCH 14/19] feat: update message with app creds (#1166) Co-authored-by: pierrick --- .../api/chat/samples/UpdateMessageAppCred.java | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageAppCred.java b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageAppCred.java index 8eaf3dd7..559ad13f 100644 --- a/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageAppCred.java +++ b/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageAppCred.java @@ -17,7 +17,13 @@ package com.google.workspace.api.chat.samples; import com.google.protobuf.util.JsonFormat; + +import java.util.List; + // [START chat_update_message_app_cred] +import com.google.apps.card.v1.Card; +import com.google.apps.card.v1.Card.CardHeader; +import com.google.chat.v1.CardWithId; import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.UpdateMessageRequest; import com.google.chat.v1.Message; @@ -33,10 +39,14 @@ public static void main(String[] args) throws Exception { .setMessage(Message.newBuilder() // replace SPACE_NAME and MESSAGE_NAME here .setName("spaces/SPACE_NAME/messages/MESSAGE_NAME") - .setText("Updated with app credential!")) + .setText("Text updated with app credential!") + .addCardsV2(CardWithId.newBuilder().setCard(Card.newBuilder() + .setHeader(CardHeader.newBuilder() + .setTitle("Card updated with app credential!") + .setImageUrl("https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg"))))) .setUpdateMask(FieldMask.newBuilder() // The field paths to update. - .addPaths("text")); + .addAllPaths(List.of("text", "cards_v2"))); Message response = chatServiceClient.updateMessage(request.build()); System.out.println(JsonFormat.printer().print(response)); From b30298095f654ff9952a691333f0aa5862ab935c Mon Sep 17 00:00:00 2001 From: sce-taid Date: Thu, 11 Sep 2025 01:06:16 +0200 Subject: [PATCH 15/19] fix: updating FileList query field name (#1473) renaming `items` (v2) to `files` (v3) --- drive/snippets/drive_v3/src/main/java/SearchFile.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drive/snippets/drive_v3/src/main/java/SearchFile.java b/drive/snippets/drive_v3/src/main/java/SearchFile.java index 08f574b1..2e5e7f01 100644 --- a/drive/snippets/drive_v3/src/main/java/SearchFile.java +++ b/drive/snippets/drive_v3/src/main/java/SearchFile.java @@ -60,7 +60,7 @@ public static List searchFile() throws IOException { FileList result = service.files().list() .setQ("mimeType='image/jpeg'") .setSpaces("drive") - .setFields("nextPageToken, items(id, title)") + .setFields("nextPageToken, files(id, title)") .setPageToken(pageToken) .execute(); for (File file : result.getFiles()) { From d219a446eaace9ce6d53fd58ca764d1b63bf2a16 Mon Sep 17 00:00:00 2001 From: googleworkspace-bot <109114539+googleworkspace-bot@users.noreply.github.com> Date: Tue, 18 Nov 2025 15:43:28 -0700 Subject: [PATCH 16/19] chore: Created local '.gemini/' from remote 'sync-files/defaults/.gemini/' (#1692) --- .gemini/GEMINI.md | 12 ++++++++++++ .gemini/config.yaml | 12 ++++++++++++ .gemini/settings.json | 8 ++++++++ 3 files changed, 32 insertions(+) create mode 100644 .gemini/GEMINI.md create mode 100644 .gemini/config.yaml create mode 100644 .gemini/settings.json diff --git a/.gemini/GEMINI.md b/.gemini/GEMINI.md new file mode 100644 index 00000000..0f175c59 --- /dev/null +++ b/.gemini/GEMINI.md @@ -0,0 +1,12 @@ +# Overview + +This codebase is part of the Google Workspace GitHub organization, https://github.com/googleworkspace. + +## Style Guide + +Use open source best practices for code style and formatting with a preference for Google's style guides. + +## Tools + +- Verify against Google Workspace documentation with the `workspace-developer` MCP server tools. +- Use `gh` for GitHub interactions. diff --git a/.gemini/config.yaml b/.gemini/config.yaml new file mode 100644 index 00000000..a4814a5f --- /dev/null +++ b/.gemini/config.yaml @@ -0,0 +1,12 @@ +# Config for the Gemini Pull Request Review Bot. +# https://github.com/marketplace/gemini-code-assist +have_fun: false +code_review: + disable: false + comment_severity_threshold: "HIGH" + max_review_comments: -1 + pull_request_opened: + help: false + summary: true + code_review: true +ignore_patterns: [] diff --git a/.gemini/settings.json b/.gemini/settings.json new file mode 100644 index 00000000..ec3565d5 --- /dev/null +++ b/.gemini/settings.json @@ -0,0 +1,8 @@ +{ + "mcpServers": { + "workspace-developer": { + "httpUrl": "https://workspace-developer.goog/mcp", + "trust": true + } + } +} \ No newline at end of file From 43971ae6e90c0ac95dea1842d432eccc916a5a48 Mon Sep 17 00:00:00 2001 From: googleworkspace-bot <109114539+googleworkspace-bot@users.noreply.github.com> Date: Tue, 18 Nov 2025 15:47:46 -0700 Subject: [PATCH 17/19] chore: Synced file(s) with googleworkspace/.github --- .vscode/extensions.json | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .vscode/extensions.json diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 00000000..4a9deaa4 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,5 @@ +{ + "recommendations": [ + "google-workspace.google-workspace-developer-tools" + ] +} \ No newline at end of file From e8ba9fd71688ee75119f4e13c175239ca88291ff Mon Sep 17 00:00:00 2001 From: Pierrick Voulet <6769971+PierrickVoulet@users.noreply.github.com> Date: Mon, 8 Dec 2025 23:43:33 -0500 Subject: [PATCH 18/19] feat: add webhook chat app (#1715) Co-authored-by: pierrick --- solutions/webhook-chat-app/README.md | 4 ++ solutions/webhook-chat-app/pom.xml | 52 +++++++++++++++++++ .../java/com/google/chat/webhook/App.java | 45 ++++++++++++++++ .../com/google/chat/webhook/AppThread.java | 48 +++++++++++++++++ 4 files changed, 149 insertions(+) create mode 100644 solutions/webhook-chat-app/README.md create mode 100644 solutions/webhook-chat-app/pom.xml create mode 100644 solutions/webhook-chat-app/src/main/java/com/google/chat/webhook/App.java create mode 100644 solutions/webhook-chat-app/src/main/java/com/google/chat/webhook/AppThread.java diff --git a/solutions/webhook-chat-app/README.md b/solutions/webhook-chat-app/README.md new file mode 100644 index 00000000..59643860 --- /dev/null +++ b/solutions/webhook-chat-app/README.md @@ -0,0 +1,4 @@ +# Google Chat App Webhook + +Please see related guide on how to +[send messages to Google Chat with incoming webhooks](https://developers.google.com/workspace/chat/quickstart/webhooks). diff --git a/solutions/webhook-chat-app/pom.xml b/solutions/webhook-chat-app/pom.xml new file mode 100644 index 00000000..be47addd --- /dev/null +++ b/solutions/webhook-chat-app/pom.xml @@ -0,0 +1,52 @@ + + + + + + 4.0.0 + + com.google.chat.webhook + webhook-app + 0.1.0 + webhook-app + + + 11 + 11 + + + + + com.google.code.gson + gson + 2.9.1 + + + + + + + + maven-compiler-plugin + 3.8.0 + + + + + + diff --git a/solutions/webhook-chat-app/src/main/java/com/google/chat/webhook/App.java b/solutions/webhook-chat-app/src/main/java/com/google/chat/webhook/App.java new file mode 100644 index 00000000..3f9f4032 --- /dev/null +++ b/solutions/webhook-chat-app/src/main/java/com/google/chat/webhook/App.java @@ -0,0 +1,45 @@ +/** + * Copyright 2022 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. + */ +package com.google.chat.webhook; + +// [START chat_webhook] +import com.google.gson.Gson; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.Map; +import java.net.URI; + +public class App { + private static final String URL = "https://chat.googleapis.com/v1/spaces/SPACE_ID/messages?key=KEY&token=TOKEN"; + private static final Gson gson = new Gson(); + private static final HttpClient client = HttpClient.newHttpClient(); + + public static void main(String[] args) throws Exception { + String message = gson.toJson(Map.of( + "text", "Hello from Java!" + )); + + HttpRequest request = HttpRequest.newBuilder(URI.create(URL)) + .header("accept", "application/json; charset=UTF-8") + .POST(HttpRequest.BodyPublishers.ofString(message)).build(); + + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); + + System.out.println(response.body()); + } +} +// [END chat_webhook] diff --git a/solutions/webhook-chat-app/src/main/java/com/google/chat/webhook/AppThread.java b/solutions/webhook-chat-app/src/main/java/com/google/chat/webhook/AppThread.java new file mode 100644 index 00000000..d5c5fb52 --- /dev/null +++ b/solutions/webhook-chat-app/src/main/java/com/google/chat/webhook/AppThread.java @@ -0,0 +1,48 @@ +/** + * Copyright 2025 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. + */ +package com.google.chat.webhook; + +// [START chat_webhook_thread] +import com.google.gson.Gson; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.Map; +import java.net.URI; + +public class App { + private static final String URL = "https://chat.googleapis.com/v1/spaces/SPACE_ID/messages?key=KEY&token=TOKEN&messageReplyOption=REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD"; + private static final Gson gson = new Gson(); + private static final HttpClient client = HttpClient.newHttpClient(); + + public static void main(String[] args) throws Exception { + String message = gson.toJson(Map.of( + "text", "Hello from Java!", + "thread", Map.of( + "threadKey", "THREAD_KEY_VALUE" + ) + )); + + HttpRequest request = HttpRequest.newBuilder(URI.create(URL)) + .header("accept", "application/json; charset=UTF-8") + .POST(HttpRequest.BodyPublishers.ofString(message)).build(); + + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); + + System.out.println(response.body()); + } +} +// [END chat_webhook_thread] From 19db17de8d3d018de067c5c8bbe50753b9f2055c Mon Sep 17 00:00:00 2001 From: Ken Cenerelli Date: Tue, 17 Feb 2026 11:54:57 -0800 Subject: [PATCH 19/19] docs: add SheetsFilterViews Java sample (#1747) * docs: add SheetsFilterViews Java sample Adds Java sample for filter views. Based on the `sheets_filter_views` sample from Python. * Fix comment formatting in SheetsFilterViews.java * Implement error handling for filter view operations Added error handling for Add and Duplicate Filter View requests to ensure valid responses. * Update copyright year in SheetsFilterViews.java Updated copyright year from 2022 to 2026. --- .../src/main/java/SheetsFilterViews.java | 175 ++++++++++++++++++ 1 file changed, 175 insertions(+) create mode 100644 sheets/snippets/src/main/java/SheetsFilterViews.java diff --git a/sheets/snippets/src/main/java/SheetsFilterViews.java b/sheets/snippets/src/main/java/SheetsFilterViews.java new file mode 100644 index 00000000..06a1f939 --- /dev/null +++ b/sheets/snippets/src/main/java/SheetsFilterViews.java @@ -0,0 +1,175 @@ +/ * +Copyright 2026 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 sheets_filter_views] + +/* + * Dependencies (Maven): + * com.google.apis:google-api-services-sheets:v4-rev20220927-2.0.0 + * com.google.auth:google-auth-library-oauth2-http:1.19.0 + */ + +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.services.sheets.v4.Sheets; +import com.google.api.services.sheets.v4.SheetsScopes; +import com.google.api.services.sheets.v4.model.*; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.*; + +public class SheetsFilterViews { + + public static void main(String... args) { + filterViews("1CM29gwKIzeXsAppeNwrc8lbYaVMmUclprLuLYuHog4k"); + } + + public static void filterViews(String spreadsheetId) { + try { + // Load pre-authorized user credentials from the environment. + // TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2. + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(SheetsScopes.SPREADSHEETS)); + + Sheets service = new Sheets.Builder( + GoogleNetHttpTransport.newTrustedTransport(), + GsonFactory.getDefaultInstance(), + new HttpCredentialsAdapter(credentials)) + .setApplicationName("Sheets Filter Views Sample") + .build(); + + // --- Step 1: Add Filter View --- + GridRange myRange = new GridRange() + .setSheetId(0) + .setStartRowIndex(0) + .setStartColumnIndex(0); + + // Construct Criteria for Column 0 (Hidden Values) + FilterCriteria criteria0 = new FilterCriteria() + .setHiddenValues(Collections.singletonList("Panel")); + + // Construct Criteria for Column 6 (Date Condition) + ConditionValue dateValue = new ConditionValue().setUserEnteredValue("4/30/2016"); + BooleanCondition dateCondition = new BooleanCondition() + .setType("DATE_BEFORE") + .setValues(Collections.singletonList(dateValue)); + FilterCriteria criteria6 = new FilterCriteria().setCondition(dateCondition); + + // Map criteria to column indices (Note: keys are Strings in Java map) + Map criteriaMap = new HashMap<>(); + criteriaMap.put("0", criteria0); + criteriaMap.put("6", criteria6); + + FilterView filterView = new FilterView() + .setTitle("Sample Filter") + .setRange(myRange) + .setSortSpecs(Collections.singletonList( + new SortSpec().setDimensionIndex(3).setSortOrder("DESCENDING") + )) + .setCriteria(criteriaMap); + + // --- Step 1: Add Filter View --- + // (Request construction remains the same) + // ... + AddFilterViewRequest addFilterViewRequest = new AddFilterViewRequest().setFilter(filterView); + + BatchUpdateSpreadsheetRequest batchRequest1 = new BatchUpdateSpreadsheetRequest() + .setRequests(Collections.singletonList(new Request().setAddFilterView(addFilterViewRequest))); + + BatchUpdateSpreadsheetResponse response1 = service.spreadsheets() + .batchUpdate(spreadsheetId, batchRequest1) + .execute(); + + if (response1.getReplies() == null || response1.getReplies().isEmpty()) { + System.err.println("Error: No replies returned from AddFilterView request."); + return; + } + + Response reply1 = response1.getReplies().get(0); + if (reply1.getAddFilterView() == null || reply1.getAddFilterView().getFilter() == null) { + System.err.println("Error: Response did not contain AddFilterView data."); + return; + } + + int filterId = reply1.getAddFilterView().getFilter().getFilterViewId(); + + // --- Step 2: Duplicate Filter View --- + DuplicateFilterViewRequest duplicateRequest = new DuplicateFilterViewRequest() + .setFilterId(filterId); + + BatchUpdateSpreadsheetRequest batchRequest2 = new BatchUpdateSpreadsheetRequest() + .setRequests(Collections.singletonList(new Request().setDuplicateFilterView(duplicateRequest))); + + BatchUpdateSpreadsheetResponse response2 = service.spreadsheets() + .batchUpdate(spreadsheetId, batchRequest2) + .execute(); + + if (response2.getReplies() == null || response2.getReplies().isEmpty()) { + System.err.println("Error: No replies returned from DuplicateFilterView request."); + return; + } + + Response reply2 = response2.getReplies().get(0); + if (reply2.getDuplicateFilterView() == null || reply2.getDuplicateFilterView().getFilter() == null) { + System.err.println("Error: Response did not contain DuplicateFilterView data."); + return; + } + + int newFilterId = reply2.getDuplicateFilterView().getFilter().getFilterViewId(); + + // --- Step 3: Update Filter View --- + // Extract the new ID from the duplicate response + int newFilterId = response2.getReplies().get(0) + .getDuplicateFilterView().getFilter().getFilterViewId(); + + // Create update criteria + Map updateCriteriaMap = new HashMap<>(); + updateCriteriaMap.put("0", new FilterCriteria()); // Empty criteria + + ConditionValue numValue = new ConditionValue().setUserEnteredValue("5"); + BooleanCondition numCondition = new BooleanCondition() + .setType("NUMBER_GREATER") + .setValues(Collections.singletonList(numValue)); + updateCriteriaMap.put("3", new FilterCriteria().setCondition(numCondition)); + + FilterView updateFilterView = new FilterView() + .setFilterViewId(newFilterId) + .setTitle("Updated Filter") + .setCriteria(updateCriteriaMap); + + UpdateFilterViewRequest updateRequest = new UpdateFilterViewRequest() + .setFilter(updateFilterView) + .setFields("criteria,title"); + + BatchUpdateSpreadsheetRequest batchRequest3 = new BatchUpdateSpreadsheetRequest() + .setRequests(Collections.singletonList(new Request().setUpdateFilterView(updateRequest))); + + BatchUpdateSpreadsheetResponse response3 = service.spreadsheets() + .batchUpdate(spreadsheetId, batchRequest3) + .execute(); + + System.out.println(response3.toPrettyString()); + + } catch (IOException | GeneralSecurityException e) { + System.err.println("An error occurred: " + e); + } + } +} + +// [END sheets_filter_views]