From 1d101ff57f704a843fb335fc7503ae7de8a46cca Mon Sep 17 00:00:00 2001 From: Manvendra-P-Singh Date: Wed, 6 Jul 2022 20:20:45 +0000 Subject: [PATCH 001/152] test: drive v3 file snippets patch2 (#242) * git-on-borg files of gmail-api-snippets * Update build.gradle test12 * Update build.gradle * Drive-v3: File snippets UnitTest patch2 Co-authored-by: sanjuktaghosh7 Co-authored-by: Rajesh Mudaliyar --- .../drive_v3/src/main/java/UploadToFolder.java | 2 +- .../src/main/java/UploadWithConversion.java | 2 +- .../src/test/java/TestUploadToFolder.java | 18 ++++++++++++++++++ .../test/java/TestUploadWithConversion.java | 16 ++++++++++++++++ 4 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 drive/snippets/drive_v3/src/test/java/TestUploadToFolder.java create mode 100644 drive/snippets/drive_v3/src/test/java/TestUploadWithConversion.java diff --git a/drive/snippets/drive_v3/src/main/java/UploadToFolder.java b/drive/snippets/drive_v3/src/main/java/UploadToFolder.java index 03c711a5..db2be62f 100644 --- a/drive/snippets/drive_v3/src/main/java/UploadToFolder.java +++ b/drive/snippets/drive_v3/src/main/java/UploadToFolder.java @@ -38,7 +38,7 @@ public class UploadToFolder { * @return Inserted file metadata if successful, {@code null} otherwise. * @throws IOException if service account credentials file not found. */ - private static File uploadToFolder(String realFolderId) throws IOException { + public static File uploadToFolder(String realFolderId) 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. diff --git a/drive/snippets/drive_v3/src/main/java/UploadWithConversion.java b/drive/snippets/drive_v3/src/main/java/UploadWithConversion.java index dca7e60a..21d871b5 100644 --- a/drive/snippets/drive_v3/src/main/java/UploadWithConversion.java +++ b/drive/snippets/drive_v3/src/main/java/UploadWithConversion.java @@ -36,7 +36,7 @@ public class UploadWithConversion { * @return Inserted file id if successful, {@code null} otherwise. * @throws IOException if service account credentials file not found. */ - private static String uploadWithConversion() throws IOException { + public static String uploadWithConversion() 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. diff --git a/drive/snippets/drive_v3/src/test/java/TestUploadToFolder.java b/drive/snippets/drive_v3/src/test/java/TestUploadToFolder.java new file mode 100644 index 00000000..bf4702e9 --- /dev/null +++ b/drive/snippets/drive_v3/src/test/java/TestUploadToFolder.java @@ -0,0 +1,18 @@ +import com.google.api.services.drive.model.File; +import org.junit.Test; + +import java.io.IOException; +import java.security.GeneralSecurityException; + +import static org.junit.Assert.assertTrue; + +public class TestUploadToFolder extends BaseTest{ + @Test + public void uploadToFolder() throws IOException, GeneralSecurityException { + String folderId = CreateFolder.createFolder(); + File file = UploadToFolder.uploadToFolder(folderId); + assertTrue(file.getParents().contains(folderId)); + deleteFileOnCleanup(file.getId()); + deleteFileOnCleanup(folderId); + } +} diff --git a/drive/snippets/drive_v3/src/test/java/TestUploadWithConversion.java b/drive/snippets/drive_v3/src/test/java/TestUploadWithConversion.java new file mode 100644 index 00000000..a3d69c52 --- /dev/null +++ b/drive/snippets/drive_v3/src/test/java/TestUploadWithConversion.java @@ -0,0 +1,16 @@ +import org.junit.Test; + +import java.io.IOException; +import java.security.GeneralSecurityException; + +import static org.junit.Assert.assertNotNull; + +public class TestUploadWithConversion extends BaseTest{ + @Test + public void uploadWithConversion() + throws IOException, GeneralSecurityException { + String id = UploadWithConversion.uploadWithConversion(); + assertNotNull(id); + deleteFileOnCleanup(id); + } +} From a5e8727fb3c1e745f46b7544a5d2e58e3ac78c53 Mon Sep 17 00:00:00 2001 From: Manvendra-P-Singh Date: Wed, 6 Jul 2022 20:21:13 +0000 Subject: [PATCH 002/152] test: drive v3 file snippets patch3 (#243) * git-on-borg files of gmail-api-snippets * Update build.gradle test12 * Update build.gradle * Drive-v3: File snippets UnitTest patch3 Co-authored-by: sanjuktaghosh7 Co-authored-by: Rajesh Mudaliyar --- .../drive_v3/src/main/java/CreateShortcut.java | 3 ++- .../drive_v3/src/main/java/DownloadFile.java | 2 +- .../drive_v3/src/main/java/ExportPdf.java | 2 +- .../drive_v3/src/main/java/TouchFile.java | 2 +- .../src/test/java/TestCreateShortcut.java | 15 +++++++++++++++ .../src/test/java/TestDownloadFile.java | 18 ++++++++++++++++++ .../drive_v3/src/test/java/TestExportPdf.java | 16 ++++++++++++++++ .../drive_v3/src/test/java/TestTouchFile.java | 16 ++++++++++++++++ 8 files changed, 70 insertions(+), 4 deletions(-) create mode 100644 drive/snippets/drive_v3/src/test/java/TestCreateShortcut.java create mode 100644 drive/snippets/drive_v3/src/test/java/TestDownloadFile.java create mode 100644 drive/snippets/drive_v3/src/test/java/TestExportPdf.java create mode 100644 drive/snippets/drive_v3/src/test/java/TestTouchFile.java diff --git a/drive/snippets/drive_v3/src/main/java/CreateShortcut.java b/drive/snippets/drive_v3/src/main/java/CreateShortcut.java index 98b35603..d75f104e 100644 --- a/drive/snippets/drive_v3/src/main/java/CreateShortcut.java +++ b/drive/snippets/drive_v3/src/main/java/CreateShortcut.java @@ -34,7 +34,7 @@ public class CreateShortcut { * Creates shortcut for file. * @throws IOException if service account credentials file not found. */ - private static void createShortcut() throws IOException{ + public static String createShortcut() 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.*/ @@ -57,6 +57,7 @@ private static void createShortcut() throws IOException{ .setFields("id") .execute(); System.out.println("File ID: " + file.getId()); + return file.getId(); }catch (GoogleJsonResponseException e) { // TODO(developer) - handle error appropriately System.err.println("Unable to create shortcut: " + e.getDetails()); diff --git a/drive/snippets/drive_v3/src/main/java/DownloadFile.java b/drive/snippets/drive_v3/src/main/java/DownloadFile.java index 8cf14a80..0931acc5 100644 --- a/drive/snippets/drive_v3/src/main/java/DownloadFile.java +++ b/drive/snippets/drive_v3/src/main/java/DownloadFile.java @@ -37,7 +37,7 @@ public class DownloadFile { * @return byte array stream if successful, {@code null} otherwise. * @throws IOException if service account credentials file not found. */ - private static ByteArrayOutputStream downloadFile(String realFileId) throws IOException{ + public static ByteArrayOutputStream downloadFile(String realFileId) 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.*/ diff --git a/drive/snippets/drive_v3/src/main/java/ExportPdf.java b/drive/snippets/drive_v3/src/main/java/ExportPdf.java index fbc5f047..16d86539 100644 --- a/drive/snippets/drive_v3/src/main/java/ExportPdf.java +++ b/drive/snippets/drive_v3/src/main/java/ExportPdf.java @@ -37,7 +37,7 @@ public class ExportPdf { * @return byte array stream if successful, {@code null} otherwise. * @throws IOException if service account credentials file not found. */ - private static ByteArrayOutputStream exportPdf(String realFileId) throws IOException{ + public static ByteArrayOutputStream exportPdf(String realFileId) 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. diff --git a/drive/snippets/drive_v3/src/main/java/TouchFile.java b/drive/snippets/drive_v3/src/main/java/TouchFile.java index f243e16a..2729133c 100644 --- a/drive/snippets/drive_v3/src/main/java/TouchFile.java +++ b/drive/snippets/drive_v3/src/main/java/TouchFile.java @@ -38,7 +38,7 @@ public class TouchFile { * @return long file's latest modification date value. * @throws IOException if service account credentials file not found. * */ - private static long touchFile(String realFileId, long realTimestamp) + public static long touchFile(String realFileId, long realTimestamp) throws IOException { /*Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for diff --git a/drive/snippets/drive_v3/src/test/java/TestCreateShortcut.java b/drive/snippets/drive_v3/src/test/java/TestCreateShortcut.java new file mode 100644 index 00000000..a9aec655 --- /dev/null +++ b/drive/snippets/drive_v3/src/test/java/TestCreateShortcut.java @@ -0,0 +1,15 @@ +import org.junit.Test; + +import java.io.IOException; +import java.security.GeneralSecurityException; + +import static org.junit.Assert.assertNotNull; + +public class TestCreateShortcut extends BaseTest{ + @Test + public void createShortcut() throws IOException, GeneralSecurityException { + String id = CreateShortcut.createShortcut(); + assertNotNull(id); + deleteFileOnCleanup(id); + } +} diff --git a/drive/snippets/drive_v3/src/test/java/TestDownloadFile.java b/drive/snippets/drive_v3/src/test/java/TestDownloadFile.java new file mode 100644 index 00000000..2c4806f6 --- /dev/null +++ b/drive/snippets/drive_v3/src/test/java/TestDownloadFile.java @@ -0,0 +1,18 @@ +import org.junit.Test; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.security.GeneralSecurityException; + +import static org.junit.Assert.assertEquals; + +public class TestDownloadFile extends BaseTest{ + @Test + public void downloadFile() throws IOException, GeneralSecurityException { + String id = createTestBlob(); + ByteArrayOutputStream out = DownloadFile.downloadFile(id); + byte[] bytes = out.toByteArray(); + assertEquals((byte) 0xFF, bytes[0]); + assertEquals((byte) 0xD8, bytes[1]); + } +} diff --git a/drive/snippets/drive_v3/src/test/java/TestExportPdf.java b/drive/snippets/drive_v3/src/test/java/TestExportPdf.java new file mode 100644 index 00000000..f8741feb --- /dev/null +++ b/drive/snippets/drive_v3/src/test/java/TestExportPdf.java @@ -0,0 +1,16 @@ +import org.junit.Test; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.security.GeneralSecurityException; + +import static org.junit.Assert.assertEquals; + +public class TestExportPdf extends BaseTest{ + @Test + public void exportPdf() throws IOException, GeneralSecurityException { + String id = createTestDocument(); + ByteArrayOutputStream out = ExportPdf.exportPdf(id); + assertEquals("%PDF", out.toString("UTF-8").substring(0, 4)); + } +} diff --git a/drive/snippets/drive_v3/src/test/java/TestTouchFile.java b/drive/snippets/drive_v3/src/test/java/TestTouchFile.java new file mode 100644 index 00000000..3280bcbb --- /dev/null +++ b/drive/snippets/drive_v3/src/test/java/TestTouchFile.java @@ -0,0 +1,16 @@ +import org.junit.Test; + +import java.io.IOException; +import java.security.GeneralSecurityException; + +import static org.junit.Assert.assertEquals; + +public class TestTouchFile extends BaseTest{ + @Test + public void touchFile() throws IOException, GeneralSecurityException { + String id = this.createTestBlob(); + long now = System.currentTimeMillis(); + long modifiedTime = TouchFile.touchFile(id, now); + assertEquals(now, modifiedTime); + } +} From 9647a4a59b1e6cea61d36133464acfe0e4e73e0b Mon Sep 17 00:00:00 2001 From: Sanjukta Ghosh Date: Wed, 13 Jul 2022 16:11:29 +0000 Subject: [PATCH 003/152] test: added testcase for slide snippets (#245) * git-on-borg files of gmail-api-snippets * Update build.gradle test12 * Update build.gradle * test: added testcase for slide snippets * test: added testcase for slide snippets * fix: update in slide snippets Co-authored-by: Rajesh Mudaliyar Co-authored-by: Manvendra-P-Singh Co-authored-by: himanshupr2627 --- .../snippets/src/main/java/CreateImage.java | 3 +- .../snippets/src/main/java/CreateSlide.java | 5 +- slides/snippets/src/main/java/Snippets.java | 450 ------------------ slides/snippets/src/test/java/BaseTest.java | 108 ++--- .../snippets/src/test/java/SnippetsTest.java | 160 ------- .../src/test/java/TestCopyPresentation.java | 31 ++ .../src/test/java/TestCreateBulletedText.java | 35 ++ .../src/test/java/TestCreateImage.java | 39 ++ .../src/test/java/TestCreatePresentation.java | 30 ++ .../src/test/java/TestCreateSheetsChart.java | 40 ++ .../src/test/java/TestCreateSlide.java | 37 ++ .../test/java/TestCreateTextboxWithText.java | 38 ++ .../src/test/java/TestImageMerging.java | 45 ++ .../src/test/java/TestRefreshSheetsChart.java | 38 ++ .../src/test/java/TestSimpleTextReplace.java | 35 ++ .../src/test/java/TestTextMerging.java | 46 ++ .../src/test/java/TestTextStyleUpdate.java | 35 ++ 17 files changed, 482 insertions(+), 693 deletions(-) delete mode 100644 slides/snippets/src/main/java/Snippets.java delete mode 100644 slides/snippets/src/test/java/SnippetsTest.java create mode 100644 slides/snippets/src/test/java/TestCopyPresentation.java create mode 100644 slides/snippets/src/test/java/TestCreateBulletedText.java create mode 100644 slides/snippets/src/test/java/TestCreateImage.java create mode 100644 slides/snippets/src/test/java/TestCreatePresentation.java create mode 100644 slides/snippets/src/test/java/TestCreateSheetsChart.java create mode 100644 slides/snippets/src/test/java/TestCreateSlide.java create mode 100644 slides/snippets/src/test/java/TestCreateTextboxWithText.java create mode 100644 slides/snippets/src/test/java/TestImageMerging.java create mode 100644 slides/snippets/src/test/java/TestRefreshSheetsChart.java create mode 100644 slides/snippets/src/test/java/TestSimpleTextReplace.java create mode 100644 slides/snippets/src/test/java/TestTextMerging.java create mode 100644 slides/snippets/src/test/java/TestTextStyleUpdate.java diff --git a/slides/snippets/src/main/java/CreateImage.java b/slides/snippets/src/main/java/CreateImage.java index 6338d405..132b3493 100644 --- a/slides/snippets/src/main/java/CreateImage.java +++ b/slides/snippets/src/main/java/CreateImage.java @@ -46,14 +46,12 @@ public class CreateImage { * * @param presentationId - id of the presentation. * @param slideId - id of the shape. - * @param imageId - id for the image. * @param imageUrl - Url of the image. * @return image id * @throws IOException - if credentials file not found. */ public static BatchUpdatePresentationResponse createImage(String presentationId, String slideId, - String imageId, String imageUrl) throws IOException { /* Load pre-authorized user credentials from the environment. @@ -73,6 +71,7 @@ public static BatchUpdatePresentationResponse createImage(String presentationId, // Create a new image, using the supplied object ID, with content downloaded from imageUrl. List requests = new ArrayList<>(); + String imageId = "MyImageId_01"; Dimension emu4M = new Dimension().setMagnitude(4000000.0).setUnit("EMU"); requests.add(new Request() .setCreateImage(new CreateImageRequest() diff --git a/slides/snippets/src/main/java/CreateSlide.java b/slides/snippets/src/main/java/CreateSlide.java index c1a55b99..9a809264 100644 --- a/slides/snippets/src/main/java/CreateSlide.java +++ b/slides/snippets/src/main/java/CreateSlide.java @@ -41,12 +41,10 @@ public class CreateSlide { * Creates a new slide. * * @param presentationId - id of the presentation. - * @param slideId - id for the new slide. * @return slide id * @throws IOException - if credentials file not found. */ - public static BatchUpdatePresentationResponse createSlide(String presentationId, - String slideId) throws IOException { + public static BatchUpdatePresentationResponse createSlide(String presentationId) 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. */ @@ -64,6 +62,7 @@ public static BatchUpdatePresentationResponse createSlide(String presentationId, // Add a slide at index 1 using the predefined "TITLE_AND_TWO_COLUMNS" layout List requests = new ArrayList<>(); + String slideId = "MyNewSlide_001"; BatchUpdatePresentationResponse response = null; try { requests.add(new Request() diff --git a/slides/snippets/src/main/java/Snippets.java b/slides/snippets/src/main/java/Snippets.java deleted file mode 100644 index c1c07907..00000000 --- a/slides/snippets/src/main/java/Snippets.java +++ /dev/null @@ -1,450 +0,0 @@ -import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; -import com.google.api.services.drive.Drive; -import com.google.api.services.drive.model.File; -import com.google.api.services.sheets.v4.Sheets; -import com.google.api.services.sheets.v4.model.ValueRange; -import com.google.api.services.slides.v1.Slides; -import com.google.api.services.slides.v1.model.*; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -public class Snippets { - - private Slides service; - private Drive driveService; - private Sheets sheetsService; - - Snippets(Slides service, Drive driveService, Sheets sheetsService) { - this.service = service; - this.driveService = driveService; - this.sheetsService = sheetsService; - } - - public String createPresentation(String title) throws IOException { - Slides slidesService = this.service; - // [START slides_create_presentation] - Presentation presentation = new Presentation() - .setTitle(title); - presentation = slidesService.presentations().create(presentation) - .setFields("presentationId") - .execute(); - System.out.println("Created presentation with ID: " + presentation.getPresentationId()); - // [END slides_create_presentation] - return presentation.getPresentationId(); - } - - public String copyPresentation(String presentationId, String copyTitle) throws IOException { - Drive driveService = this.driveService; - // [START slides_copy_presentation] - File copyMetadata = new File().setName(copyTitle); - File presentationCopyFile = - driveService.files().copy(presentationId, copyMetadata).execute(); - String presentationCopyId = presentationCopyFile.getId(); - // [END slides_copy_presentation] - return presentationCopyId; - } - - public BatchUpdatePresentationResponse createSlide(String presentationId) throws IOException { - Slides slidesService = this.service; - // [START slides_create_slide] - // Add a slide at index 1 using the predefined "TITLE_AND_TWO_COLUMNS" layout - // and the ID "MyNewSlide_001". - List requests = new ArrayList<>(); - String slideId = "MyNewSlide_001"; - requests.add(new Request() - .setCreateSlide(new CreateSlideRequest() - .setObjectId(slideId) - .setInsertionIndex(1) - .setSlideLayoutReference(new LayoutReference() - .setPredefinedLayout("TITLE_AND_TWO_COLUMNS")))); - - // If you wish to populate the slide with elements, add create requests here, - // using the slide ID specified above. - - // Execute the request. - BatchUpdatePresentationRequest body = - new BatchUpdatePresentationRequest().setRequests(requests); - BatchUpdatePresentationResponse response = - slidesService.presentations().batchUpdate(presentationId, body).execute(); - CreateSlideResponse createSlideResponse = response.getReplies().get(0).getCreateSlide(); - System.out.println("Created slide with ID: " + createSlideResponse.getObjectId()); - // [END slides_create_slide] - return response; - } - - public BatchUpdatePresentationResponse createTextBoxWithText( - String presentationId, String slideId) throws IOException { - Slides slidesService = this.service; - // [START slides_create_textbox_with_text] - // Create a new square text box, using a supplied object ID. - List requests = new ArrayList<>(); - String textBoxId = "MyTextBox_01"; - Dimension pt350 = new Dimension().setMagnitude(350.0).setUnit("PT"); - requests.add(new Request() - .setCreateShape(new CreateShapeRequest() - .setObjectId(textBoxId) - .setShapeType("TEXT_BOX") - .setElementProperties(new PageElementProperties() - .setPageObjectId(slideId) - .setSize(new Size() - .setHeight(pt350) - .setWidth(pt350)) - .setTransform(new AffineTransform() - .setScaleX(1.0) - .setScaleY(1.0) - .setTranslateX(350.0) - .setTranslateY(100.0) - .setUnit("PT"))))); - - // Insert text into the box, using the object ID given to it. - requests.add(new Request() - .setInsertText(new InsertTextRequest() - .setObjectId(textBoxId) - .setInsertionIndex(0) - .setText("New Box Text Inserted"))); - - // Execute the requests. - BatchUpdatePresentationRequest body = - new BatchUpdatePresentationRequest().setRequests(requests); - BatchUpdatePresentationResponse response = - slidesService.presentations().batchUpdate(presentationId, body).execute(); - CreateShapeResponse createShapeResponse = response.getReplies().get(0).getCreateShape(); - System.out.println("Created textbox with ID: " + createShapeResponse.getObjectId()); - // [END slides_create_textbox_with_text] - return response; - } - - - public BatchUpdatePresentationResponse createImage(String presentationId, - String slideId, - GoogleCredential credential) - throws IOException { - Slides slidesService = this.service; - // [START slides_create_image] - String imageUrl = "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"; - - // Create a new image, using the supplied object ID, with content downloaded from imageUrl. - List requests = new ArrayList<>(); - String imageId = "MyImageId_01"; - Dimension emu4M = new Dimension().setMagnitude(4000000.0).setUnit("EMU"); - requests.add(new Request() - .setCreateImage(new CreateImageRequest() - .setObjectId(imageId) - .setUrl(imageUrl) - .setElementProperties(new PageElementProperties() - .setPageObjectId(slideId) - .setSize(new Size() - .setHeight(emu4M) - .setWidth(emu4M)) - .setTransform(new AffineTransform() - .setScaleX(1.0) - .setScaleY(1.0) - .setTranslateX(100000.0) - .setTranslateY(100000.0) - .setUnit("EMU"))))); - - // Execute the request. - BatchUpdatePresentationRequest body = - new BatchUpdatePresentationRequest().setRequests(requests); - BatchUpdatePresentationResponse response = - slidesService.presentations().batchUpdate(presentationId, body).execute(); - CreateImageResponse createImageResponse = response.getReplies().get(0).getCreateImage(); - System.out.println("Created image with ID: " + createImageResponse.getObjectId()); - // [END slides_create_image] - return response; - } - - public List textMerging( - String templatePresentationId, String dataSpreadsheetId) throws IOException { - Slides slidesService = this.service; - Drive driveService = this.driveService; - Sheets sheetsService = this.sheetsService; - List responses = new ArrayList<>(5); - // [START slides_text_merging] - // Use the Sheets API to load data, one record per row. - String dataRangeNotation = "Customers!A2:M6"; - ValueRange sheetsResponse = sheetsService.spreadsheets().values() - .get(dataSpreadsheetId, dataRangeNotation).execute(); - List> values = sheetsResponse.getValues(); - - // For each record, create a new merged presentation. - for (List row: values) { - String customerName = row.get(2).toString(); // name in column 3 - String caseDescription = row.get(5).toString(); // case description in column 6 - String totalPortfolio = row.get(11).toString(); // total portfolio in column 12 - - // Duplicate the template presentation using the Drive API. - String copyTitle = customerName + " presentation"; - File content = new File().setName(copyTitle); - File presentationFile = - driveService.files().copy(templatePresentationId, content).execute(); - String presentationId = presentationFile.getId(); - - // Create the text merge (replaceAllText) requests for this presentation. - List requests = new ArrayList<>(); - requests.add(new Request() - .setReplaceAllText(new ReplaceAllTextRequest() - .setContainsText(new SubstringMatchCriteria() - .setText("{{customer-name}}") - .setMatchCase(true)) - .setReplaceText(customerName))); - requests.add(new Request() - .setReplaceAllText(new ReplaceAllTextRequest() - .setContainsText(new SubstringMatchCriteria() - .setText("{{case-description}}") - .setMatchCase(true)) - .setReplaceText(caseDescription))); - requests.add(new Request() - .setReplaceAllText(new ReplaceAllTextRequest() - .setContainsText(new SubstringMatchCriteria() - .setText("{{total-portfolio}}") - .setMatchCase(true)) - .setReplaceText(totalPortfolio))); - - // Execute the requests for this presentation. - BatchUpdatePresentationRequest body = - new BatchUpdatePresentationRequest().setRequests(requests); - BatchUpdatePresentationResponse response = - slidesService.presentations().batchUpdate(presentationId, body).execute(); - // [START_EXCLUDE silent] - responses.add(response); - // [END_EXCLUDE] - // Count total number of replacements made. - int numReplacements = 0; - for (Response resp : response.getReplies()) { - numReplacements += resp.getReplaceAllText().getOccurrencesChanged(); - } - - System.out.println("Created merged presentation for " + - customerName + " with ID: " + presentationId); - System.out.println("Replaced " + numReplacements + " text instances."); - } - // [END slides_text_merging] - return responses; - } - - public BatchUpdatePresentationResponse imageMerging(String templatePresentationId, - String imageUrl, - String customerName) throws IOException { - Slides slidesService = this.service; - Drive driveService = this.driveService; - String logoUrl = imageUrl; - String customerGraphicUrl = imageUrl; - - // [START slides_image_merging] - // Duplicate the template presentation using the Drive API. - String copyTitle = customerName + " presentation"; - File content = new File().setName(copyTitle); - File presentationFile = - driveService.files().copy(templatePresentationId, content).execute(); - String presentationId = presentationFile.getId(); - - // Create the image merge (replaceAllShapesWithImage) requests. - List requests = new ArrayList<>(); - requests.add(new Request() - .setReplaceAllShapesWithImage(new ReplaceAllShapesWithImageRequest() - .setImageUrl(logoUrl) - .setReplaceMethod("CENTER_INSIDE") - .setContainsText(new SubstringMatchCriteria() - .setText("{{company-logo}}") - .setMatchCase(true)))); - requests.add(new Request() - .setReplaceAllShapesWithImage(new ReplaceAllShapesWithImageRequest() - .setImageUrl(customerGraphicUrl) - .setReplaceMethod("CENTER_INSIDE") - .setContainsText(new SubstringMatchCriteria() - .setText("{{customer-graphic}}") - .setMatchCase(true)))); - - // Execute the requests. - BatchUpdatePresentationRequest body = - new BatchUpdatePresentationRequest().setRequests(requests); - BatchUpdatePresentationResponse response = - slidesService.presentations().batchUpdate(presentationId, body).execute(); - - // Count total number of replacements made. - int numReplacements = 0; - for(Response resp: response.getReplies()) { - numReplacements += resp.getReplaceAllShapesWithImage().getOccurrencesChanged(); - } - - System.out.println("Created merged presentation with ID: " + presentationId); - System.out.println("Replaced " + numReplacements + " shapes instances with images."); - // [END slides_image_merging] - return response; - } - - public BatchUpdatePresentationResponse simpleTextReplace( - String presentationId, String shapeId, String replacementText) throws IOException { - Slides slidesService = this.service; - // [START slides_simple_text_replace] - // Remove existing text in the shape, then insert the new text. - List requests = new ArrayList<>(); - requests.add(new Request() - .setDeleteText(new DeleteTextRequest() - .setObjectId(shapeId) - .setTextRange(new Range() - .setType("ALL")))); - requests.add(new Request() - .setInsertText(new InsertTextRequest() - .setObjectId(shapeId) - .setInsertionIndex(0) - .setText(replacementText))); - - // Execute the requests. - BatchUpdatePresentationRequest body = - new BatchUpdatePresentationRequest().setRequests(requests); - BatchUpdatePresentationResponse response = - slidesService.presentations().batchUpdate(presentationId, body).execute(); - - System.out.println("Replaced text in shape with ID: " + shapeId); - // [END slides_simple_text_replace] - return response; - } - - public BatchUpdatePresentationResponse textStyleUpdate(String presentationId, String shapeId) - throws IOException { - Slides slidesService = this.service; - // [START slides_text_style_update] - // Update the text style so that the first 5 characters are bolded - // and italicized, and the next 5 are displayed in blue 14 pt Times - // New Roman font, and the next five are hyperlinked. - List requests = new ArrayList<>(); - requests.add(new Request() - .setUpdateTextStyle(new UpdateTextStyleRequest() - .setObjectId(shapeId) - .setTextRange(new Range() - .setType("FIXED_RANGE") - .setStartIndex(0) - .setEndIndex(5)) - .setStyle(new TextStyle() - .setBold(true) - .setItalic(true)) - .setFields("bold,italic"))); - requests.add(new Request() - .setUpdateTextStyle(new UpdateTextStyleRequest() - .setObjectId(shapeId) - .setTextRange(new Range() - .setType("FIXED_RANGE") - .setStartIndex(5) - .setEndIndex(10)) - .setStyle(new TextStyle() - .setFontFamily("Times New Roman") - .setFontSize(new Dimension() - .setMagnitude(14.0) - .setUnit("PT")) - .setForegroundColor(new OptionalColor() - .setOpaqueColor(new OpaqueColor() - .setRgbColor(new RgbColor() - .setBlue(1.0F) - .setGreen(0.0F) - .setRed(0.0F))))) - .setFields("foregroundColor,fontFamily,fontSize"))); - requests.add(new Request() - .setUpdateTextStyle(new UpdateTextStyleRequest() - .setObjectId(shapeId) - .setTextRange(new Range() - .setType("FIXED_RANGE") - .setStartIndex(10) - .setEndIndex(15)) - .setStyle(new TextStyle() - .setLink(new Link() - .setUrl("www.example.com"))) - .setFields("link"))); - - // Execute the requests. - BatchUpdatePresentationRequest body = - new BatchUpdatePresentationRequest().setRequests(requests); - BatchUpdatePresentationResponse response = - slidesService.presentations().batchUpdate(presentationId, body).execute(); - - System.out.println("Updated text style for shape with ID: " + shapeId); - // [END slides_text_style_update] - return response; - } - - public BatchUpdatePresentationResponse createBulletedText(String presentationId, - String shapeId) throws IOException { - Slides slidesService = this.service; - // [START slides_create_bulleted_text] - // Add arrow-diamond-disc bullets to all text in the shape. - List requests = new ArrayList<>(); - requests.add(new Request() - .setCreateParagraphBullets(new CreateParagraphBulletsRequest() - .setObjectId(shapeId) - .setTextRange(new Range() - .setType("ALL")) - .setBulletPreset("BULLET_ARROW_DIAMOND_DISC"))); - - // Execute the request. - BatchUpdatePresentationRequest body = - new BatchUpdatePresentationRequest().setRequests(requests); - BatchUpdatePresentationResponse response = - slidesService.presentations().batchUpdate(presentationId, body).execute(); - System.out.println("Added bullets to text in shape with ID: " + shapeId); - // [END slides_create_bulleted_text] - return response; - } - - public BatchUpdatePresentationResponse createSheetsChart( - String presentationId, String pageId, String spreadsheetId, Integer sheetChartId) - throws IOException { - Slides slidesService = this.service; - // [START slides_create_sheets_chart] - // Embed a Sheets chart (indicated by the spreadsheetId and sheetChartId) onto - // a page in the presentation. Setting the linking mode as "LINKED" allows the - // chart to be refreshed if the Sheets version is updated. - List requests = new ArrayList<>(); - Dimension emu4M = new Dimension().setMagnitude(4000000.0).setUnit("EMU"); - String presentationChartId = "MyEmbeddedChart"; - requests.add(new Request() - .setCreateSheetsChart(new CreateSheetsChartRequest() - .setObjectId(presentationChartId) - .setSpreadsheetId(spreadsheetId) - .setChartId(sheetChartId) - .setLinkingMode("LINKED") - .setElementProperties(new PageElementProperties() - .setPageObjectId(pageId) - .setSize(new Size() - .setHeight(emu4M) - .setWidth(emu4M)) - .setTransform(new AffineTransform() - .setScaleX(1.0) - .setScaleY(1.0) - .setTranslateX(100000.0) - .setTranslateY(100000.0) - .setUnit("EMU"))))); - - // Execute the request. - BatchUpdatePresentationRequest body = - new BatchUpdatePresentationRequest().setRequests(requests); - BatchUpdatePresentationResponse response = - slidesService.presentations().batchUpdate(presentationId, body).execute(); - System.out.println("Added a linked Sheets chart with ID " + presentationChartId); - // [END slides_create_sheets_chart] - return response; - } - - public BatchUpdatePresentationResponse refreshSheetsChart( - String presentationId, String presentationChartId) throws IOException { - Slides slidesService = this.service; - // [START slides_refresh_sheets_chart] - List requests = new ArrayList<>(); - - // Refresh an existing linked Sheets chart embedded a presentation. - requests.add(new Request() - .setRefreshSheetsChart(new RefreshSheetsChartRequest() - .setObjectId(presentationChartId))); - - // Execute the request. - BatchUpdatePresentationRequest body = - new BatchUpdatePresentationRequest().setRequests(requests); - BatchUpdatePresentationResponse response = - slidesService.presentations().batchUpdate(presentationId, body).execute(); - System.out.println("Refreshed a linked Sheets chart with ID " + presentationChartId); - // [END slides_refresh_sheets_chart] - return response; - } -} diff --git a/slides/snippets/src/test/java/BaseTest.java b/slides/snippets/src/test/java/BaseTest.java index 99e97610..f88fec7c 100644 --- a/slides/snippets/src/test/java/BaseTest.java +++ b/slides/snippets/src/test/java/BaseTest.java @@ -1,117 +1,71 @@ -import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; -import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; -import com.google.api.client.http.HttpTransport; -import com.google.api.client.json.jackson2.JacksonFactory; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.drive.Drive; -import com.google.api.services.drive.DriveScopes; import com.google.api.services.sheets.v4.Sheets; import com.google.api.services.slides.v1.Slides; +import com.google.api.services.slides.v1.SlidesScopes; import com.google.api.services.slides.v1.model.*; - import java.io.IOException; import java.security.GeneralSecurityException; import java.util.*; import java.util.List; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.LogRecord; -import java.util.logging.Logger; -import org.junit.After; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; import org.junit.Before; +import org.junit.After; public class BaseTest { - static { - enableLogging(); - } - - protected GoogleCredential credential; protected Slides service; protected Drive driveService; protected Sheets sheetsService; - protected Set filesToDelete = new HashSet<>(); - - - public static void enableLogging() { - Logger logger = Logger.getLogger(HttpTransport.class.getName()); - logger.setLevel(Level.INFO); - logger.addHandler(new Handler() { - - @Override - public void close() throws SecurityException { - } - - @Override - public void flush() { - } - - @Override - public void publish(LogRecord record) { - // default ConsoleHandler will print >= INFO to System.err - if (record.getLevel().intValue() < Level.INFO.intValue()) { - System.out.println(record.getMessage()); - } - } - }); - } - public GoogleCredential getCredential() throws IOException { - return GoogleCredential.getApplicationDefault() - .createScoped(Arrays.asList(DriveScopes.DRIVE)); + public GoogleCredentials getCredential() 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(SlidesScopes.PRESENTATIONS, SlidesScopes.DRIVE); + return credentials; } - public Slides buildService(GoogleCredential credential) - throws IOException, GeneralSecurityException { + public Slides buildService(GoogleCredentials credential) { return new Slides.Builder( - GoogleNetHttpTransport.newTrustedTransport(), - JacksonFactory.getDefaultInstance(), - credential) + new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + new HttpCredentialsAdapter(credential)) .setApplicationName("Slides API Snippets") .build(); } - public Drive buildDriveService(GoogleCredential credential) - throws IOException, GeneralSecurityException { + public Drive buildDriveService(GoogleCredentials credential) { return new Drive.Builder( - GoogleNetHttpTransport.newTrustedTransport(), - JacksonFactory.getDefaultInstance(), - credential) + new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + new HttpCredentialsAdapter(credential)) .setApplicationName("Slides API Snippets") .build(); } - public Sheets buildSheetsService(GoogleCredential credential) - throws IOException, GeneralSecurityException { + public Sheets buildSheetsService(GoogleCredentials credential) { return new Sheets.Builder( - GoogleNetHttpTransport.newTrustedTransport(), - JacksonFactory.getDefaultInstance(), - credential) + new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + new HttpCredentialsAdapter(credential)) .setApplicationName("Slides API Snippets") .build(); } @Before - public void setup() throws IOException, GeneralSecurityException { - this.credential = getCredential(); + public void setup() throws IOException { + GoogleCredentials credential = getCredential(); this.service = buildService(credential); this.driveService = buildDriveService(credential); this.sheetsService = buildSheetsService(credential); - this.filesToDelete.clear(); - } - - @After - public void cleanupFiles() { - for(String id : filesToDelete) { - try { - this.driveService.files().delete(id).execute(); - } catch (IOException e) { - System.err.println("Unable to cleanup file " + id); - } - } } - protected void deleteFileOnCleanup(String id) { - filesToDelete.add(id); + protected void deleteFileOnCleanup(String id) throws IOException { + this.driveService.files().delete(id).execute(); } protected String createTestPresentation() throws IOException { @@ -120,9 +74,7 @@ protected String createTestPresentation() throws IOException { presentation = service.presentations().create(presentation) .setFields("presentationId") .execute(); - String presentationId = presentation.getPresentationId(); - this.deleteFileOnCleanup(presentationId); - return presentationId; + return presentation.getPresentationId(); } protected String createTestSlide(String presentationId) throws IOException { diff --git a/slides/snippets/src/test/java/SnippetsTest.java b/slides/snippets/src/test/java/SnippetsTest.java deleted file mode 100644 index ec2a4ce7..00000000 --- a/slides/snippets/src/test/java/SnippetsTest.java +++ /dev/null @@ -1,160 +0,0 @@ -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import com.google.api.services.slides.v1.model.*; - -import java.io.IOException; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; - -public class SnippetsTest extends BaseTest { - - private Snippets snippets; - - private final String IMAGE_URL = - "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"; - private final String TEMPLATE_PRESENTATION_ID = "1wJUN1B5CQ2wQOBzmz2apky48QNK1OsE2oNKHPMLpKDc"; - private final String DATA_SPREADSHEET_ID = "14KaZMq2aCAGt5acV77zaA_Ps8aDt04G7T0ei4KiXLX8"; - private final Integer CHART_ID = 1107320627; - - private final String CUSTOMER_NAME = "Fake Customer"; - - @Before - public void createSnippets() { - this.snippets = new Snippets(this.service, this.driveService, this.sheetsService); - } - - @Test - public void testCreatePresentation() throws IOException { - String presentationId = this.snippets.createPresentation("Title"); - assertNotNull(presentationId); - this.deleteFileOnCleanup(presentationId); - } - - @Test - public void testCopyPresentation() throws IOException { - String presentationId = this.createTestPresentation(); - String copyId = this.snippets.copyPresentation(presentationId, "My Duplicate Presentation"); - assertNotNull(copyId); - this.deleteFileOnCleanup(copyId); - } - - @Test - public void testCreateSlide() throws IOException { - String presentationId = this.createTestPresentation(); - BatchUpdatePresentationResponse response = this.snippets.createSlide(presentationId); - assertNotNull(response); - assertEquals(1, response.getReplies().size()); - String pageId = response.getReplies().get(0).getCreateSlide().getObjectId(); - assertNotNull(pageId); - } - - @Test - public void testCreateTextBox() throws IOException { - String presentationId = this.createTestPresentation(); - String pageId = this.createTestSlide(presentationId); - BatchUpdatePresentationResponse response = - this.snippets.createTextBoxWithText(presentationId, pageId); - assertEquals(2, response.getReplies().size()); - String boxId = response.getReplies().get(0).getCreateShape().getObjectId(); - assertNotNull(boxId); - } - - @Test - public void testCreateImage() throws IOException { - String presentationId = this.createTestPresentation(); - String pageId = this.createTestSlide(presentationId); - BatchUpdatePresentationResponse response = this.snippets.createImage( - presentationId, pageId, this.credential); - assertEquals(1, response.getReplies().size()); - String imageId = response.getReplies().get(0).getCreateImage().getObjectId(); - assertNotNull(imageId); - } - - @Test - public void testTextMerge() throws IOException { - List responses = - this.snippets.textMerging(TEMPLATE_PRESENTATION_ID, DATA_SPREADSHEET_ID); - for (BatchUpdatePresentationResponse response: responses) { - String presentationId = response.getPresentationId(); - assertNotNull(presentationId); - assertEquals(3, response.getReplies().size()); - int numReplacements = 0; - for (Response resp : response.getReplies()) { - numReplacements += resp.getReplaceAllText().getOccurrencesChanged(); - } - assertEquals(4, numReplacements); - this.deleteFileOnCleanup(presentationId); - } - } - - @Test - public void testImageMerge() throws IOException { - BatchUpdatePresentationResponse response = - this.snippets.imageMerging(TEMPLATE_PRESENTATION_ID, IMAGE_URL, CUSTOMER_NAME); - String presentationId = response.getPresentationId(); - assertNotNull(presentationId); - assertEquals(2, response.getReplies().size()); - int numReplacements = 0; - for(Response resp: response.getReplies()) { - numReplacements += resp.getReplaceAllShapesWithImage().getOccurrencesChanged(); - } - assertEquals(2, numReplacements); - this.deleteFileOnCleanup(presentationId); - } - - @Test - public void testSimpleTextReplace() throws IOException { - String presentationId = this.createTestPresentation(); - String pageId = this.createTestSlide(presentationId); - String boxId = this.createTestTextBox(presentationId, pageId); - BatchUpdatePresentationResponse response = - this.snippets.simpleTextReplace(presentationId, boxId, "MY NEW TEXT"); - assertEquals(2, response.getReplies().size()); - } - - @Test - public void testTextStyleUpdate() throws IOException { - String presentationId = this.createTestPresentation(); - String pageId = this.createTestSlide(presentationId); - String boxId = this.createTestTextBox(presentationId, pageId); - BatchUpdatePresentationResponse response = - this.snippets.textStyleUpdate(presentationId, boxId); - assertEquals(3, response.getReplies().size()); - } - - @Test - public void testCreateBulletText() throws IOException { - String presentationId = this.createTestPresentation(); - String pageId = this.createTestSlide(presentationId); - String boxId = this.createTestTextBox(presentationId, pageId); - BatchUpdatePresentationResponse response = - this.snippets.createBulletedText(presentationId, boxId); - assertEquals(1, response.getReplies().size()); - } - - @Test - public void testCreateSheetsChart() throws IOException { - String presentationId = this.createTestPresentation(); - String pageId = this.createTestSlide(presentationId); - BatchUpdatePresentationResponse response = - this.snippets.createSheetsChart( - presentationId, pageId, DATA_SPREADSHEET_ID, CHART_ID); - assertEquals(1, response.getReplies().size()); - String chartId = response.getReplies().get(0).getCreateSheetsChart().getObjectId(); - assertNotNull(chartId); - } - - @Test - public void testRefreshSheetsChart() throws IOException { - String presentationId = this.createTestPresentation(); - String pageId = this.createTestSlide(presentationId); - String chartId = - this.createTestSheetsChart(presentationId, pageId, DATA_SPREADSHEET_ID, CHART_ID); - BatchUpdatePresentationResponse response = - this.snippets.refreshSheetsChart(presentationId, chartId); - assertEquals(1, response.getReplies().size()); - } -} diff --git a/slides/snippets/src/test/java/TestCopyPresentation.java b/slides/snippets/src/test/java/TestCopyPresentation.java new file mode 100644 index 00000000..a4772d09 --- /dev/null +++ b/slides/snippets/src/test/java/TestCopyPresentation.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 org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertNotNull; + +// Unit testcase for copy presentation snippet +public class TestCopyPresentation extends BaseTest{ + + @Test + public void testCopyPresentation() throws IOException { + String presentationId = createTestPresentation(); + String copyId = CopyPresentation.copyPresentation(presentationId, "My Duplicate Presentation"); + assertNotNull(copyId); + deleteFileOnCleanup(copyId); + } +} diff --git a/slides/snippets/src/test/java/TestCreateBulletedText.java b/slides/snippets/src/test/java/TestCreateBulletedText.java new file mode 100644 index 00000000..c6c00cf9 --- /dev/null +++ b/slides/snippets/src/test/java/TestCreateBulletedText.java @@ -0,0 +1,35 @@ +// 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.slides.v1.model.BatchUpdatePresentationResponse; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; + +// Unit testcase for createBulletedText snippet +public class TestCreateBulletedText extends BaseTest{ + + @Test + public void testCreateBulletText() throws IOException { + String presentationId = createTestPresentation(); + String pageId = createTestSlide(presentationId); + String boxId = createTestTextBox(presentationId, pageId); + BatchUpdatePresentationResponse response = + CreateBulletedText.createBulletedText(presentationId, boxId); + assertEquals(1, response.getReplies().size()); + deleteFileOnCleanup(presentationId); + } +} diff --git a/slides/snippets/src/test/java/TestCreateImage.java b/slides/snippets/src/test/java/TestCreateImage.java new file mode 100644 index 00000000..f2493670 --- /dev/null +++ b/slides/snippets/src/test/java/TestCreateImage.java @@ -0,0 +1,39 @@ +// 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.slides.v1.model.BatchUpdatePresentationResponse; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +// Unit testcase for createImage snippet +public class TestCreateImage extends BaseTest { + + private final String IMAGE_URL = + "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"; + + @Test + public void testCreateImage() throws IOException { + String presentationId = createTestPresentation(); + String slideId = createTestSlide(presentationId); + BatchUpdatePresentationResponse response = CreateImage.createImage( + presentationId, slideId, IMAGE_URL); + assertEquals(1, response.getReplies().size()); + String imageId = response.getReplies().get(0).getCreateImage().getObjectId(); + assertNotNull(imageId); + } +} diff --git a/slides/snippets/src/test/java/TestCreatePresentation.java b/slides/snippets/src/test/java/TestCreatePresentation.java new file mode 100644 index 00000000..8a44c76c --- /dev/null +++ b/slides/snippets/src/test/java/TestCreatePresentation.java @@ -0,0 +1,30 @@ +// 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 org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertNotNull; + +// Unit testcase for createPresentation snippet +public class TestCreatePresentation extends BaseTest{ + + @Test + public void testCreatePresentation() throws IOException { + String presentationId = CreatePresentation.createPresentation("Title"); + assertNotNull(presentationId); + deleteFileOnCleanup(presentationId); + } +} diff --git a/slides/snippets/src/test/java/TestCreateSheetsChart.java b/slides/snippets/src/test/java/TestCreateSheetsChart.java new file mode 100644 index 00000000..c4905b83 --- /dev/null +++ b/slides/snippets/src/test/java/TestCreateSheetsChart.java @@ -0,0 +1,40 @@ +// 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.slides.v1.model.BatchUpdatePresentationResponse; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +// Unit testcase for createSheetsChart snippet +public class TestCreateSheetsChart extends BaseTest{ + // TODO(developer) - change the IDs before executing + private final String DATA_SPREADSHEET_ID = "1ZCGbdHSvLnp776gDGSGtkEBxWQ-FDMuWEF4EOSmeDDw"; + private final Integer CHART_ID = 1107320627; + @Test + public void testCreateSheetsChart() throws IOException { + String presentationId = this.createTestPresentation(); + String pageId = this.createTestSlide(presentationId); + BatchUpdatePresentationResponse response = + CreateSheetsChart.createSheetsChart( + presentationId, pageId, DATA_SPREADSHEET_ID, CHART_ID); + assertEquals(1, response.getReplies().size()); + String chartId = response.getReplies().get(0).getCreateSheetsChart().getObjectId(); + assertNotNull(chartId); + deleteFileOnCleanup(presentationId); + } +} diff --git a/slides/snippets/src/test/java/TestCreateSlide.java b/slides/snippets/src/test/java/TestCreateSlide.java new file mode 100644 index 00000000..84997780 --- /dev/null +++ b/slides/snippets/src/test/java/TestCreateSlide.java @@ -0,0 +1,37 @@ +// 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.slides.v1.model.BatchUpdatePresentationResponse; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +// Unit testcase for createSlide snippet +public class TestCreateSlide extends BaseTest{ + + @Test + public void testCreateSlide() throws IOException { + String presentationId = createTestPresentation(); + BatchUpdatePresentationResponse response = + CreateSlide.createSlide(presentationId); + assertNotNull(response); + assertEquals(1, response.getReplies().size()); + String pageId = response.getReplies().get(0).getCreateSlide().getObjectId(); + assertNotNull(pageId); + deleteFileOnCleanup(presentationId); + } +} diff --git a/slides/snippets/src/test/java/TestCreateTextboxWithText.java b/slides/snippets/src/test/java/TestCreateTextboxWithText.java new file mode 100644 index 00000000..5fbf15bc --- /dev/null +++ b/slides/snippets/src/test/java/TestCreateTextboxWithText.java @@ -0,0 +1,38 @@ +// 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.slides.v1.model.BatchUpdatePresentationResponse; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +// Unit testcase for createTextboxWithText snippet +public class TestCreateTextboxWithText extends BaseTest{ + + @Test + public void testCreateTextBox() throws IOException { + String presentationId = createTestPresentation(); + String pageId = createTestSlide(presentationId); + BatchUpdatePresentationResponse response = + CreateTextboxWithText.createTextBoxWithText(presentationId, + pageId, "MyTextBox"); + assertEquals(2, response.getReplies().size()); + String boxId = response.getReplies().get(0).getCreateShape().getObjectId(); + assertNotNull(boxId); + deleteFileOnCleanup(presentationId); + } +} diff --git a/slides/snippets/src/test/java/TestImageMerging.java b/slides/snippets/src/test/java/TestImageMerging.java new file mode 100644 index 00000000..73a16f90 --- /dev/null +++ b/slides/snippets/src/test/java/TestImageMerging.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 +// +// 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.slides.v1.model.BatchUpdatePresentationResponse; +import com.google.api.services.slides.v1.model.Response; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +// Unit testcase for imageMerging snippet +public class TestImageMerging extends BaseTest{ + // TODO(developer) - change the IDs before executing + private final String IMAGE_URL = + "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"; + private final String TEMPLATE_PRESENTATION_ID = "1wJUN1B5CQ2wQOBzmz2apky48QNK1OsE2oNKHPMLpKDc"; + private final String CUSTOMER_NAME = "Fake Customer"; + @Test + public void testImageMerge() throws IOException { + BatchUpdatePresentationResponse response = + ImageMerging.imageMerging(TEMPLATE_PRESENTATION_ID, IMAGE_URL, CUSTOMER_NAME); + String presentationId = response.getPresentationId(); + assertNotNull(presentationId); + assertEquals(2, response.getReplies().size()); + int numReplacements = 0; + for(Response resp: response.getReplies()) { + numReplacements += resp.getReplaceAllShapesWithImage().getOccurrencesChanged(); + } + assertEquals(2, numReplacements); + deleteFileOnCleanup(presentationId); + } +} diff --git a/slides/snippets/src/test/java/TestRefreshSheetsChart.java b/slides/snippets/src/test/java/TestRefreshSheetsChart.java new file mode 100644 index 00000000..b2c17928 --- /dev/null +++ b/slides/snippets/src/test/java/TestRefreshSheetsChart.java @@ -0,0 +1,38 @@ +// 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.slides.v1.model.BatchUpdatePresentationResponse; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; + +// Unit testcase for refreshSheetsChart snippet +public class TestRefreshSheetsChart extends BaseTest{ + // TODO(developer) - change the IDs before executing + private final String DATA_SPREADSHEET_ID = "14KaZMq2aCAGt5acV77zaA_Ps8aDt04G7T0ei4KiXLX8"; + private final Integer CHART_ID = 1107320627; + @Test + public void testRefreshSheetsChart() throws IOException { + String presentationId = this.createTestPresentation(); + String pageId = this.createTestSlide(presentationId); + String chartId = + this.createTestSheetsChart(presentationId, pageId, DATA_SPREADSHEET_ID, CHART_ID); + BatchUpdatePresentationResponse response = + RefreshSheetsChart.refreshSheetsChart(presentationId, chartId); + assertEquals(1, response.getReplies().size()); + deleteFileOnCleanup(presentationId); + } +} diff --git a/slides/snippets/src/test/java/TestSimpleTextReplace.java b/slides/snippets/src/test/java/TestSimpleTextReplace.java new file mode 100644 index 00000000..397a3263 --- /dev/null +++ b/slides/snippets/src/test/java/TestSimpleTextReplace.java @@ -0,0 +1,35 @@ +// 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.slides.v1.model.BatchUpdatePresentationResponse; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; + +// Unit testcase for simpleTextReplace snippet +public class TestSimpleTextReplace extends BaseTest{ + + @Test + public void testSimpleTextReplace() throws IOException { + String presentationId = createTestPresentation(); + String pageId = createTestSlide(presentationId); + String boxId = createTestTextBox(presentationId, pageId); + BatchUpdatePresentationResponse response = + SimpleTextReplace.simpleTextReplace(presentationId, boxId, "MY NEW TEXT"); + assertEquals(2, response.getReplies().size()); + deleteFileOnCleanup(presentationId); + } +} diff --git a/slides/snippets/src/test/java/TestTextMerging.java b/slides/snippets/src/test/java/TestTextMerging.java new file mode 100644 index 00000000..35917aa3 --- /dev/null +++ b/slides/snippets/src/test/java/TestTextMerging.java @@ -0,0 +1,46 @@ +// 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.slides.v1.model.BatchUpdatePresentationResponse; +import com.google.api.services.slides.v1.model.Response; +import org.junit.Test; + +import java.io.IOException; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +// Unit testcase for textMerging snippet +public class TestTextMerging extends BaseTest{ + // TODO(developer) - change the IDs before executing + private final String TEMPLATE_PRESENTATION_ID = "1wJUN1B5CQ2wQOBzmz2apky48QNK1OsE2oNKHPMLpKDc"; + private final String DATA_SPREADSHEET_ID = "14KaZMq2aCAGt5acV77zaA_Ps8aDt04G7T0ei4KiXLX8"; + @Test + public void testTextMerge() throws IOException { + List responses = + TextMerging.textMerging(TEMPLATE_PRESENTATION_ID, DATA_SPREADSHEET_ID); + for (BatchUpdatePresentationResponse response: responses) { + String presentationId = response.getPresentationId(); + assertNotNull(presentationId); + assertEquals(3, response.getReplies().size()); + int numReplacements = 0; + for (Response resp : response.getReplies()) { + numReplacements += resp.getReplaceAllText().getOccurrencesChanged(); + } + assertEquals(4, numReplacements); + deleteFileOnCleanup(presentationId); + } + } +} diff --git a/slides/snippets/src/test/java/TestTextStyleUpdate.java b/slides/snippets/src/test/java/TestTextStyleUpdate.java new file mode 100644 index 00000000..6bf13102 --- /dev/null +++ b/slides/snippets/src/test/java/TestTextStyleUpdate.java @@ -0,0 +1,35 @@ +// 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.slides.v1.model.BatchUpdatePresentationResponse; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; + +// Unit testcase for textStyleUpdate snippet +public class TestTextStyleUpdate extends BaseTest{ + + @Test + public void testTextStyleUpdate() throws IOException { + String presentationId = this.createTestPresentation(); + String pageId = this.createTestSlide(presentationId); + String boxId = this.createTestTextBox(presentationId, pageId); + BatchUpdatePresentationResponse response = + TextStyleUpdate.textStyleUpdate(presentationId, boxId); + assertEquals(3, response.getReplies().size()); + deleteFileOnCleanup(presentationId); + } +} From f07b8cf24f776c35e82e796a6a3b4856914f38a7 Mon Sep 17 00:00:00 2001 From: Manvendra-P-Singh Date: Wed, 13 Jul 2022 16:11:48 +0000 Subject: [PATCH 004/152] test: removing deprecated GoogleCredential from drive v3 BaseTest (#246) * git-on-borg files of gmail-api-snippets * Update build.gradle test12 * Update build.gradle * test: Implemented auth using GoogleCredentials in v3 Co-authored-by: sanjuktaghosh7 Co-authored-by: Rajesh Mudaliyar Co-authored-by: himanshupr2627 --- drive/snippets/drive_v3/build.gradle | 4 ++ .../drive_v3/src/test/java/BaseTest.java | 42 ++++++++++++------- 2 files changed, 31 insertions(+), 15 deletions(-) diff --git a/drive/snippets/drive_v3/build.gradle b/drive/snippets/drive_v3/build.gradle index ce70eda8..4327d404 100644 --- a/drive/snippets/drive_v3/build.gradle +++ b/drive/snippets/drive_v3/build.gradle @@ -9,4 +9,8 @@ dependencies { implementation 'com.google.auth:google-auth-library-oauth2-http:1.3.0' implementation 'com.google.code.gson:gson:2.4' testImplementation 'junit:junit:4.12' +} + +test { + useJUnitPlatform() } \ No newline at end of file diff --git a/drive/snippets/drive_v3/src/test/java/BaseTest.java b/drive/snippets/drive_v3/src/test/java/BaseTest.java index 1177eee1..f46d3225 100644 --- a/drive/snippets/drive_v3/src/test/java/BaseTest.java +++ b/drive/snippets/drive_v3/src/test/java/BaseTest.java @@ -1,6 +1,5 @@ -import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; -import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.FileContent; +import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.apache.ApacheHttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; @@ -8,6 +7,8 @@ import com.google.api.services.drive.Drive; import com.google.api.services.drive.DriveScopes; import com.google.api.services.drive.model.File; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; import org.junit.After; import org.junit.Before; @@ -51,22 +52,33 @@ public void publish(LogRecord record) { }); } - public GoogleCredential getCredential() throws IOException { - return GoogleCredential.getApplicationDefault() - .createScoped(Arrays.asList(DriveScopes.DRIVE, DriveScopes.DRIVE_APPDATA)); + public GoogleCredentials getCredential() throws IOException { + return GoogleCredentials.getApplicationDefault() + .createScoped(Arrays.asList(DriveScopes.DRIVE, DriveScopes.DRIVE_APPDATA,DriveScopes.DRIVE_FILE)); } - public Drive buildService() throws IOException, GeneralSecurityException { - GoogleCredential credential = getCredential(); - return new Drive.Builder( - //new ApacheHttpTransport(), - //GoogleNetHttpTransport.newTrustedTransport(), - new NetHttpTransport(), + /** + * Creates a default authorization Drive client service. + * + * @return an authorized Drive client service + * @throws IOException - if credentials file not found. + */ + protected Drive 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 = getCredential(); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); + + // Create the classroom API client + Drive service = new Drive.Builder(new NetHttpTransport(), GsonFactory.getDefaultInstance(), - //GsonFactory.getDefaultInstance(), - credential) - .setApplicationName("Drive API Snippets") - .build(); + requestInitializer) + .setApplicationName("Drive Snippets") + .build(); + + return service; } @Before From ca7379ced6dd418555daba7ff4f36f2867f3fad2 Mon Sep 17 00:00:00 2001 From: googleworkspace-bot <109114539+googleworkspace-bot@users.noreply.github.com> Date: Thu, 21 Jul 2022 11:12:44 -0600 Subject: [PATCH 005/152] chore: Synced file(s) with googleworkspace/.github (#248) * chore: Created local '.github/workflows/lint.yml' from remote 'sync-files/defaults/.github/workflows/lint.yml' * chore: Created local '.github/workflows/test.yml' from remote 'sync-files/defaults/.github/workflows/test.yml' * chore: Created local '.github/CODEOWNERS' from remote 'sync-files/defaults/.github/CODEOWNERS' * chore: Created local '.github/sync-repo-settings.yaml' from remote 'sync-files/defaults/.github/sync-repo-settings.yaml' * chore: Created local '.github/workflows/automation.yml' from remote 'sync-files/defaults/.github/workflows/automation.yml' * chore: Created local 'SECURITY.md' from remote 'SECURITY.md' --- .github/CODEOWNERS | 17 ++++++++++ .github/sync-repo-settings.yaml | 54 ++++++++++++++++++++++++++++++++ .github/workflows/automation.yml | 28 +++++++++++++++++ .github/workflows/lint.yml | 24 ++++++++++++++ .github/workflows/test.yml | 24 ++++++++++++++ SECURITY.md | 6 ++++ 6 files changed, 153 insertions(+) create mode 100644 .github/CODEOWNERS create mode 100644 .github/sync-repo-settings.yaml create mode 100644 .github/workflows/automation.yml create mode 100644 .github/workflows/lint.yml create mode 100644 .github/workflows/test.yml create mode 100644 SECURITY.md diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 00000000..804a0939 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,17 @@ +# 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. + +# https://help.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners + +.github/ @googleworkspace/workspace-devrel-dpe diff --git a/.github/sync-repo-settings.yaml b/.github/sync-repo-settings.yaml new file mode 100644 index 00000000..757d7bb5 --- /dev/null +++ b/.github/sync-repo-settings.yaml @@ -0,0 +1,54 @@ +# 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. + +# .github/sync-repo-settings.yaml +# See https://github.com/googleapis/repo-automation-bots/tree/main/packages/sync-repo-settings for app options. +rebaseMergeAllowed: true +squashMergeAllowed: true +mergeCommitAllowed: false +deleteBranchOnMerge: true +branchProtectionRules: + - pattern: main + isAdminEnforced: false + requiresStrictStatusChecks: false + requiredStatusCheckContexts: + # .github/workflows/test.yml with a job called "test" + - "test" + # .github/workflows/lint.yml with a job called "lint" + - "lint" + # Google bots below + - "cla/google" + - "snippet-bot check" + - "header-check" + - "conventionalcommits.org" + requiredApprovingReviewCount: 1 + requiresCodeOwnerReviews: true + - pattern: master + isAdminEnforced: false + requiresStrictStatusChecks: false + requiredStatusCheckContexts: + # .github/workflows/test.yml with a job called "test" + - "test" + # .github/workflows/lint.yml with a job called "lint" + - "lint" + # Google bots below + - "cla/google" + - "snippet-bot check" + - "header-check" + - "conventionalcommits.org" + requiredApprovingReviewCount: 1 + requiresCodeOwnerReviews: true +permissionRules: + - team: workspace-devrel-dpe + permission: admin diff --git a/.github/workflows/automation.yml b/.github/workflows/automation.yml new file mode 100644 index 00000000..a5b0e865 --- /dev/null +++ b/.github/workflows/automation.yml @@ -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 +# +# 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. + +name: Automation +on: [pull_request] +jobs: + dependabot: + runs-on: ubuntu-latest + if: ${{ github.actor == 'dependabot[bot]' }} + env: + PR_URL: ${{github.event.pull_request.html_url}} + GITHUB_TOKEN: ${{secrets.GOOGLEWORKSPACE_BOT_TOKEN}} + steps: + - name: approve + run: gh pr review --approve "$PR_URL" + - name: merge + run: gh pr merge --auto --squash --delete-branch "$PR_URL diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 00000000..c5cb1be8 --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,24 @@ +# 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. + +name: Lint +on: [push, pull_request] +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - run: | + echo "No lint checks"; + exit 1; diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 00000000..debf4655 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,24 @@ +# 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. + +name: Test +on: [push, pull_request] +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - run: | + echo "No tests"; + exit 1; diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000..968a1fb3 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,6 @@ +# Report a security issue + +To report a security issue, please use https://g.co/vulnz. We use +https://g.co/vulnz for our intake, and do coordination and disclosure here on +GitHub (including using GitHub Security Advisory). The Google Security Team will +respond within 5 working days of your report on g.co/vulnz. From 6ca85bb70195bbb7b9a00ebf0d89e0f9151820d5 Mon Sep 17 00:00:00 2001 From: Justin Poehnelt Date: Thu, 21 Jul 2022 12:13:18 -0600 Subject: [PATCH 006/152] chore: standardize workflows (#249) * chore: standardize workflows * test: aggregate matrix --- .github/workflows/ci.yaml | 51 ----------------------------- .github/workflows/lint.yaml | 39 ---------------------- .github/workflows/lint.yml | 24 +++++++++----- .github/workflows/test.yml | 65 ++++++++++++++++++++++++++----------- 4 files changed, 62 insertions(+), 117 deletions(-) delete mode 100644 .github/workflows/ci.yaml delete mode 100644 .github/workflows/lint.yaml diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml deleted file mode 100644 index 88816de2..00000000 --- a/.github/workflows/ci.yaml +++ /dev/null @@ -1,51 +0,0 @@ -name: CI - -on: - push: - branches: [ master ] - pull_request: - branches: [ master ] - workflow_dispatch: - -jobs: - test: - concurrency: - group: ${{ github.head_ref || github.ref }} - cancel-in-progress: true - # Only run for internal PRs or after a merge - if: ${{ github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository }} - runs-on: ubuntu-latest - strategy: - matrix: - # TODO - expand matrix once stable - java-version: [11] - steps: - - uses: actions/checkout@v3 - - name: Fetch and Diff PR with base from which it was cloned - if: ${{ github.event.pull_request.base.sha }} - run: | - git fetch origin master "${{ github.event.pull_request.base.sha }}" - git diff --diff-filter=ACM --name-only "${{ github.event.pull_request.base.sha }}" "${{ github.sha }}" > "${HOME}/changed_files.txt" - - name: Set up Java ${{ matrix.java-version }} - uses: actions/setup-java@v2 - with: - distribution: 'temurin' - java-version: ${{ matrix.java-version }} - - name: Write test credentials - run: | - mkdir "${HOME}/secrets" - echo "${DEFAULT_CREDENTIALS}" > "${HOME}/secrets/default_credentials.json" - echo "${SERVICE_ACCOUNT_CREDENTIALS}" > "${HOME}/secrets/service_account.json" - echo "${CLIENT_ID_FILE}" > "${HOME}/secrets/client_id.json" - env: - DEFAULT_CREDENTIALS: ${{secrets.SNIPPETS_DEFAULT_CREDENTIALS}} - SERVICE_ACCOUNT_CREDENTIALS: ${{secrets.SNIPPETS_DELEGATED_ADMIN_SERVICE_ACCOUNT}} - CLIENT_ID_FILE: ${{secrets.SNIPPETS_CLIENT_ID_FILE}} - - name: Validate Gradle wrapper - uses: gradle/wrapper-validation-action@v1 - - name: Setup Gradle - uses: gradle/gradle-build-action@v2.1.1 - with: - gradle-version: 7.4 - - name: Run tests - run: ./.github/scripts/test.sh diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml deleted file mode 100644 index 285a7e99..00000000 --- a/.github/workflows/lint.yaml +++ /dev/null @@ -1,39 +0,0 @@ -# Copyright 2021 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. -name: Lint -on: - push: - branches: - - master - pull_request: - branches: - - master - workflow_dispatch: - -jobs: - lint: - concurrency: - group: ${{ github.head_ref || github.ref }} - cancel-in-progress: true - runs-on: ubuntu-20.04 - steps: - - uses: actions/checkout@v2.4.0 - with: - fetch-depth: 0 - - uses: github/super-linter/slim@v4.8.5 - env: - ERROR_ON_MISSING_EXEC_BIT: true - VALIDATE_JSCPD: false - VALIDATE_ALL_CODEBASE: ${{ github.event_name == 'push' }} - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index c5cb1be8..befb9074 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -1,4 +1,4 @@ -# Copyright 2022 Google LLC +# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -11,14 +11,22 @@ # 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. - name: Lint -on: [push, pull_request] +on: [push, pull_request, workflow_dispatch] + jobs: lint: - runs-on: ubuntu-latest + concurrency: + group: ${{ github.head_ref || github.ref }} + cancel-in-progress: true + runs-on: ubuntu-20.04 steps: - - uses: actions/checkout@v2 - - run: | - echo "No lint checks"; - exit 1; + - uses: actions/checkout@v2.4.0 + with: + fetch-depth: 0 + - uses: github/super-linter/slim@v4.8.5 + env: + ERROR_ON_MISSING_EXEC_BIT: true + VALIDATE_JSCPD: false + VALIDATE_ALL_CODEBASE: ${{ github.event_name == 'push' }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index debf4655..31604d02 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,24 +1,51 @@ -# 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. - name: Test -on: [push, pull_request] + +on: [push, pull_request, workflow_dispatch] + jobs: + matrix: + concurrency: + group: ${{ github.head_ref || github.ref }} + cancel-in-progress: true + # Only run for internal PRs or after a merge + if: ${{ github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository }} + runs-on: ubuntu-latest + strategy: + matrix: + # TODO - expand matrix once stable + java-version: [11] + steps: + - uses: actions/checkout@v3 + - name: Fetch and Diff PR with base from which it was cloned + if: ${{ github.event.pull_request.base.sha }} + run: | + git fetch origin master "${{ github.event.pull_request.base.sha }}" + git diff --diff-filter=ACM --name-only "${{ github.event.pull_request.base.sha }}" "${{ github.sha }}" > "${HOME}/changed_files.txt" + - name: Set up Java ${{ matrix.java-version }} + uses: actions/setup-java@v2 + with: + distribution: 'temurin' + java-version: ${{ matrix.java-version }} + - name: Write test credentials + run: | + mkdir "${HOME}/secrets" + echo "${DEFAULT_CREDENTIALS}" > "${HOME}/secrets/default_credentials.json" + echo "${SERVICE_ACCOUNT_CREDENTIALS}" > "${HOME}/secrets/service_account.json" + echo "${CLIENT_ID_FILE}" > "${HOME}/secrets/client_id.json" + env: + DEFAULT_CREDENTIALS: ${{secrets.SNIPPETS_DEFAULT_CREDENTIALS}} + SERVICE_ACCOUNT_CREDENTIALS: ${{secrets.SNIPPETS_DELEGATED_ADMIN_SERVICE_ACCOUNT}} + CLIENT_ID_FILE: ${{secrets.SNIPPETS_CLIENT_ID_FILE}} + - name: Validate Gradle wrapper + uses: gradle/wrapper-validation-action@v1 + - name: Setup Gradle + uses: gradle/gradle-build-action@v2.1.1 + with: + gradle-version: 7.4 + - name: Run tests + run: ./.github/scripts/test.sh test: + needs: [matrix] runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - run: | - echo "No tests"; - exit 1; + - run: echo "Test matrix finished" \ No newline at end of file From fbe50d8a3263deaf65291deba31209868d1137a3 Mon Sep 17 00:00:00 2001 From: Justin Poehnelt Date: Thu, 21 Jul 2022 12:25:54 -0600 Subject: [PATCH 007/152] chore: add license headers (#250) --- .github/linters/sun_checks.xml | 16 ++++++++++++++++ .github/snippet-bot.yml | 14 ++++++++++++++ .github/workflows/test.yml | 14 ++++++++++++++ .travis.yml | 14 ++++++++++++++ calendar/sync/packaging.yaml | 14 ++++++++++++++ calendar/sync/pom.xml | 16 ++++++++++++++++ classroom/snippets/src/main/java/Courses.java | 16 ++++++++++++++++ classroom/snippets/src/test/java/BaseTest.java | 16 ++++++++++++++++ .../snippets/src/test/java/CoursesTest.java | 16 ++++++++++++++++ .../drive_v2/src/main/java/AppDataSnippets.java | 16 ++++++++++++++++ .../drive_v2/src/main/java/ChangeSnippets.java | 16 ++++++++++++++++ .../drive_v2/src/main/java/DriveSnippets.java | 16 ++++++++++++++++ .../drive_v2/src/main/java/FileSnippets.java | 16 ++++++++++++++++ .../src/main/java/TeamDriveSnippets.java | 16 ++++++++++++++++ .../src/test/java/AppDataSnippetsTest.java | 16 ++++++++++++++++ .../drive_v2/src/test/java/BaseTest.java | 16 ++++++++++++++++ .../src/test/java/ChangeSnippetsTest.java | 16 ++++++++++++++++ .../src/test/java/DriveSnippetsTest.java | 16 ++++++++++++++++ .../drive_v2/src/test/java/FileSnippetsTest.java | 16 ++++++++++++++++ .../src/test/java/TeamDriveSnippetsTest.java | 16 ++++++++++++++++ .../drive_v2/src/test/java/TestCreateDrive.java | 16 ++++++++++++++++ .../drive_v2/src/test/java/TestCreateFolder.java | 16 ++++++++++++++++ .../src/test/java/TestCreateShortcut.java | 16 ++++++++++++++++ .../src/test/java/TestCreateTeamDrive.java | 16 ++++++++++++++++ .../drive_v2/src/test/java/TestDownloadFile.java | 16 ++++++++++++++++ .../drive_v2/src/test/java/TestExportPdf.java | 16 ++++++++++++++++ .../drive_v2/src/test/java/TestFetchChanges.java | 16 ++++++++++++++++ .../src/test/java/TestFetchStartPageToken.java | 16 ++++++++++++++++ .../src/test/java/TestMoveFileToFolder.java | 16 ++++++++++++++++ .../src/test/java/TestRecoverDrives.java | 16 ++++++++++++++++ .../src/test/java/TestRecoverTeamDrives.java | 16 ++++++++++++++++ .../drive_v2/src/test/java/TestSearchFiles.java | 16 ++++++++++++++++ .../drive_v2/src/test/java/TestShareFile.java | 16 ++++++++++++++++ .../drive_v2/src/test/java/TestTouchFile.java | 16 ++++++++++++++++ .../drive_v2/src/test/java/TestUploadBasic.java | 16 ++++++++++++++++ .../src/test/java/TestUploadRevision.java | 16 ++++++++++++++++ .../src/test/java/TestUploadToFolder.java | 16 ++++++++++++++++ .../src/test/java/TestUploadWithConversion.java | 16 ++++++++++++++++ .../drive_v3/src/main/java/AppDataSnippets.java | 16 ++++++++++++++++ .../drive_v3/src/main/java/ChangeSnippets.java | 16 ++++++++++++++++ .../drive_v3/src/main/java/DriveSnippets.java | 16 ++++++++++++++++ .../drive_v3/src/main/java/FileSnippets.java | 16 ++++++++++++++++ .../src/main/java/TeamDriveSnippets.java | 16 ++++++++++++++++ .../src/test/java/AppDataSnippetsTest.java | 16 ++++++++++++++++ .../drive_v3/src/test/java/BaseTest.java | 16 ++++++++++++++++ .../src/test/java/ChangeSnippetsTest.java | 16 ++++++++++++++++ .../src/test/java/DriveSnippetsTest.java | 16 ++++++++++++++++ .../drive_v3/src/test/java/FileSnippetsTest.java | 16 ++++++++++++++++ .../src/test/java/TeamDriveSnippetsTest.java | 16 ++++++++++++++++ .../drive_v3/src/test/java/TestCreateFolder.java | 16 ++++++++++++++++ .../src/test/java/TestCreateShortcut.java | 16 ++++++++++++++++ .../drive_v3/src/test/java/TestDownloadFile.java | 16 ++++++++++++++++ .../drive_v3/src/test/java/TestExportPdf.java | 16 ++++++++++++++++ .../src/test/java/TestFetchAppDataFolder.java | 16 ++++++++++++++++ .../drive_v3/src/test/java/TestListAppData.java | 16 ++++++++++++++++ .../src/test/java/TestMoveFileToFolder.java | 16 ++++++++++++++++ .../drive_v3/src/test/java/TestSearchFiles.java | 16 ++++++++++++++++ .../drive_v3/src/test/java/TestShareFile.java | 16 ++++++++++++++++ .../drive_v3/src/test/java/TestTouchFile.java | 16 ++++++++++++++++ .../src/test/java/TestUploadAppdata.java | 16 ++++++++++++++++ .../drive_v3/src/test/java/TestUploadBasic.java | 16 ++++++++++++++++ .../src/test/java/TestUploadRevision.java | 16 ++++++++++++++++ .../src/test/java/TestUploadToFolder.java | 16 ++++++++++++++++ .../src/test/java/TestUploadWithConversion.java | 16 ++++++++++++++++ gmail/snippets/src/main/java/SendEmail.java | 16 ++++++++++++++++ .../snippets/src/main/java/SettingsSnippets.java | 16 ++++++++++++++++ gmail/snippets/src/main/java/SmimeSnippets.java | 16 ++++++++++++++++ gmail/snippets/src/test/java/BaseTest.java | 16 ++++++++++++++++ sheets/snippets/src/test/java/BaseTest.java | 16 ++++++++++++++++ .../snippets/src/test/java/TestPivotTable.java | 16 ++++++++++++++++ slides/snippets/src/test/java/BaseTest.java | 16 ++++++++++++++++ .../vault/chatmigration/DirectoryService.java | 16 ++++++++++++++++ .../vault/chatmigration/DuplicateHold.java | 16 ++++++++++++++++ .../google/vault/chatmigration/HoldsReport.java | 16 ++++++++++++++++ .../vault/chatmigration/MigrationHelper.java | 16 ++++++++++++++++ .../google/vault/chatmigration/QuickStart.java | 16 ++++++++++++++++ .../vault/chatmigration/RetryableTemplate.java | 16 ++++++++++++++++ 77 files changed, 1224 insertions(+) diff --git a/.github/linters/sun_checks.xml b/.github/linters/sun_checks.xml index 5585111e..59cbc573 100644 --- a/.github/linters/sun_checks.xml +++ b/.github/linters/sun_checks.xml @@ -1,4 +1,20 @@ + + diff --git a/.github/snippet-bot.yml b/.github/snippet-bot.yml index e69de29b..bb488a81 100644 --- a/.github/snippet-bot.yml +++ b/.github/snippet-bot.yml @@ -0,0 +1,14 @@ +# 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. + diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 31604d02..1ce73dbb 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,3 +1,17 @@ +# 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. + name: Test on: [push, pull_request, workflow_dispatch] diff --git a/.travis.yml b/.travis.yml index c8b5032d..16a64d16 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,3 +1,17 @@ +# 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. + language: java jdk: - oraclejdk11 diff --git a/calendar/sync/packaging.yaml b/calendar/sync/packaging.yaml index 4a6cb239..e150add5 100644 --- a/calendar/sync/packaging.yaml +++ b/calendar/sync/packaging.yaml @@ -1,3 +1,17 @@ +# 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. + # GOOGLE SAMPLE PACKAGING DATA # # This file is used by Google as part of our samples packaging process. diff --git a/calendar/sync/pom.xml b/calendar/sync/pom.xml index e97d4a68..333decb2 100644 --- a/calendar/sync/pom.xml +++ b/calendar/sync/pom.xml @@ -1,4 +1,20 @@ + + 4.0.0 diff --git a/classroom/snippets/src/main/java/Courses.java b/classroom/snippets/src/main/java/Courses.java index df399390..0526ddd5 100644 --- a/classroom/snippets/src/main/java/Courses.java +++ b/classroom/snippets/src/main/java/Courses.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.client.googleapis.batch.BatchRequest; import com.google.api.client.googleapis.batch.json.JsonBatchCallback; import com.google.api.client.googleapis.json.GoogleJsonError; diff --git a/classroom/snippets/src/test/java/BaseTest.java b/classroom/snippets/src/test/java/BaseTest.java index 8fa029f5..4b69228f 100644 --- a/classroom/snippets/src/test/java/BaseTest.java +++ b/classroom/snippets/src/test/java/BaseTest.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; diff --git a/classroom/snippets/src/test/java/CoursesTest.java b/classroom/snippets/src/test/java/CoursesTest.java index dc7342bd..858d4540 100644 --- a/classroom/snippets/src/test/java/CoursesTest.java +++ b/classroom/snippets/src/test/java/CoursesTest.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.services.classroom.Classroom; import com.google.api.services.classroom.model.Course; import com.google.api.services.classroom.model.CourseAlias; diff --git a/drive/snippets/drive_v2/src/main/java/AppDataSnippets.java b/drive/snippets/drive_v2/src/main/java/AppDataSnippets.java index a05d5cc3..cee70b57 100644 --- a/drive/snippets/drive_v2/src/main/java/AppDataSnippets.java +++ b/drive/snippets/drive_v2/src/main/java/AppDataSnippets.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.client.http.FileContent; import com.google.api.services.drive.Drive; import com.google.api.services.drive.model.File; diff --git a/drive/snippets/drive_v2/src/main/java/ChangeSnippets.java b/drive/snippets/drive_v2/src/main/java/ChangeSnippets.java index 23710324..ae8d4558 100644 --- a/drive/snippets/drive_v2/src/main/java/ChangeSnippets.java +++ b/drive/snippets/drive_v2/src/main/java/ChangeSnippets.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.services.drive.Drive; import com.google.api.services.drive.model.Change; import com.google.api.services.drive.model.ChangeList; diff --git a/drive/snippets/drive_v2/src/main/java/DriveSnippets.java b/drive/snippets/drive_v2/src/main/java/DriveSnippets.java index 49942b6d..8c70c3da 100644 --- a/drive/snippets/drive_v2/src/main/java/DriveSnippets.java +++ b/drive/snippets/drive_v2/src/main/java/DriveSnippets.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.services.drive.model.Drive; import com.google.api.services.drive.model.DriveList; import com.google.api.services.drive.model.Permission; diff --git a/drive/snippets/drive_v2/src/main/java/FileSnippets.java b/drive/snippets/drive_v2/src/main/java/FileSnippets.java index f79a8159..f1a86c7c 100644 --- a/drive/snippets/drive_v2/src/main/java/FileSnippets.java +++ b/drive/snippets/drive_v2/src/main/java/FileSnippets.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.client.googleapis.batch.BatchRequest; import com.google.api.client.googleapis.batch.json.JsonBatchCallback; import com.google.api.client.googleapis.json.GoogleJsonError; diff --git a/drive/snippets/drive_v2/src/main/java/TeamDriveSnippets.java b/drive/snippets/drive_v2/src/main/java/TeamDriveSnippets.java index 0a6572b6..1f740c8a 100644 --- a/drive/snippets/drive_v2/src/main/java/TeamDriveSnippets.java +++ b/drive/snippets/drive_v2/src/main/java/TeamDriveSnippets.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.client.http.FileContent; import com.google.api.services.drive.Drive; import com.google.api.services.drive.model.File; diff --git a/drive/snippets/drive_v2/src/test/java/AppDataSnippetsTest.java b/drive/snippets/drive_v2/src/test/java/AppDataSnippetsTest.java index 747103f5..b4237983 100644 --- a/drive/snippets/drive_v2/src/test/java/AppDataSnippetsTest.java +++ b/drive/snippets/drive_v2/src/test/java/AppDataSnippetsTest.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.services.drive.model.File; import com.google.api.services.drive.model.FileList; import org.junit.Before; diff --git a/drive/snippets/drive_v2/src/test/java/BaseTest.java b/drive/snippets/drive_v2/src/test/java/BaseTest.java index d3851aed..1bbf6e2e 100644 --- a/drive/snippets/drive_v2/src/test/java/BaseTest.java +++ b/drive/snippets/drive_v2/src/test/java/BaseTest.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.client.http.HttpRequestInitializer; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; diff --git a/drive/snippets/drive_v2/src/test/java/ChangeSnippetsTest.java b/drive/snippets/drive_v2/src/test/java/ChangeSnippetsTest.java index 3a33e4e8..4323cc7d 100644 --- a/drive/snippets/drive_v2/src/test/java/ChangeSnippetsTest.java +++ b/drive/snippets/drive_v2/src/test/java/ChangeSnippetsTest.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Before; import org.junit.Test; diff --git a/drive/snippets/drive_v2/src/test/java/DriveSnippetsTest.java b/drive/snippets/drive_v2/src/test/java/DriveSnippetsTest.java index cbe27af2..42bbaf53 100644 --- a/drive/snippets/drive_v2/src/test/java/DriveSnippetsTest.java +++ b/drive/snippets/drive_v2/src/test/java/DriveSnippetsTest.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.services.drive.model.Drive; import com.google.api.services.drive.model.Permission; import com.google.api.services.drive.model.PermissionList; diff --git a/drive/snippets/drive_v2/src/test/java/FileSnippetsTest.java b/drive/snippets/drive_v2/src/test/java/FileSnippetsTest.java index dab8987b..1efd149b 100644 --- a/drive/snippets/drive_v2/src/test/java/FileSnippetsTest.java +++ b/drive/snippets/drive_v2/src/test/java/FileSnippetsTest.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.services.drive.model.File; import com.google.api.services.drive.model.FileList; import org.junit.Before; diff --git a/drive/snippets/drive_v2/src/test/java/TeamDriveSnippetsTest.java b/drive/snippets/drive_v2/src/test/java/TeamDriveSnippetsTest.java index 59bdf809..bfed9e79 100644 --- a/drive/snippets/drive_v2/src/test/java/TeamDriveSnippetsTest.java +++ b/drive/snippets/drive_v2/src/test/java/TeamDriveSnippetsTest.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.services.drive.model.TeamDrive; import com.google.api.services.drive.model.Permission; import com.google.api.services.drive.model.PermissionList; diff --git a/drive/snippets/drive_v2/src/test/java/TestCreateDrive.java b/drive/snippets/drive_v2/src/test/java/TestCreateDrive.java index dee4bc33..4db53c7b 100644 --- a/drive/snippets/drive_v2/src/test/java/TestCreateDrive.java +++ b/drive/snippets/drive_v2/src/test/java/TestCreateDrive.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import java.io.IOException; diff --git a/drive/snippets/drive_v2/src/test/java/TestCreateFolder.java b/drive/snippets/drive_v2/src/test/java/TestCreateFolder.java index 4d744772..0c7a25af 100644 --- a/drive/snippets/drive_v2/src/test/java/TestCreateFolder.java +++ b/drive/snippets/drive_v2/src/test/java/TestCreateFolder.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import java.io.IOException; diff --git a/drive/snippets/drive_v2/src/test/java/TestCreateShortcut.java b/drive/snippets/drive_v2/src/test/java/TestCreateShortcut.java index a9aec655..1853773d 100644 --- a/drive/snippets/drive_v2/src/test/java/TestCreateShortcut.java +++ b/drive/snippets/drive_v2/src/test/java/TestCreateShortcut.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import java.io.IOException; diff --git a/drive/snippets/drive_v2/src/test/java/TestCreateTeamDrive.java b/drive/snippets/drive_v2/src/test/java/TestCreateTeamDrive.java index bca94def..72695b33 100644 --- a/drive/snippets/drive_v2/src/test/java/TestCreateTeamDrive.java +++ b/drive/snippets/drive_v2/src/test/java/TestCreateTeamDrive.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import java.io.IOException; diff --git a/drive/snippets/drive_v2/src/test/java/TestDownloadFile.java b/drive/snippets/drive_v2/src/test/java/TestDownloadFile.java index 2c4806f6..ce285417 100644 --- a/drive/snippets/drive_v2/src/test/java/TestDownloadFile.java +++ b/drive/snippets/drive_v2/src/test/java/TestDownloadFile.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import java.io.ByteArrayOutputStream; diff --git a/drive/snippets/drive_v2/src/test/java/TestExportPdf.java b/drive/snippets/drive_v2/src/test/java/TestExportPdf.java index f8741feb..fc6deabb 100644 --- a/drive/snippets/drive_v2/src/test/java/TestExportPdf.java +++ b/drive/snippets/drive_v2/src/test/java/TestExportPdf.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import java.io.ByteArrayOutputStream; diff --git a/drive/snippets/drive_v2/src/test/java/TestFetchChanges.java b/drive/snippets/drive_v2/src/test/java/TestFetchChanges.java index b5a60ee3..751c47ec 100644 --- a/drive/snippets/drive_v2/src/test/java/TestFetchChanges.java +++ b/drive/snippets/drive_v2/src/test/java/TestFetchChanges.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import java.io.IOException; diff --git a/drive/snippets/drive_v2/src/test/java/TestFetchStartPageToken.java b/drive/snippets/drive_v2/src/test/java/TestFetchStartPageToken.java index 701ee971..270d09a1 100644 --- a/drive/snippets/drive_v2/src/test/java/TestFetchStartPageToken.java +++ b/drive/snippets/drive_v2/src/test/java/TestFetchStartPageToken.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import java.io.IOException; diff --git a/drive/snippets/drive_v2/src/test/java/TestMoveFileToFolder.java b/drive/snippets/drive_v2/src/test/java/TestMoveFileToFolder.java index b563346d..7ad8f1bf 100644 --- a/drive/snippets/drive_v2/src/test/java/TestMoveFileToFolder.java +++ b/drive/snippets/drive_v2/src/test/java/TestMoveFileToFolder.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import java.io.IOException; diff --git a/drive/snippets/drive_v2/src/test/java/TestRecoverDrives.java b/drive/snippets/drive_v2/src/test/java/TestRecoverDrives.java index d8b246a2..c214234e 100644 --- a/drive/snippets/drive_v2/src/test/java/TestRecoverDrives.java +++ b/drive/snippets/drive_v2/src/test/java/TestRecoverDrives.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.services.drive.model.Drive; import com.google.api.services.drive.model.Permission; import com.google.api.services.drive.model.PermissionList; diff --git a/drive/snippets/drive_v2/src/test/java/TestRecoverTeamDrives.java b/drive/snippets/drive_v2/src/test/java/TestRecoverTeamDrives.java index 41399754..9b1a7892 100644 --- a/drive/snippets/drive_v2/src/test/java/TestRecoverTeamDrives.java +++ b/drive/snippets/drive_v2/src/test/java/TestRecoverTeamDrives.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.services.drive.model.Permission; import com.google.api.services.drive.model.PermissionList; import com.google.api.services.drive.model.TeamDrive; diff --git a/drive/snippets/drive_v2/src/test/java/TestSearchFiles.java b/drive/snippets/drive_v2/src/test/java/TestSearchFiles.java index 48a8b818..6772cb40 100644 --- a/drive/snippets/drive_v2/src/test/java/TestSearchFiles.java +++ b/drive/snippets/drive_v2/src/test/java/TestSearchFiles.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.services.drive.model.File; import org.junit.Test; diff --git a/drive/snippets/drive_v2/src/test/java/TestShareFile.java b/drive/snippets/drive_v2/src/test/java/TestShareFile.java index 746ef71a..c47ec72c 100644 --- a/drive/snippets/drive_v2/src/test/java/TestShareFile.java +++ b/drive/snippets/drive_v2/src/test/java/TestShareFile.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import java.io.IOException; diff --git a/drive/snippets/drive_v2/src/test/java/TestTouchFile.java b/drive/snippets/drive_v2/src/test/java/TestTouchFile.java index 3280bcbb..aecfabf4 100644 --- a/drive/snippets/drive_v2/src/test/java/TestTouchFile.java +++ b/drive/snippets/drive_v2/src/test/java/TestTouchFile.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import java.io.IOException; diff --git a/drive/snippets/drive_v2/src/test/java/TestUploadBasic.java b/drive/snippets/drive_v2/src/test/java/TestUploadBasic.java index 35cdf8a4..79617d8d 100644 --- a/drive/snippets/drive_v2/src/test/java/TestUploadBasic.java +++ b/drive/snippets/drive_v2/src/test/java/TestUploadBasic.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import java.io.IOException; diff --git a/drive/snippets/drive_v2/src/test/java/TestUploadRevision.java b/drive/snippets/drive_v2/src/test/java/TestUploadRevision.java index 77682baa..de932e4f 100644 --- a/drive/snippets/drive_v2/src/test/java/TestUploadRevision.java +++ b/drive/snippets/drive_v2/src/test/java/TestUploadRevision.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import java.io.IOException; diff --git a/drive/snippets/drive_v2/src/test/java/TestUploadToFolder.java b/drive/snippets/drive_v2/src/test/java/TestUploadToFolder.java index 6dceb63b..815982d9 100644 --- a/drive/snippets/drive_v2/src/test/java/TestUploadToFolder.java +++ b/drive/snippets/drive_v2/src/test/java/TestUploadToFolder.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.services.drive.model.File; import org.junit.Test; diff --git a/drive/snippets/drive_v2/src/test/java/TestUploadWithConversion.java b/drive/snippets/drive_v2/src/test/java/TestUploadWithConversion.java index a3d69c52..ae3a889c 100644 --- a/drive/snippets/drive_v2/src/test/java/TestUploadWithConversion.java +++ b/drive/snippets/drive_v2/src/test/java/TestUploadWithConversion.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import java.io.IOException; diff --git a/drive/snippets/drive_v3/src/main/java/AppDataSnippets.java b/drive/snippets/drive_v3/src/main/java/AppDataSnippets.java index 05300c26..975aafb6 100644 --- a/drive/snippets/drive_v3/src/main/java/AppDataSnippets.java +++ b/drive/snippets/drive_v3/src/main/java/AppDataSnippets.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.client.http.FileContent; import com.google.api.services.drive.Drive; import com.google.api.services.drive.model.File; diff --git a/drive/snippets/drive_v3/src/main/java/ChangeSnippets.java b/drive/snippets/drive_v3/src/main/java/ChangeSnippets.java index 147668fa..5710478b 100644 --- a/drive/snippets/drive_v3/src/main/java/ChangeSnippets.java +++ b/drive/snippets/drive_v3/src/main/java/ChangeSnippets.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.services.drive.Drive; import com.google.api.services.drive.model.Change; import com.google.api.services.drive.model.ChangeList; diff --git a/drive/snippets/drive_v3/src/main/java/DriveSnippets.java b/drive/snippets/drive_v3/src/main/java/DriveSnippets.java index 0262a6f4..3bedd15e 100644 --- a/drive/snippets/drive_v3/src/main/java/DriveSnippets.java +++ b/drive/snippets/drive_v3/src/main/java/DriveSnippets.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.client.http.FileContent; //import com.google.api.services.drive.Drive; import com.google.api.services.drive.model.Drive; diff --git a/drive/snippets/drive_v3/src/main/java/FileSnippets.java b/drive/snippets/drive_v3/src/main/java/FileSnippets.java index 784a2bbe..84117f41 100644 --- a/drive/snippets/drive_v3/src/main/java/FileSnippets.java +++ b/drive/snippets/drive_v3/src/main/java/FileSnippets.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.client.googleapis.batch.BatchRequest; import com.google.api.client.googleapis.batch.json.JsonBatchCallback; import com.google.api.client.googleapis.json.GoogleJsonError; diff --git a/drive/snippets/drive_v3/src/main/java/TeamDriveSnippets.java b/drive/snippets/drive_v3/src/main/java/TeamDriveSnippets.java index 10ca713f..eb2e0711 100644 --- a/drive/snippets/drive_v3/src/main/java/TeamDriveSnippets.java +++ b/drive/snippets/drive_v3/src/main/java/TeamDriveSnippets.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.client.http.FileContent; import com.google.api.services.drive.Drive; import com.google.api.services.drive.model.TeamDrive; diff --git a/drive/snippets/drive_v3/src/test/java/AppDataSnippetsTest.java b/drive/snippets/drive_v3/src/test/java/AppDataSnippetsTest.java index 39d5111b..cab4ed28 100644 --- a/drive/snippets/drive_v3/src/test/java/AppDataSnippetsTest.java +++ b/drive/snippets/drive_v3/src/test/java/AppDataSnippetsTest.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.services.drive.model.File; import com.google.api.services.drive.model.FileList; import org.junit.Before; diff --git a/drive/snippets/drive_v3/src/test/java/BaseTest.java b/drive/snippets/drive_v3/src/test/java/BaseTest.java index f46d3225..75e636f3 100644 --- a/drive/snippets/drive_v3/src/test/java/BaseTest.java +++ b/drive/snippets/drive_v3/src/test/java/BaseTest.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.client.http.FileContent; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; diff --git a/drive/snippets/drive_v3/src/test/java/ChangeSnippetsTest.java b/drive/snippets/drive_v3/src/test/java/ChangeSnippetsTest.java index 3a33e4e8..4323cc7d 100644 --- a/drive/snippets/drive_v3/src/test/java/ChangeSnippetsTest.java +++ b/drive/snippets/drive_v3/src/test/java/ChangeSnippetsTest.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Before; import org.junit.Test; diff --git a/drive/snippets/drive_v3/src/test/java/DriveSnippetsTest.java b/drive/snippets/drive_v3/src/test/java/DriveSnippetsTest.java index f520db8b..71ec6b25 100644 --- a/drive/snippets/drive_v3/src/test/java/DriveSnippetsTest.java +++ b/drive/snippets/drive_v3/src/test/java/DriveSnippetsTest.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.services.drive.model.Drive; import com.google.api.services.drive.model.Permission; import com.google.api.services.drive.model.PermissionList; diff --git a/drive/snippets/drive_v3/src/test/java/FileSnippetsTest.java b/drive/snippets/drive_v3/src/test/java/FileSnippetsTest.java index 94eafc4c..a9641861 100644 --- a/drive/snippets/drive_v3/src/test/java/FileSnippetsTest.java +++ b/drive/snippets/drive_v3/src/test/java/FileSnippetsTest.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.services.drive.model.File; import com.google.api.services.drive.model.FileList; import org.junit.Before; diff --git a/drive/snippets/drive_v3/src/test/java/TeamDriveSnippetsTest.java b/drive/snippets/drive_v3/src/test/java/TeamDriveSnippetsTest.java index 3e46bd38..43447b4d 100644 --- a/drive/snippets/drive_v3/src/test/java/TeamDriveSnippetsTest.java +++ b/drive/snippets/drive_v3/src/test/java/TeamDriveSnippetsTest.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.services.drive.model.TeamDrive; import com.google.api.services.drive.model.Permission; import com.google.api.services.drive.model.PermissionList; diff --git a/drive/snippets/drive_v3/src/test/java/TestCreateFolder.java b/drive/snippets/drive_v3/src/test/java/TestCreateFolder.java index 8d2a10bf..9c12f12f 100644 --- a/drive/snippets/drive_v3/src/test/java/TestCreateFolder.java +++ b/drive/snippets/drive_v3/src/test/java/TestCreateFolder.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import java.io.IOException; diff --git a/drive/snippets/drive_v3/src/test/java/TestCreateShortcut.java b/drive/snippets/drive_v3/src/test/java/TestCreateShortcut.java index a9aec655..1853773d 100644 --- a/drive/snippets/drive_v3/src/test/java/TestCreateShortcut.java +++ b/drive/snippets/drive_v3/src/test/java/TestCreateShortcut.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import java.io.IOException; diff --git a/drive/snippets/drive_v3/src/test/java/TestDownloadFile.java b/drive/snippets/drive_v3/src/test/java/TestDownloadFile.java index 2c4806f6..ce285417 100644 --- a/drive/snippets/drive_v3/src/test/java/TestDownloadFile.java +++ b/drive/snippets/drive_v3/src/test/java/TestDownloadFile.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import java.io.ByteArrayOutputStream; diff --git a/drive/snippets/drive_v3/src/test/java/TestExportPdf.java b/drive/snippets/drive_v3/src/test/java/TestExportPdf.java index f8741feb..fc6deabb 100644 --- a/drive/snippets/drive_v3/src/test/java/TestExportPdf.java +++ b/drive/snippets/drive_v3/src/test/java/TestExportPdf.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import java.io.ByteArrayOutputStream; diff --git a/drive/snippets/drive_v3/src/test/java/TestFetchAppDataFolder.java b/drive/snippets/drive_v3/src/test/java/TestFetchAppDataFolder.java index 4049e5f6..95c69b6c 100644 --- a/drive/snippets/drive_v3/src/test/java/TestFetchAppDataFolder.java +++ b/drive/snippets/drive_v3/src/test/java/TestFetchAppDataFolder.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import java.io.IOException; diff --git a/drive/snippets/drive_v3/src/test/java/TestListAppData.java b/drive/snippets/drive_v3/src/test/java/TestListAppData.java index 52544bfd..fe67a1f2 100644 --- a/drive/snippets/drive_v3/src/test/java/TestListAppData.java +++ b/drive/snippets/drive_v3/src/test/java/TestListAppData.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.services.drive.model.FileList; import org.junit.Test; diff --git a/drive/snippets/drive_v3/src/test/java/TestMoveFileToFolder.java b/drive/snippets/drive_v3/src/test/java/TestMoveFileToFolder.java index 857c20d7..7e4b2b8d 100644 --- a/drive/snippets/drive_v3/src/test/java/TestMoveFileToFolder.java +++ b/drive/snippets/drive_v3/src/test/java/TestMoveFileToFolder.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import javax.annotation.CheckReturnValue; diff --git a/drive/snippets/drive_v3/src/test/java/TestSearchFiles.java b/drive/snippets/drive_v3/src/test/java/TestSearchFiles.java index 48a8b818..6772cb40 100644 --- a/drive/snippets/drive_v3/src/test/java/TestSearchFiles.java +++ b/drive/snippets/drive_v3/src/test/java/TestSearchFiles.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.services.drive.model.File; import org.junit.Test; diff --git a/drive/snippets/drive_v3/src/test/java/TestShareFile.java b/drive/snippets/drive_v3/src/test/java/TestShareFile.java index 746ef71a..c47ec72c 100644 --- a/drive/snippets/drive_v3/src/test/java/TestShareFile.java +++ b/drive/snippets/drive_v3/src/test/java/TestShareFile.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import java.io.IOException; diff --git a/drive/snippets/drive_v3/src/test/java/TestTouchFile.java b/drive/snippets/drive_v3/src/test/java/TestTouchFile.java index 3280bcbb..aecfabf4 100644 --- a/drive/snippets/drive_v3/src/test/java/TestTouchFile.java +++ b/drive/snippets/drive_v3/src/test/java/TestTouchFile.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import java.io.IOException; diff --git a/drive/snippets/drive_v3/src/test/java/TestUploadAppdata.java b/drive/snippets/drive_v3/src/test/java/TestUploadAppdata.java index 67e2d13c..a8dbd5be 100644 --- a/drive/snippets/drive_v3/src/test/java/TestUploadAppdata.java +++ b/drive/snippets/drive_v3/src/test/java/TestUploadAppdata.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import java.io.IOException; diff --git a/drive/snippets/drive_v3/src/test/java/TestUploadBasic.java b/drive/snippets/drive_v3/src/test/java/TestUploadBasic.java index c301131c..b33b7866 100644 --- a/drive/snippets/drive_v3/src/test/java/TestUploadBasic.java +++ b/drive/snippets/drive_v3/src/test/java/TestUploadBasic.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import java.io.IOException; diff --git a/drive/snippets/drive_v3/src/test/java/TestUploadRevision.java b/drive/snippets/drive_v3/src/test/java/TestUploadRevision.java index 77682baa..de932e4f 100644 --- a/drive/snippets/drive_v3/src/test/java/TestUploadRevision.java +++ b/drive/snippets/drive_v3/src/test/java/TestUploadRevision.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import java.io.IOException; diff --git a/drive/snippets/drive_v3/src/test/java/TestUploadToFolder.java b/drive/snippets/drive_v3/src/test/java/TestUploadToFolder.java index bf4702e9..c328994e 100644 --- a/drive/snippets/drive_v3/src/test/java/TestUploadToFolder.java +++ b/drive/snippets/drive_v3/src/test/java/TestUploadToFolder.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.services.drive.model.File; import org.junit.Test; diff --git a/drive/snippets/drive_v3/src/test/java/TestUploadWithConversion.java b/drive/snippets/drive_v3/src/test/java/TestUploadWithConversion.java index a3d69c52..ae3a889c 100644 --- a/drive/snippets/drive_v3/src/test/java/TestUploadWithConversion.java +++ b/drive/snippets/drive_v3/src/test/java/TestUploadWithConversion.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import org.junit.Test; import java.io.IOException; diff --git a/gmail/snippets/src/main/java/SendEmail.java b/gmail/snippets/src/main/java/SendEmail.java index 002f2f53..9b671f32 100644 --- a/gmail/snippets/src/main/java/SendEmail.java +++ b/gmail/snippets/src/main/java/SendEmail.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.services.gmail.Gmail; import com.google.api.services.gmail.model.Draft; import com.google.api.services.gmail.model.Message; diff --git a/gmail/snippets/src/main/java/SettingsSnippets.java b/gmail/snippets/src/main/java/SettingsSnippets.java index fab67fa6..89bb8fd9 100644 --- a/gmail/snippets/src/main/java/SettingsSnippets.java +++ b/gmail/snippets/src/main/java/SettingsSnippets.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.client.googleapis.batch.BatchRequest; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.http.FileContent; diff --git a/gmail/snippets/src/main/java/SmimeSnippets.java b/gmail/snippets/src/main/java/SmimeSnippets.java index 85f3d0de..7c0fd468 100644 --- a/gmail/snippets/src/main/java/SmimeSnippets.java +++ b/gmail/snippets/src/main/java/SmimeSnippets.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.services.gmail.Gmail; import com.google.api.services.gmail.model.*; import com.google.api.services.gmail.model.SmimeInfo; diff --git a/gmail/snippets/src/test/java/BaseTest.java b/gmail/snippets/src/test/java/BaseTest.java index 4e287a9f..3fc90c8b 100644 --- a/gmail/snippets/src/test/java/BaseTest.java +++ b/gmail/snippets/src/test/java/BaseTest.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; diff --git a/sheets/snippets/src/test/java/BaseTest.java b/sheets/snippets/src/test/java/BaseTest.java index 12a1db27..b1f27a1a 100644 --- a/sheets/snippets/src/test/java/BaseTest.java +++ b/sheets/snippets/src/test/java/BaseTest.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.drive.Drive; diff --git a/sheets/snippets/src/test/java/TestPivotTable.java b/sheets/snippets/src/test/java/TestPivotTable.java index 84c1b043..83d26883 100644 --- a/sheets/snippets/src/test/java/TestPivotTable.java +++ b/sheets/snippets/src/test/java/TestPivotTable.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.services.sheets.v4.model.BatchUpdateSpreadsheetResponse; import org.junit.Test; import java.io.IOException; diff --git a/slides/snippets/src/test/java/BaseTest.java b/slides/snippets/src/test/java/BaseTest.java index f88fec7c..f28c5117 100644 --- a/slides/snippets/src/test/java/BaseTest.java +++ b/slides/snippets/src/test/java/BaseTest.java @@ -1,3 +1,19 @@ +/* + * 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. + */ + import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.drive.Drive; diff --git a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/DirectoryService.java b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/DirectoryService.java index 55d2bf7c..24514a5e 100644 --- a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/DirectoryService.java +++ b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/DirectoryService.java @@ -1,3 +1,19 @@ +/* + * 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.vault.chatmigration; import com.github.rholder.retry.RetryException; diff --git a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/DuplicateHold.java b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/DuplicateHold.java index 7cfc8ed7..cf8ef242 100644 --- a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/DuplicateHold.java +++ b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/DuplicateHold.java @@ -1,3 +1,19 @@ +/* + * 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.vault.chatmigration; import com.github.rholder.retry.RetryException; diff --git a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/HoldsReport.java b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/HoldsReport.java index 8ed6af36..b2bb1a07 100644 --- a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/HoldsReport.java +++ b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/HoldsReport.java @@ -1,3 +1,19 @@ +/* + * 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.vault.chatmigration; import com.google.api.services.admin.directory.model.OrgUnit; diff --git a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/MigrationHelper.java b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/MigrationHelper.java index 4e4772f6..2da593c3 100644 --- a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/MigrationHelper.java +++ b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/MigrationHelper.java @@ -1,3 +1,19 @@ +/* + * 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.vault.chatmigration; import com.google.api.client.auth.oauth2.Credential; diff --git a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/QuickStart.java b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/QuickStart.java index b4fd4cea..70e5943e 100644 --- a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/QuickStart.java +++ b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/QuickStart.java @@ -1,3 +1,19 @@ +/* + * 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.vault.chatmigration; import com.google.api.services.admin.directory.Directory; diff --git a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/RetryableTemplate.java b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/RetryableTemplate.java index 5f1fc347..d9642d58 100644 --- a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/RetryableTemplate.java +++ b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/RetryableTemplate.java @@ -1,3 +1,19 @@ +/* + * 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.vault.chatmigration; import com.github.rholder.retry.RetryException; From fa9e1d2363a1c8f67bc220d0afc85c1587a98a69 Mon Sep 17 00:00:00 2001 From: googleworkspace-bot <109114539+googleworkspace-bot@users.noreply.github.com> Date: Thu, 21 Jul 2022 12:52:45 -0600 Subject: [PATCH 008/152] chore: Synced local '.github/workflows/automation.yml' with remote 'sync-files/defaults/.github/workflows/automation.yml' (#251) --- .github/workflows/automation.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/automation.yml b/.github/workflows/automation.yml index a5b0e865..aaef124b 100644 --- a/.github/workflows/automation.yml +++ b/.github/workflows/automation.yml @@ -11,7 +11,7 @@ # 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. - +--- name: Automation on: [pull_request] jobs: @@ -25,4 +25,4 @@ jobs: - name: approve run: gh pr review --approve "$PR_URL" - name: merge - run: gh pr merge --auto --squash --delete-branch "$PR_URL + run: gh pr merge --auto --squash --delete-branch "$PR_URL" From 9e7d6708d7b6b0d02506aa17eee9f1c09495efd0 Mon Sep 17 00:00:00 2001 From: googleworkspace-bot <109114539+googleworkspace-bot@users.noreply.github.com> Date: Fri, 22 Jul 2022 16:32:37 -0600 Subject: [PATCH 009/152] chore: Synced local '.github/workflows/automation.yml' with remote 'sync-files/defaults/.github/workflows/automation.yml' (#252) --- .github/workflows/automation.yml | 45 ++++++++++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 2 deletions(-) diff --git a/.github/workflows/automation.yml b/.github/workflows/automation.yml index aaef124b..5144afe4 100644 --- a/.github/workflows/automation.yml +++ b/.github/workflows/automation.yml @@ -13,11 +13,11 @@ # limitations under the License. --- name: Automation -on: [pull_request] +on: [push, pull_request, workflow_dispatch] jobs: dependabot: runs-on: ubuntu-latest - if: ${{ github.actor == 'dependabot[bot]' }} + if: ${{ github.actor == 'dependabot[bot]' && github.event_name == 'pull_request' }} env: PR_URL: ${{github.event.pull_request.html_url}} GITHUB_TOKEN: ${{secrets.GOOGLEWORKSPACE_BOT_TOKEN}} @@ -26,3 +26,44 @@ jobs: run: gh pr review --approve "$PR_URL" - name: merge run: gh pr merge --auto --squash --delete-branch "$PR_URL" + default-branch-migration: + # this job helps with migrating the default branch to main + # it pushes main to master if master exists and main is the default branch + # it pushes master to main if master is the default branch + runs-on: ubuntu-latest + if: ${{ github.ref == 'refs/heads/main' || github.ref == 'refs/heads/master' }} + steps: + - uses: actions/checkout@v2 + with: + fetch-depth: 0 + # required otherwise GitHub blocks infinite loops in pushes originating in an action + token: ${{ secrets.GOOGLEWORKSPACE_BOT_TOKEN }} + - name: Set env + run: | + # set DEFAULT BRANCH + echo "DEFAULT_BRANCH=$(gh repo view --json defaultBranchRef --jq '.defaultBranchRef.name')" >> $GITHUB_ENV; + + # set HAS_MASTER_BRANCH + if [ ! -z "$(git ls-remote --heads origin master)" ]; then + echo "HAS_MASTER_BRANCH=true" >> $GITHUB_ENV + else + echo "HAS_MASTER_BRANCH=false" >> $GITHUB_ENV + fi + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: configure git + run: | + git config --global user.name 'googleworkspace-bot' + git config --global user.email 'googleworkspace-bot@google.com' + - if: ${{ env.DEFAULT_BRANCH == 'main' && env.HAS_MASTER_BRANCH == 'true' }} + name: Update master branch from main + run: | + git checkout -b master + git reset --hard origin/main + git push origin master + - if: ${{ env.DEFAULT_BRANCH == 'master'}} + name: Update main branch from master + run: | + git checkout -b main + git reset --hard origin/master + git push origin main From e39e8b5eedfdcffafa27090375a82d9180e46fe9 Mon Sep 17 00:00:00 2001 From: Justin Poehnelt Date: Fri, 22 Jul 2022 17:06:47 -0600 Subject: [PATCH 010/152] chore: switch to main (#253) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 189f8f47..2ab1be1a 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Google Workspace APIs Java Samples [![Build Status](https://travis-ci.org/googleworkspace/java-samples.svg?branch=master)](https://travis-ci.org/googleworkspace/java-samples) +# Google Workspace APIs Java Samples [![Build Status](https://travis-ci.org/googleworkspace/java-samples.svg?branch=main)](https://travis-ci.org/googleworkspace/java-samples) A collection of samples that demonstrate how to call Google Workspace APIs in Java. From f0b358e76dcd6a5d058d5d1df00029a77643760d Mon Sep 17 00:00:00 2001 From: Justin Poehnelt Date: Thu, 28 Jul 2022 10:54:51 -0600 Subject: [PATCH 011/152] build: remove travis (#254) --- .travis.yml | 31 ------------------------------- README.md | 2 -- 2 files changed, 33 deletions(-) delete mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 16a64d16..00000000 --- a/.travis.yml +++ /dev/null @@ -1,31 +0,0 @@ -# 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. - -language: java -jdk: - - oraclejdk11 -# Use a Build Matrix for subdirs (https://lord.io/blog/2014/travis-multiple-subdirs/) -env: - - DIR=adminSDK/alertcenter/quickstart - - DIR=adminSDK/directory/quickstart - - DIR=adminSDK/reports/quickstart - - DIR=adminSDK/reseller/quickstart - - DIR=appsScript/quickstart - - DIR=classroom/quickstart - - DIR=drive/quickstart - - DIR=gmail/quickstart - - DIR=sheets/quickstart - - DIR=slides/quickstart - - DIR=tasks/quickstart -script: cd $DIR && gradle build # gradle -q run diff --git a/README.md b/README.md index 2ab1be1a..46bec9a3 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,3 @@ -# Google Workspace APIs Java Samples [![Build Status](https://travis-ci.org/googleworkspace/java-samples.svg?branch=main)](https://travis-ci.org/googleworkspace/java-samples) - A collection of samples that demonstrate how to call Google Workspace APIs in Java. ## APIs From d2da6ab1106e623eb0802e58f97b526963626b58 Mon Sep 17 00:00:00 2001 From: googleworkspace-bot <109114539+googleworkspace-bot@users.noreply.github.com> Date: Fri, 29 Jul 2022 11:17:43 -0600 Subject: [PATCH 012/152] chore: Synced file(s) with googleworkspace/.github (#255) * chore: Synced local '.github/sync-repo-settings.yaml' with remote 'sync-files/defaults/.github/sync-repo-settings.yaml' * chore: Synced local '.github/workflows/automation.yml' with remote 'sync-files/defaults/.github/workflows/automation.yml' --- .github/sync-repo-settings.yaml | 15 --------------- .github/workflows/automation.yml | 4 ++-- 2 files changed, 2 insertions(+), 17 deletions(-) diff --git a/.github/sync-repo-settings.yaml b/.github/sync-repo-settings.yaml index 757d7bb5..1e81cab7 100644 --- a/.github/sync-repo-settings.yaml +++ b/.github/sync-repo-settings.yaml @@ -34,21 +34,6 @@ branchProtectionRules: - "conventionalcommits.org" requiredApprovingReviewCount: 1 requiresCodeOwnerReviews: true - - pattern: master - isAdminEnforced: false - requiresStrictStatusChecks: false - requiredStatusCheckContexts: - # .github/workflows/test.yml with a job called "test" - - "test" - # .github/workflows/lint.yml with a job called "lint" - - "lint" - # Google bots below - - "cla/google" - - "snippet-bot check" - - "header-check" - - "conventionalcommits.org" - requiredApprovingReviewCount: 1 - requiresCodeOwnerReviews: true permissionRules: - team: workspace-devrel-dpe permission: admin diff --git a/.github/workflows/automation.yml b/.github/workflows/automation.yml index 5144afe4..b01e9cf9 100644 --- a/.github/workflows/automation.yml +++ b/.github/workflows/automation.yml @@ -58,12 +58,12 @@ jobs: - if: ${{ env.DEFAULT_BRANCH == 'main' && env.HAS_MASTER_BRANCH == 'true' }} name: Update master branch from main run: | - git checkout -b master + git checkout -B master git reset --hard origin/main git push origin master - if: ${{ env.DEFAULT_BRANCH == 'master'}} name: Update main branch from master run: | - git checkout -b main + git checkout -B main git reset --hard origin/master git push origin main From 41559c4daa0b838348c9cbc4426ee6d4c4a98ffe Mon Sep 17 00:00:00 2001 From: Steve Bazyl Date: Thu, 4 Aug 2022 16:41:56 -0600 Subject: [PATCH 013/152] chore: Remove no longer used files. (#256) --- .../drive_v2/src/main/java/FileSnippets.java | 313 ------------------ .../src/main/java/TeamDriveSnippets.java | 98 ------ .../drive_v3/src/main/java/FileSnippets.java | 306 ----------------- .../src/main/java/TeamDriveSnippets.java | 100 ------ .../src/main/java/SettingsSnippets.java | 122 ------- .../snippets/src/main/java/SmimeSnippets.java | 275 --------------- 6 files changed, 1214 deletions(-) delete mode 100644 drive/snippets/drive_v2/src/main/java/FileSnippets.java delete mode 100644 drive/snippets/drive_v2/src/main/java/TeamDriveSnippets.java delete mode 100644 drive/snippets/drive_v3/src/main/java/FileSnippets.java delete mode 100644 drive/snippets/drive_v3/src/main/java/TeamDriveSnippets.java delete mode 100644 gmail/snippets/src/main/java/SettingsSnippets.java delete mode 100644 gmail/snippets/src/main/java/SmimeSnippets.java diff --git a/drive/snippets/drive_v2/src/main/java/FileSnippets.java b/drive/snippets/drive_v2/src/main/java/FileSnippets.java deleted file mode 100644 index f1a86c7c..00000000 --- a/drive/snippets/drive_v2/src/main/java/FileSnippets.java +++ /dev/null @@ -1,313 +0,0 @@ -/* - * 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. - */ - -import com.google.api.client.googleapis.batch.BatchRequest; -import com.google.api.client.googleapis.batch.json.JsonBatchCallback; -import com.google.api.client.googleapis.json.GoogleJsonError; -import com.google.api.client.http.FileContent; -import com.google.api.client.http.HttpHeaders; -import com.google.api.client.util.DateTime; -import com.google.api.services.drive.Drive; -import com.google.api.services.drive.model.File; -import com.google.api.services.drive.model.FileList; -import com.google.api.services.drive.model.Permission; -import com.google.api.services.drive.model.ParentReference; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - - -public class FileSnippets { - - private Drive service; - - public FileSnippets(Drive service) { - this.service = service; - } - - public String uploadBasic() throws IOException { - Drive driveService = this.service; - // [START uploadBasic] - File fileMetadata = new File(); - fileMetadata.setTitle("photo.jpg"); - java.io.File filePath = new java.io.File("files/photo.jpg"); - FileContent mediaContent = new FileContent("image/jpeg", filePath); - File file = driveService.files().insert(fileMetadata, mediaContent) - .setFields("id") - .execute(); - System.out.println("File ID: " + file.getId()); - // [END uploadBasic] - return file.getId(); - } - - public String uploadRevision(String realFileId) throws IOException { - Drive driveService = this.service; - // [START uploadRevision] - String fileId = "0BwwA4oUTeiV1UVNwOHItT0xfa2M"; - // [START_EXCLUDE silent] - fileId = realFileId; - // [END_EXCLUDE] - java.io.File filePath = new java.io.File("files/photo.jpg"); - FileContent mediaContent = new FileContent("image/jpeg", filePath); - Drive.Files.Update request = driveService.files().update(fileId, new File(), mediaContent) - .setFields("id"); - request.getMediaHttpUploader().setDirectUploadEnabled(true); - File file = request.execute(); - System.out.println("File ID: " + file.getId()); - // [END uploadRevision] - return file.getId(); - } - - - public File uploadToFolder(String realFolderId) throws IOException { - Drive driveService = this.service; - // [START uploadToFolder] - String folderId = "0BwwA4oUTeiV1TGRPeTVjaWRDY1E"; - File fileMetadata = new File(); - // [START_EXCLUDE silent] - folderId = realFolderId; - // [END_EXCLUDE] - fileMetadata.setTitle("photo.jpg"); - fileMetadata.setParents(Collections.singletonList( - new ParentReference().setId(folderId))); - java.io.File filePath = new java.io.File("files/photo.jpg"); - FileContent mediaContent = new FileContent("image/jpeg", filePath); - File file = driveService.files().insert(fileMetadata, mediaContent) - .setFields("id, parents") - .execute(); - System.out.println("File ID: " + file.getId()); - // [END uploadToFolder] - return file; - } - - public String uploadWithConversion() throws IOException { - Drive driveService = this.service; - - // [START uploadWithConversion] - File fileMetadata = new File(); - fileMetadata.setTitle("My Report"); - fileMetadata.setMimeType("application/vnd.google-apps.spreadsheet"); - - java.io.File filePath = new java.io.File("files/report.csv"); - FileContent mediaContent = new FileContent("text/csv", filePath); - File file = driveService.files().insert(fileMetadata, mediaContent) - .setFields("id") - .execute(); - System.out.println("File ID: " + file.getId()); - // [END uploadWithConversion] - return file.getId(); - } - - public ByteArrayOutputStream exportPdf(String realFileId) - throws IOException { - Drive driveService = this.service; - // [START exportPdf] - String fileId = "1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo"; - OutputStream outputStream = new ByteArrayOutputStream(); - // [START_EXCLUDE silent] - fileId = realFileId; - // [END_EXCLUDE] - driveService.files().export(fileId, "application/pdf") - .executeMediaAndDownloadTo(outputStream); - // [END exportPdf] - return (ByteArrayOutputStream) outputStream; - } - - public ByteArrayOutputStream downloadFile(String realFileId) - throws IOException { - Drive driveService = this.service; - // [START downloadFile] - String fileId = "0BwwA4oUTeiV1UVNwOHItT0xfa2M"; - OutputStream outputStream = new ByteArrayOutputStream(); - // [START_EXCLUDE silent] - fileId = realFileId; - // [END_EXCLUDE] - driveService.files().get(fileId) - .executeMediaAndDownloadTo(outputStream); - // [END downloadFile] - return (ByteArrayOutputStream) outputStream; - } - - public String createShortcut() throws IOException { - Drive driveService = this.service; - // [START createShortcut] - File fileMetadata = new File(); - fileMetadata.setTitle("Project plan"); - fileMetadata.setMimeType("application/vnd.google-apps.drive-sdk"); - - File file = driveService.files().insert(fileMetadata) - .setFields("id") - .execute(); - System.out.println("File ID: " + file.getId()); - // [END createShortcut] - return file.getId(); - } - - public long touchFile(String realFileId, long realTimestamp) - throws IOException { - Drive driveService = this.service; - - // [START touchFile] - String fileId = "1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ"; - File fileMetadata = new File(); - fileMetadata.setModifiedDate(new DateTime(System.currentTimeMillis())); - // [START_EXCLUDE silent] - fileId = realFileId; - fileMetadata.setModifiedDate(new DateTime(realTimestamp)); - // [END_EXCLUDE] - File file = driveService.files().update(fileId, fileMetadata) - .setSetModifiedDate(true) - .setFields("id, modifiedDate") - .execute(); - System.out.println("Modified time: " + file.getModifiedDate()); - // [END touchFile] - return file.getModifiedDate().getValue(); - } - - public String createFolder() throws IOException { - Drive driveService = this.service; - // [START createFolder] - File fileMetadata = new File(); - fileMetadata.setTitle("Invoices"); - fileMetadata.setMimeType("application/vnd.google-apps.folder"); - - File file = driveService.files().insert(fileMetadata) - .setFields("id") - .execute(); - System.out.println("Folder ID: " + file.getId()); - // [END createFolder] - return file.getId(); - } - - public List moveFileToFolder(String realFileId, String realFolderId) - throws IOException { - Drive driveService = this.service; - // [START moveFileToFolder] - String fileId = "1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ"; - String folderId = "0BwwA4oUTeiV1TGRPeTVjaWRDY1E"; - // [START_EXCLUDE silent] - fileId = realFileId; - folderId = realFolderId; - // [END_EXCLUDE] - // Retrieve the existing parents to remove - File file = driveService.files().get(fileId) - .setFields("parents") - .execute(); - StringBuilder previousParents = new StringBuilder(); - for (ParentReference parent : file.getParents()) { - previousParents.append(parent.getId()); - previousParents.append(','); - } - // Move the file to the new folder - file = driveService.files().update(fileId, null) - .setAddParents(folderId) - .setRemoveParents(previousParents.toString()) - .setFields("id, parents") - .execute(); - // [END moveFileToFolder] - List parents = new ArrayList(); - for (ParentReference parent : file.getParents()) { - parents.add(parent.getId()); - } - return parents; - } - - public List searchFiles() throws IOException { - Drive driveService = this.service; - List files = new ArrayList(); - // [START searchFiles] - String pageToken = null; - do { - FileList result = driveService.files().list() - .setQ("mimeType='image/jpeg'") - .setSpaces("drive") - .setFields("nextPageToken, items(id, title)") - .setPageToken(pageToken) - .execute(); - for (File file : result.getItems()) { - System.out.printf("Found file: %s (%s)\n", - file.getTitle(), file.getId()); - } - // [START_EXCLUDE silent] - files.addAll(result.getItems()); - // [END_EXCLUDE] - pageToken = result.getNextPageToken(); - } while (pageToken != null); - // [END searchFiles] - return files; - } - - public List shareFile(String realFileId, String realUser, String realDomain) - throws IOException { - Drive driveService = this.service; - final List ids = new ArrayList(); - // [START shareFile] - String fileId = "1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ"; - // [START_EXCLUDE silent] - fileId = realFileId; - // [END_EXCLUDE] - JsonBatchCallback callback = new JsonBatchCallback() { - @Override - public void onFailure(GoogleJsonError e, - HttpHeaders responseHeaders) - throws IOException { - // Handle error - System.err.println(e.getMessage()); - } - - @Override - public void onSuccess(Permission permission, - HttpHeaders responseHeaders) - throws IOException { - System.out.println("Permission ID: " + permission.getId()); - // [START_EXCLUDE silent] - ids.add(permission.getId()); - // [END_EXCLUDE] - } - }; - BatchRequest batch = driveService.batch(); - Permission userPermission = new Permission() - .setType("user") - .setRole("writer") - .setValue("user@example.com"); - // [START_EXCLUDE silent] - userPermission.setValue(realUser); - // [END_EXCLUDE] - driveService.permissions().insert(fileId, userPermission) - .setFields("id") - .queue(batch, callback); - - Permission domainPermission = new Permission() - .setType("domain") - .setRole("reader") - .setValue("example.com"); - // [START_EXCLUDE silent] - domainPermission.setValue(realDomain); - // [END_EXCLUDE] - driveService.permissions().insert(fileId, domainPermission) - .setFields("id") - .queue(batch, callback); - - batch.execute(); - // [END shareFile] - return ids; - } - -} diff --git a/drive/snippets/drive_v2/src/main/java/TeamDriveSnippets.java b/drive/snippets/drive_v2/src/main/java/TeamDriveSnippets.java deleted file mode 100644 index 1f740c8a..00000000 --- a/drive/snippets/drive_v2/src/main/java/TeamDriveSnippets.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * 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. - */ - -import com.google.api.client.http.FileContent; -import com.google.api.services.drive.Drive; -import com.google.api.services.drive.model.File; -import com.google.api.services.drive.model.TeamDrive; -import com.google.api.services.drive.model.TeamDriveList; -import com.google.api.services.drive.model.Permission; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -public class TeamDriveSnippets { - private Drive service; - - public TeamDriveSnippets(Drive service) { - this.service = service; - } - - public String createTeamDrive() throws IOException { - Drive driveService = this.service; - // [START createTeamDrive] - TeamDrive teamDriveMetadata = new TeamDrive(); - teamDriveMetadata.setName("Project Resources"); - String requestId = UUID.randomUUID().toString(); - TeamDrive teamDrive = driveService.teamdrives().insert(requestId, teamDriveMetadata) - .execute(); - System.out.println("Team Drive ID: " + teamDrive.getId()); - // [END createTeamDrive] - return teamDrive.getId(); - } - - public List recoverTeamDrives(String realUser) - throws IOException { - Drive driveService = this.service; - List teamDrives = new ArrayList(); - // [START recoverTeamDrives] - // Find all Team Drives without an organizer and add one. - // Note: This example does not capture all cases. Team Drives - // that have an empty group as the sole organizer, or an - // organizer outside the organization are not captured. A - // more exhaustive approach would evaluate each Team Drive - // and the associated permissions and groups to ensure an active - // organizer is assigned. - String pageToken = null; - Permission newOrganizerPermission = new Permission() - .setType("user") - .setRole("organizer") - .setValue("user@example.com"); - // [START_EXCLUDE silent] - newOrganizerPermission.setValue(realUser); - // [END_EXCLUDE] - - do { - TeamDriveList result = driveService.teamdrives().list() - .setQ("organizerCount = 0") - .setUseDomainAdminAccess(true) - .setFields("nextPageToken, items(id, name)") - .setPageToken(pageToken) - .execute(); - for (TeamDrive teamDrive : result.getItems()) { - System.out.printf("Found Team Drive without organizer: %s (%s)\n", - teamDrive.getName(), teamDrive.getId()); - // Note: For improved efficiency, consider batching - // permission insert requests - Permission permissionResult = driveService.permissions() - .insert(teamDrive.getId(), newOrganizerPermission) - .setUseDomainAdminAccess(true) - .setSupportsTeamDrives(true) - .setFields("id") - .execute(); - System.out.printf("Added organizer permission: %s\n", permissionResult.getId()); - } - // [START_EXCLUDE silent] - teamDrives.addAll(result.getItems()); - // [END_EXCLUDE] - pageToken = result.getNextPageToken(); - } while (pageToken != null); - // [END recoverTeamDrives] - return teamDrives; - } -} diff --git a/drive/snippets/drive_v3/src/main/java/FileSnippets.java b/drive/snippets/drive_v3/src/main/java/FileSnippets.java deleted file mode 100644 index 84117f41..00000000 --- a/drive/snippets/drive_v3/src/main/java/FileSnippets.java +++ /dev/null @@ -1,306 +0,0 @@ -/* - * 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. - */ - -import com.google.api.client.googleapis.batch.BatchRequest; -import com.google.api.client.googleapis.batch.json.JsonBatchCallback; -import com.google.api.client.googleapis.json.GoogleJsonError; -import com.google.api.client.http.FileContent; -import com.google.api.client.http.HttpHeaders; -import com.google.api.client.util.DateTime; -import com.google.api.services.drive.Drive; -import com.google.api.services.drive.model.File; -import com.google.api.services.drive.model.FileList; -import com.google.api.services.drive.model.Permission; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - - -public class FileSnippets { - - private Drive service; - - public FileSnippets(Drive service) { - this.service = service; - } - - public String uploadBasic() throws IOException { - Drive driveService = this.service; - // [START uploadBasic] - File fileMetadata = new File(); - fileMetadata.setName("photo.jpg"); - java.io.File filePath = new java.io.File("files/photo.jpg"); - FileContent mediaContent = new FileContent("image/jpeg", filePath); - File file = driveService.files().create(fileMetadata, mediaContent) - .setFields("id") - .execute(); - System.out.println("File ID: " + file.getId()); - // [END uploadBasic] - return file.getId(); - } - - public String uploadRevision(String realFileId) throws IOException { - Drive driveService = this.service; - // [START uploadRevision] - String fileId = "0BwwA4oUTeiV1UVNwOHItT0xfa2M"; - // [START_EXCLUDE silent] - fileId = realFileId; - // [END_EXCLUDE] - java.io.File filePath = new java.io.File("files/photo.jpg"); - FileContent mediaContent = new FileContent("image/jpeg", filePath); - Drive.Files.Update request = driveService.files().update(fileId, new File(), mediaContent) - .setFields("id"); - request.getMediaHttpUploader().setDirectUploadEnabled(true); - File file = request.execute(); - System.out.println("File ID: " + file.getId()); - // [END uploadRevision] - return file.getId(); - } - - - public File uploadToFolder(String realFolderId) throws IOException { - Drive driveService = this.service; - // [START uploadToFolder] - String folderId = "0BwwA4oUTeiV1TGRPeTVjaWRDY1E"; - File fileMetadata = new File(); - // [START_EXCLUDE silent] - folderId = realFolderId; - // [END_EXCLUDE] - fileMetadata.setName("photo.jpg"); - fileMetadata.setParents(Collections.singletonList(folderId)); - java.io.File filePath = new java.io.File("files/photo.jpg"); - FileContent mediaContent = new FileContent("image/jpeg", filePath); - File file = driveService.files().create(fileMetadata, mediaContent) - .setFields("id, parents") - .execute(); - System.out.println("File ID: " + file.getId()); - // [END uploadToFolder] - return file; - } - - public String uploadWithConversion() throws IOException { - Drive driveService = this.service; - - // [START uploadWithConversion] - File fileMetadata = new File(); - fileMetadata.setName("My Report"); - fileMetadata.setMimeType("application/vnd.google-apps.spreadsheet"); - - java.io.File filePath = new java.io.File("files/report.csv"); - FileContent mediaContent = new FileContent("text/csv", filePath); - File file = driveService.files().create(fileMetadata, mediaContent) - .setFields("id") - .execute(); - System.out.println("File ID: " + file.getId()); - // [END uploadWithConversion] - return file.getId(); - } - - public ByteArrayOutputStream exportPdf(String realFileId) - throws IOException { - Drive driveService = this.service; - // [START exportPdf] - String fileId = "1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo"; - OutputStream outputStream = new ByteArrayOutputStream(); - // [START_EXCLUDE silent] - fileId = realFileId; - // [END_EXCLUDE] - driveService.files().export(fileId, "application/pdf") - .executeMediaAndDownloadTo(outputStream); - // [END exportPdf] - return (ByteArrayOutputStream) outputStream; - } - - public ByteArrayOutputStream downloadFile(String realFileId) - throws IOException { - Drive driveService = this.service; - // [START downloadFile] - String fileId = "0BwwA4oUTeiV1UVNwOHItT0xfa2M"; - OutputStream outputStream = new ByteArrayOutputStream(); - // [START_EXCLUDE silent] - fileId = realFileId; - // [END_EXCLUDE] - driveService.files().get(fileId) - .executeMediaAndDownloadTo(outputStream); - // [END downloadFile] - return (ByteArrayOutputStream) outputStream; - } - - public String createShortcut() throws IOException { - Drive driveService = this.service; - // [START createShortcut] - File fileMetadata = new File(); - fileMetadata.setName("Project plan"); - fileMetadata.setMimeType("application/vnd.google-apps.drive-sdk"); - - File file = driveService.files().create(fileMetadata) - .setFields("id") - .execute(); - System.out.println("File ID: " + file.getId()); - // [END createShortcut] - return file.getId(); - } - - public long touchFile(String realFileId, long realTimestamp) - throws IOException { - Drive driveService = this.service; - - // [START touchFile] - String fileId = "1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ"; - File fileMetadata = new File(); - fileMetadata.setModifiedTime(new DateTime(System.currentTimeMillis())); - // [START_EXCLUDE silent] - fileId = realFileId; - fileMetadata.setModifiedTime(new DateTime(realTimestamp)); - // [END_EXCLUDE] - File file = driveService.files().update(fileId, fileMetadata) - .setFields("id, modifiedTime") - .execute(); - System.out.println("Modified time: " + file.getModifiedTime()); - // [END touchFile] - return file.getModifiedTime().getValue(); - } - - public String createFolder() throws IOException { - Drive driveService = this.service; - // [START createFolder] - File fileMetadata = new File(); - fileMetadata.setName("Invoices"); - fileMetadata.setMimeType("application/vnd.google-apps.folder"); - - File file = driveService.files().create(fileMetadata) - .setFields("id") - .execute(); - System.out.println("Folder ID: " + file.getId()); - // [END createFolder] - return file.getId(); - } - - public List moveFileToFolder(String realFileId, String realFolderId) - throws IOException { - Drive driveService = this.service; - // [START moveFileToFolder] - String fileId = "1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ"; - String folderId = "0BwwA4oUTeiV1TGRPeTVjaWRDY1E"; - // [START_EXCLUDE silent] - fileId = realFileId; - folderId = realFolderId; - // [END_EXCLUDE] - // Retrieve the existing parents to remove - File file = driveService.files().get(fileId) - .setFields("parents") - .execute(); - StringBuilder previousParents = new StringBuilder(); - for (String parent : file.getParents()) { - previousParents.append(parent); - previousParents.append(','); - } - // Move the file to the new folder - file = driveService.files().update(fileId, null) - .setAddParents(folderId) - .setRemoveParents(previousParents.toString()) - .setFields("id, parents") - .execute(); - // [END moveFileToFolder] - return file.getParents(); - } - - public List searchFiles() throws IOException { - Drive driveService = this.service; - List files = new ArrayList(); - // [START searchFiles] - String pageToken = null; - do { - FileList result = driveService.files().list() - .setQ("mimeType='image/jpeg'") - .setSpaces("drive") - .setFields("nextPageToken, files(id, name)") - .setPageToken(pageToken) - .execute(); - for (File file : result.getFiles()) { - System.out.printf("Found file: %s (%s)\n", - file.getName(), file.getId()); - } - // [START_EXCLUDE silent] - files.addAll(result.getFiles()); - // [END_EXCLUDE] - pageToken = result.getNextPageToken(); - } while (pageToken != null); - // [END searchFiles] - return files; - } - - public List shareFile(String realFileId, String realUser, String realDomain) - throws IOException { - Drive driveService = this.service; - final List ids = new ArrayList(); - // [START shareFile] - String fileId = "1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ"; - // [START_EXCLUDE silent] - fileId = realFileId; - // [END_EXCLUDE] - JsonBatchCallback callback = new JsonBatchCallback() { - @Override - public void onFailure(GoogleJsonError e, - HttpHeaders responseHeaders) - throws IOException { - // Handle error - System.err.println(e.getMessage()); - } - - @Override - public void onSuccess(Permission permission, - HttpHeaders responseHeaders) - throws IOException { - System.out.println("Permission ID: " + permission.getId()); - // [START_EXCLUDE silent] - ids.add(permission.getId()); - // [END_EXCLUDE] - } - }; - BatchRequest batch = driveService.batch(); - Permission userPermission = new Permission() - .setType("user") - .setRole("writer") - .setEmailAddress("user@example.com"); - // [START_EXCLUDE silent] - userPermission.setEmailAddress(realUser); - // [END_EXCLUDE] - driveService.permissions().create(fileId, userPermission) - .setFields("id") - .queue(batch, callback); - - Permission domainPermission = new Permission() - .setType("domain") - .setRole("reader") - .setDomain("example.com"); - // [START_EXCLUDE silent] - domainPermission.setDomain(realDomain); - // [END_EXCLUDE] - driveService.permissions().create(fileId, domainPermission) - .setFields("id") - .queue(batch, callback); - - batch.execute(); - // [END shareFile] - return ids; - } - -} diff --git a/drive/snippets/drive_v3/src/main/java/TeamDriveSnippets.java b/drive/snippets/drive_v3/src/main/java/TeamDriveSnippets.java deleted file mode 100644 index eb2e0711..00000000 --- a/drive/snippets/drive_v3/src/main/java/TeamDriveSnippets.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * 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. - */ - -import com.google.api.client.http.FileContent; -import com.google.api.services.drive.Drive; -import com.google.api.services.drive.model.TeamDrive; -import com.google.api.services.drive.model.TeamDriveList; -import com.google.api.services.drive.model.Permission; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -public class TeamDriveSnippets { - private Drive service; - - public TeamDriveSnippets(Drive service) { - this.service = service; - } - - public String createTeamDrive() throws IOException { - Drive driveService = this.service; - // [START createTeamDrive] - TeamDrive teamDriveMetadata = new TeamDrive(); - teamDriveMetadata.setName("Project Resources"); - String requestId = UUID.randomUUID().toString(); - TeamDrive teamDrive = driveService.teamdrives().create(requestId, - teamDriveMetadata) - .execute(); - System.out.println("Team Drive ID: " + teamDrive.getId()); - // [END createTeamDrive] - return teamDrive.getId(); - } - - public List recoverTeamDrives(String realUser) - throws IOException { - Drive driveService = this.service; - List teamDrives = new ArrayList(); - // [START recoverTeamDrives] - // Find all Team Drives without an organizer and add one. - // Note: This example does not capture all cases. Team Drives - // that have an empty group as the sole organizer, or an - // organizer outside the organization are not captured. A - // more exhaustive approach would evaluate each Team Drive - // and the associated permissions and groups to ensure an active - // organizer is assigned. - String pageToken = null; - Permission newOrganizerPermission = new Permission() - .setType("user") - .setRole("organizer") - .setEmailAddress("user@example.com"); - // [START_EXCLUDE silent] - newOrganizerPermission.setEmailAddress(realUser); - // [END_EXCLUDE] - - do { - TeamDriveList result = driveService.teamdrives().list() - .setQ("organizerCount = 0") - .setFields("nextPageToken, teamDrives(id, name)") - .setUseDomainAdminAccess(true) - .setPageToken(pageToken) - .execute(); - for (TeamDrive teamDrive : result.getTeamDrives()) { - System.out.printf("Found Team Drive without organizer: %s (%s)\n", - teamDrive.getName(), teamDrive.getId()); - // Note: For improved efficiency, consider batching - // permission insert requests - Permission permissionResult = driveService.permissions() - .create(teamDrive.getId(), newOrganizerPermission) - .setUseDomainAdminAccess(true) - .setSupportsTeamDrives(true) - .setFields("id") - .execute(); - System.out.printf("Added organizer permission: %s\n", - permissionResult.getId()); - - } - // [START_EXCLUDE silent] - teamDrives.addAll(result.getTeamDrives()); - // [END_EXCLUDE] - pageToken = result.getNextPageToken(); - } while (pageToken != null); - // [END recoverTeamDrives] - return teamDrives; - } -} diff --git a/gmail/snippets/src/main/java/SettingsSnippets.java b/gmail/snippets/src/main/java/SettingsSnippets.java deleted file mode 100644 index 89bb8fd9..00000000 --- a/gmail/snippets/src/main/java/SettingsSnippets.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * 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. - */ - -import com.google.api.client.googleapis.batch.BatchRequest; -import com.google.api.client.googleapis.json.GoogleJsonError; -import com.google.api.client.http.FileContent; -import com.google.api.client.http.HttpHeaders; -import com.google.api.client.util.DateTime; -import com.google.api.services.gmail.Gmail; -import com.google.api.services.gmail.model.*; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.time.LocalDateTime; -import java.time.ZoneOffset; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - - -public class SettingsSnippets { - - private Gmail service; - - public SettingsSnippets(Gmail service) { - this.service = service; - } - - public String updateSignature() throws IOException { - Gmail gmailService = this.service; - // [START updateSignature] - SendAs primaryAlias = null; - ListSendAsResponse aliases = gmailService.users().settings().sendAs().list("me").execute(); - for (SendAs alias: aliases.getSendAs()) { - if (alias.getIsPrimary()) { - primaryAlias = alias; - break; - } - } - SendAs aliasSettings = new SendAs().setSignature("I heart cats."); - SendAs result = gmailService.users().settings().sendAs().patch( - "me", - primaryAlias.getSendAsEmail(), - aliasSettings) - .execute(); - System.out.println("Updated signature for " + result.getDisplayName()); - // [END updateSignature] - return result.getSignature(); - } - - public String createFilter(String realLabelId) throws IOException { - Gmail gmailService = this.service; - // [START createFilter] - String labelId = "Label_14"; // ID of the user label to add - // [START_EXCLUDE silent] - labelId = realLabelId; - // [END_EXCLUDE] - Filter filter = new Filter() - .setCriteria(new FilterCriteria() - .setFrom("cat-enthusiasts@example.com")) - .setAction(new FilterAction() - .setAddLabelIds(Arrays.asList(labelId)) - .setRemoveLabelIds(Arrays.asList("INBOX"))); - Filter result = gmailService.users().settings().filters().create("me", filter).execute(); - System.out.println("Created filter " + result.getId()); - // [END createFilter] - return result.getId(); - } - - public AutoForwarding enableForwarding(String realForwardingAddress) throws IOException { - Gmail gmailService = this.service; - // [START enableForwarding] - ForwardingAddress address = new ForwardingAddress() - .setForwardingEmail("user2@example.com"); - // [START_EXCLUDE silent] - address.setForwardingEmail(realForwardingAddress); - // [END_EXCLUDE] - ForwardingAddress createAddressResult = gmailService.users().settings().forwardingAddresses() - .create("me", address).execute(); - if (createAddressResult.getVerificationStatus().equals("accepted")) { - AutoForwarding autoForwarding = new AutoForwarding() - .setEnabled(true) - .setEmailAddress(address.getForwardingEmail()) - .setDisposition("trash"); - autoForwarding = gmailService.users().settings().updateAutoForwarding("me", autoForwarding).execute(); - // [START_EXCLUDE silent] - return autoForwarding; - } - // [END enableForwarding] - return null; - } - - public VacationSettings enableAutoReply() throws IOException { - Gmail gmailService = this.service; - // [START enableAutoReply] - VacationSettings vacationSettings = new VacationSettings() - .setEnableAutoReply(true) - .setResponseBodyHtml("I'm on vacation and will reply when I'm back in the office. Thanks!") - .setRestrictToDomain(true) - .setStartTime(LocalDateTime.now().toEpochSecond(ZoneOffset.UTC) * 1000) - .setEndTime(LocalDateTime.now().plusDays(7).toEpochSecond(ZoneOffset.UTC) * 1000); - VacationSettings response = gmailService.users().settings().updateVacation("me", vacationSettings).execute(); - // [END enableAutoReply] - return response; - } - -} diff --git a/gmail/snippets/src/main/java/SmimeSnippets.java b/gmail/snippets/src/main/java/SmimeSnippets.java deleted file mode 100644 index 7c0fd468..00000000 --- a/gmail/snippets/src/main/java/SmimeSnippets.java +++ /dev/null @@ -1,275 +0,0 @@ -/* - * 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. - */ - -import com.google.api.services.gmail.Gmail; -import com.google.api.services.gmail.model.*; -import com.google.api.services.gmail.model.SmimeInfo; - -import java.io.*; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.time.Instant; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.Base64; -import org.apache.commons.csv.CSVFormat; -import org.apache.commons.csv.CSVParser; -import org.apache.commons.csv.CSVRecord; - -class SmimeSnippets { - - SmimeSnippets() {} - - // [START create_smime_info] - /** - * Create an SmimeInfo resource for a certificate from file. - * - * @param filename Name of the file containing the S/MIME certificate. - * @param password Password for the certificate file, or null if the file is not - * password-protected. - * @return An SmimeInfo object with the specified certificate. - */ - public static SmimeInfo createSmimeInfo(String filename, String password) { - SmimeInfo smimeInfo = null; - InputStream in = null; - - try { - byte[] fileContent = Files.readAllBytes(Paths.get(filename)); - smimeInfo = new SmimeInfo(); - smimeInfo.setPkcs12(Base64.getUrlEncoder().encodeToString(fileContent)); - if (password != null && password.length() > 0) { - smimeInfo.setEncryptedKeyPassword(password); - } - } catch (Exception e) { - System.out.printf("An error occured while reading the certificate file: %s\n", e); - } - return smimeInfo; - } - // [END create_smime_info] - - // [START insert_smime_info] - /** - * Upload an S/MIME certificate for the user. - * - * @param service Authorized GMail API service instance. - * @param userId User's email address. - * @param sendAsEmail The "send as" email address, or null if it should be the same as userId. - * @param smimeInfo The SmimeInfo object containing the user's S/MIME certificate. - * @return An SmimeInfo object with details about the uploaded certificate. - */ - public static SmimeInfo insertSmimeInfo( - Gmail service, String userId, String sendAsEmail, SmimeInfo smimeInfo) { - if (sendAsEmail == null) { - sendAsEmail = userId; - } - - try { - SmimeInfo results = - service - .users() - .settings() - .sendAs() - .smimeInfo() - .insert(userId, sendAsEmail, smimeInfo) - .execute(); - System.out.printf("Inserted certificate, id: %s\n", results.getId()); - return results; - } catch (IOException e) { - System.err.printf("An error occured: %s", e); - } - - return null; - } - // [END insert_smime_info] - - // [START insert_cert_from_csv] - /** - * A builder that returns a GMail API service instance that is authorized to act on behalf of the - * specified user. - */ - @FunctionalInterface - public interface GmailServiceBuilder { - Gmail buildGmailServiceFromUserId(String userId) throws IOException; - } - - /** - * Upload S/MIME certificates based on the contents of a CSV file. - * - *

Each row of the CSV file should contain a user ID, path to the certificate, and the - * certificate password. - * - * @param serviceBuilder A function that returns an authorized GMail API service instance for a - * given user. - * @param csvFilename Name of the CSV file. - */ - public static void insertCertFromCsv(GmailServiceBuilder serviceBuilder, String csvFilename) { - try { - File csvFile = new File(csvFilename); - CSVParser parser = CSVParser.parse(csvFile, java.nio.charset.StandardCharsets.UTF_8, CSVFormat.DEFAULT); - for (CSVRecord record : parser) { - String userId = record.get(0); - String certFilename = record.get(1); - String certPassword = record.get(2); - SmimeInfo smimeInfo = createSmimeInfo(certFilename, certPassword); - if (smimeInfo == null) { - System.err.printf("Unable to read certificate file for userId: %s\n", userId); - continue; - } - insertSmimeInfo(serviceBuilder.buildGmailServiceFromUserId(userId), userId, userId, smimeInfo); - } - } catch (Exception e) { - System.err.printf("An error occured while reading the CSV file: %s", e); - } - } - // [END insert_cert_from_csv] - - // [START update_smime_certs] - /** - * Update S/MIME certificates for the user. - * - *

First performs a lookup of all certificates for a user. If there are no certificates, or - * they all expire before the specified date/time, uploads the certificate in the specified file. - * If the default certificate is expired or there was no default set, chooses the certificate with - * the expiration furthest into the future and sets it as default. - * - * @param service Authorized GMail API service instance. - * @param userId User's email address. - * @param sendAsEmail The "send as" email address, or None if it should be the same as user_id. - * @param certFilename Name of the file containing the S/MIME certificate. - * @param certPassword Password for the certificate file, or None if the file is not - * password-protected. - * @param expireTime DateTime object against which the certificate expiration is compared. If - * None, uses the current time. @ returns: The ID of the default certificate. - * @return The ID of the default certifcate. - */ - public static String updateSmimeCerts( - Gmail service, - String userId, - String sendAsEmail, - String certFilename, - String certPassword, - LocalDateTime expireTime) { - if (sendAsEmail == null) { - sendAsEmail = userId; - } - - ListSmimeInfoResponse listResults = null; - try { - listResults = - service.users().settings().sendAs().smimeInfo().list(userId, sendAsEmail).execute(); - } catch (IOException e) { - System.err.printf("An error occurred during list: %s\n", e); - return null; - } - - String defaultCertId = null; - String bestCertId = null; - LocalDateTime bestCertExpire = LocalDateTime.MIN; - - if (expireTime == null) { - expireTime = LocalDateTime.now(); - } - if (listResults != null && listResults.getSmimeInfo() != null) { - for (SmimeInfo smimeInfo : listResults.getSmimeInfo()) { - String certId = smimeInfo.getId(); - boolean isDefaultCert = smimeInfo.getIsDefault(); - if (isDefaultCert) { - defaultCertId = certId; - } - LocalDateTime exp = LocalDateTime.ofInstant( - Instant.ofEpochMilli(smimeInfo.getExpiration()), ZoneId.systemDefault()); - if (exp.isAfter(expireTime)) { - if (exp.isAfter(bestCertExpire)) { - bestCertId = certId; - bestCertExpire = exp; - } - } else { - if (isDefaultCert) { - defaultCertId = null; - } - } - } - } - if (defaultCertId == null) { - String defaultId = bestCertId; - if (defaultId == null && certFilename != null) { - SmimeInfo smimeInfo = createSmimeInfo(certFilename, certPassword); - SmimeInfo insertResults = insertSmimeInfo(service, userId, sendAsEmail, smimeInfo); - if (insertResults != null) { - defaultId = insertResults.getId(); - } - } - - if (defaultId != null) { - try { - service - .users() - .settings() - .sendAs() - .smimeInfo() - .setDefault(userId, sendAsEmail, defaultId) - .execute(); - return defaultId; - } catch (IOException e) { - System.err.printf("An error occured during setDefault: %s", e); - } - } - } else { - return defaultCertId; - } - - return null; - } - - /** - * Update S/MIME certificates based on the contents of a CSV file. - * - *

Each row of the CSV file should contain a user ID, path to the certificate, and the - * certificate password. - * - * @param serviceBuilder A function that returns an authorized GMail API service instance for a - * given user. - * @param csvFilename Name of the CSV file. - * @param expireTime DateTime object against which the certificate expiration is compared. If - * None, uses the current time. - */ - public static void updateSmimeFromCsv( - GmailServiceBuilder serviceBuilder, String csvFilename, LocalDateTime expireTime) { - try { - File csvFile = new File(csvFilename); - CSVParser parser = - CSVParser.parse( - csvFile, - java.nio.charset.StandardCharsets.UTF_8, - CSVFormat.DEFAULT.withHeader().withSkipHeaderRecord()); - for (CSVRecord record : parser) { - String userId = record.get(0); - String certFilename = record.get(1); - String certPassword = record.get(2); - updateSmimeCerts( - serviceBuilder.buildGmailServiceFromUserId(userId), - userId, - userId, - certFilename, - certPassword, - expireTime); - } - } catch (Exception e) { - System.err.printf("An error occured while reading the CSV file: %s", e); - } - } - // [END update_smime_certs] -} From 39bf07bc89c4fa11fd5ade6abed0cfb1ddd0564b Mon Sep 17 00:00:00 2001 From: Steven Bazyl Date: Fri, 5 Aug 2022 10:21:46 -0600 Subject: [PATCH 014/152] chore: Remove stray lint to appease linter --- .github/snippet-bot.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/snippet-bot.yml b/.github/snippet-bot.yml index bb488a81..6d6d1266 100644 --- a/.github/snippet-bot.yml +++ b/.github/snippet-bot.yml @@ -11,4 +11,3 @@ # 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. - From 6b09f7c7a4356ae4a33ab0f7e620d226b53aea72 Mon Sep 17 00:00:00 2001 From: googleworkspace-bot <109114539+googleworkspace-bot@users.noreply.github.com> Date: Fri, 5 Aug 2022 12:25:11 -0600 Subject: [PATCH 015/152] chore: Synced local '.github/linters/' with remote 'sync-files/defaults/.github/linters/' (#257) --- .github/linters/.htmlhintrc | 25 ++++++++++++++ .github/linters/.yaml-lint.yml | 59 ++++++++++++++++++++++++++++++++++ .github/linters/sun_checks.xml | 3 -- 3 files changed, 84 insertions(+), 3 deletions(-) create mode 100644 .github/linters/.htmlhintrc create mode 100644 .github/linters/.yaml-lint.yml diff --git a/.github/linters/.htmlhintrc b/.github/linters/.htmlhintrc new file mode 100644 index 00000000..70391a46 --- /dev/null +++ b/.github/linters/.htmlhintrc @@ -0,0 +1,25 @@ +{ + "tagname-lowercase": true, + "attr-lowercase": true, + "attr-value-double-quotes": true, + "attr-value-not-empty": false, + "attr-no-duplication": true, + "doctype-first": false, + "tag-pair": true, + "tag-self-close": false, + "spec-char-escape": false, + "id-unique": true, + "src-not-empty": true, + "title-require": false, + "alt-require": true, + "doctype-html5": true, + "id-class-value": false, + "style-disabled": false, + "inline-style-disabled": false, + "inline-script-disabled": false, + "space-tab-mixed-disabled": "space", + "id-class-ad-disabled": false, + "href-abs-or-rel": false, + "attr-unsafe-chars": true, + "head-script-disabled": false +} diff --git a/.github/linters/.yaml-lint.yml b/.github/linters/.yaml-lint.yml new file mode 100644 index 00000000..e8394fd5 --- /dev/null +++ b/.github/linters/.yaml-lint.yml @@ -0,0 +1,59 @@ +--- +########################################### +# These are the rules used for # +# linting all the yaml files in the stack # +# NOTE: # +# You can disable line with: # +# # yamllint disable-line # +########################################### +rules: + braces: + level: warning + min-spaces-inside: 0 + max-spaces-inside: 0 + min-spaces-inside-empty: 1 + max-spaces-inside-empty: 5 + brackets: + level: warning + min-spaces-inside: 0 + max-spaces-inside: 0 + min-spaces-inside-empty: 1 + max-spaces-inside-empty: 5 + colons: + level: warning + max-spaces-before: 0 + max-spaces-after: 1 + commas: + level: warning + max-spaces-before: 0 + min-spaces-after: 1 + max-spaces-after: 1 + comments: disable + comments-indentation: disable + document-end: disable + document-start: + level: warning + present: true + empty-lines: + level: warning + max: 2 + max-start: 0 + max-end: 0 + hyphens: + level: warning + max-spaces-after: 1 + indentation: + level: warning + spaces: consistent + indent-sequences: true + check-multi-line-strings: false + key-duplicates: enable + line-length: + level: warning + max: 120 + allow-non-breakable-words: true + allow-non-breakable-inline-mappings: true + new-line-at-end-of-file: disable + new-lines: + type: unix + trailing-spaces: disable \ No newline at end of file diff --git a/.github/linters/sun_checks.xml b/.github/linters/sun_checks.xml index 59cbc573..de6c6cd4 100644 --- a/.github/linters/sun_checks.xml +++ b/.github/linters/sun_checks.xml @@ -1,13 +1,10 @@ - - 4.0.0 - - com.google - google - 5 - - com.google.apis-samples - calendar-sync-samples - 1 - Samples demonstrating syncing techniques for the Calendar API. - TODO: Determine the final URL. - 2014 - - 2.0.9 - + + 4.0.0 + + com.google + google + 5 + + com.google.apis-samples + calendar-sync-samples + 1 + Samples demonstrating syncing techniques for the Calendar API. + TODO: Determine the final URL. + 2014 + + 2.0.9 + - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.6 - 1.6 - - - - org.codehaus.mojo - exec-maven-plugin - 1.1 - - - - java - - - - - - - java.util.logging.config.file - logging.properties - - - - - - ${project.artifactId}-${project.version} - + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + + + + org.codehaus.mojo + exec-maven-plugin + 1.1 + + + + java + + + + + + + java.util.logging.config.file + logging.properties + + + + + + ${project.artifactId}-${project.version} + - - - com.google.apis - google-api-services-calendar - v3-rev20211026-1.32.1 - - - com.google.api-client - google-api-client - 1.33.0 - - - com.google.http-client - google-http-client-jackson2 - ${project.http.version} - - - com.google.oauth-client - google-oauth-client-jetty - ${project.oauth.version} - - - com.google.collections - google-collections - 1.0 - - + + + com.google.apis + google-api-services-calendar + v3-rev20211026-1.32.1 + + + com.google.api-client + google-api-client + 1.33.0 + + + com.google.http-client + google-http-client-jackson2 + ${project.http.version} + + + com.google.oauth-client + google-oauth-client-jetty + ${project.oauth.version} + + + com.google.collections + google-collections + 1.0 + + - - 1.41.0 - 1.32.1 - UTF-8 - + + 1.41.0 + 1.32.1 + UTF-8 + diff --git a/calendar/sync/src/main/java/com/google/api/services/samples/calendar/sync/ConditionalModificationSample.java b/calendar/sync/src/main/java/com/google/api/services/samples/calendar/sync/ConditionalModificationSample.java index e84a36a4..a3b0c500 100644 --- a/calendar/sync/src/main/java/com/google/api/services/samples/calendar/sync/ConditionalModificationSample.java +++ b/calendar/sync/src/main/java/com/google/api/services/samples/calendar/sync/ConditionalModificationSample.java @@ -20,7 +20,6 @@ import com.google.api.services.calendar.CalendarScopes; import com.google.api.services.calendar.model.Event; import com.google.common.collect.Lists; - import java.io.IOException; import java.util.List; @@ -35,10 +34,14 @@ */ public class ConditionalModificationSample { - /** The maximum number of times to attempt to update the event, before aborting. */ + /** + * The maximum number of times to attempt to update the event, before aborting. + */ private static final int MAX_UPDATE_ATTEMPTS = 5; - /** Global instance of the Calendar client. */ + /** + * Global instance of the Calendar client. + */ private static Calendar client; public static void main(String[] args) { diff --git a/calendar/sync/src/main/java/com/google/api/services/samples/calendar/sync/ConditionalRetrievalSample.java b/calendar/sync/src/main/java/com/google/api/services/samples/calendar/sync/ConditionalRetrievalSample.java index 1d20f796..66dd210d 100644 --- a/calendar/sync/src/main/java/com/google/api/services/samples/calendar/sync/ConditionalRetrievalSample.java +++ b/calendar/sync/src/main/java/com/google/api/services/samples/calendar/sync/ConditionalRetrievalSample.java @@ -20,7 +20,6 @@ import com.google.api.services.calendar.CalendarScopes; import com.google.api.services.calendar.model.Event; import com.google.common.collect.Lists; - import java.io.IOException; import java.util.List; @@ -35,7 +34,9 @@ */ public class ConditionalRetrievalSample { - /** Global instance of the Calendar client. */ + /** + * Global instance of the Calendar client. + */ private static Calendar client; public static void main(String[] args) { diff --git a/calendar/sync/src/main/java/com/google/api/services/samples/calendar/sync/SyncTokenSample.java b/calendar/sync/src/main/java/com/google/api/services/samples/calendar/sync/SyncTokenSample.java index 38b24ee3..396de651 100644 --- a/calendar/sync/src/main/java/com/google/api/services/samples/calendar/sync/SyncTokenSample.java +++ b/calendar/sync/src/main/java/com/google/api/services/samples/calendar/sync/SyncTokenSample.java @@ -22,7 +22,6 @@ import com.google.api.services.calendar.model.Event; import com.google.api.services.calendar.model.Events; import com.google.common.collect.Lists; - import java.io.IOException; import java.util.Date; import java.util.List; @@ -37,18 +36,23 @@ */ public class SyncTokenSample { - /** Global instance of the Calendar client. */ + /** + * The key in the sync settings datastore that holds the current sync token. + */ + private static final String SYNC_TOKEN_KEY = "syncToken"; + /** + * Global instance of the Calendar client. + */ private static Calendar client; - - /** Global instance of the event datastore. */ + /** + * Global instance of the event datastore. + */ private static DataStore eventDataStore; - - /** Global instance of the sync settings datastore. */ + /** + * Global instance of the sync settings datastore. + */ private static DataStore syncSettingsDataStore; - /** The key in the sync settings datastore that holds the current sync token. */ - private static final String SYNC_TOKEN_KEY = "syncToken"; - public static void main(String[] args) { try { List scopes = Lists.newArrayList(CalendarScopes.CALENDAR_READONLY); diff --git a/calendar/sync/src/main/java/com/google/api/services/samples/calendar/sync/Utils.java b/calendar/sync/src/main/java/com/google/api/services/samples/calendar/sync/Utils.java index 32e9fb87..775dc403 100644 --- a/calendar/sync/src/main/java/com/google/api/services/samples/calendar/sync/Utils.java +++ b/calendar/sync/src/main/java/com/google/api/services/samples/calendar/sync/Utils.java @@ -30,7 +30,6 @@ import com.google.api.services.calendar.model.Event; import com.google.api.services.calendar.model.Event.Reminders; import com.google.api.services.calendar.model.EventDateTime; - import java.io.IOException; import java.io.InputStreamReader; import java.util.Date; @@ -41,20 +40,27 @@ * A collection of utility methods used by these samples. */ public class Utils { - /** Application name */ + /** + * Application name + */ private static final String APPLICATION_NAME = "Calendar Sync Samples"; - /** Directory to store user credentials. */ + /** + * Directory to store user credentials. + */ private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"), ".store/calendar-sync"); - - /** Global instance of the {@link DataStoreFactory}. */ - private static FileDataStoreFactory dataStoreFactory; - - /** Global instance of the JSON factory. */ + /** + * Global instance of the JSON factory. + */ private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); - - /** Global instance of the HTTP transport. */ + /** + * Global instance of the {@link DataStoreFactory}. + */ + private static FileDataStoreFactory dataStoreFactory; + /** + * Global instance of the HTTP transport. + */ private static HttpTransport httpTransport; static { @@ -67,14 +73,18 @@ public class Utils { } } - /** Creates a new Calendar client to use when making requests to the API. */ + /** + * Creates a new Calendar client to use when making requests to the API. + */ public static Calendar createCalendarClient(List scopes) throws Exception { Credential credential = authorize(scopes); return new Calendar.Builder( httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build(); } - /** Authorizes the installed application to access user's protected data. */ + /** + * Authorizes the installed application to access user's protected data. + */ public static Credential authorize(List scopes) throws Exception { // Load client secrets. GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, @@ -83,7 +93,7 @@ public static Credential authorize(List scopes) throws Exception { || clientSecrets.getDetails().getClientSecret().startsWith("Enter")) { System.out.println( "Overwrite the src/main/resources/client_secrets.json file with the client secrets file " - + "you downloaded from your Google Developers Console project."); + + "you downloaded from your Google Developers Console project."); System.exit(1); } @@ -94,12 +104,16 @@ public static Credential authorize(List scopes) throws Exception { return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user"); } - /** Gets the datastore factory used in these samples. */ + /** + * Gets the datastore factory used in these samples. + */ public static DataStoreFactory getDataStoreFactory() { return dataStoreFactory; } - /** Creates a test event. */ + /** + * Creates a test event. + */ public static Event createTestEvent(Calendar client, String summary) throws IOException { Date oneHourFromNow = Utils.getRelativeDate(java.util.Calendar.HOUR, 1); Date twoHoursFromNow = Utils.getRelativeDate(java.util.Calendar.HOUR, 2); @@ -116,7 +130,7 @@ public static Event createTestEvent(Calendar client, String summary) throws IOEx /** * Gets a new {@link java.util.Date} relative to the current date and time. * - * @param field the field identifier from {@link java.util.Calendar} to increment + * @param field the field identifier from {@link java.util.Calendar} to increment * @param amount the amount of the field to increment * @return the new date */ diff --git a/classroom/quickstart/src/main/java/ClassroomQuickstart.java b/classroom/quickstart/src/main/java/ClassroomQuickstart.java index 29d9ae24..fb174b5e 100644 --- a/classroom/quickstart/src/main/java/ClassroomQuickstart.java +++ b/classroom/quickstart/src/main/java/ClassroomQuickstart.java @@ -13,6 +13,7 @@ // limitations under the License. // [START classroom_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; @@ -36,61 +37,66 @@ import java.util.List; public class ClassroomQuickstart { - private static final String APPLICATION_NAME = "Google Classroom API Java Quickstart"; - private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); - 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(ClassroomScopes.CLASSROOM_COURSES_READONLY); - private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; + private static final String APPLICATION_NAME = "Google Classroom API Java Quickstart"; + private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); + private static final String TOKENS_DIRECTORY_PATH = "tokens"; - /** - * Creates an authorized Credential object. - * @param HTTP_TRANSPORT The network HTTP Transport. - * @return An authorized Credential object. - * @throws IOException If the credentials.json file cannot be found. - */ - private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException { - // Load client secrets. - InputStream in = ClassroomQuickstart.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)); + /** + * 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(ClassroomScopes.CLASSROOM_COURSES_READONLY); + private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; - // 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"); + /** + * Creates an authorized Credential object. + * + * @param HTTP_TRANSPORT The network HTTP Transport. + * @return An authorized Credential object. + * @throws IOException If the credentials.json file cannot be found. + */ + private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) + throws IOException { + // Load client secrets. + InputStream in = ClassroomQuickstart.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"); + } - public static void main(String... args) throws IOException, GeneralSecurityException { - // Build a new authorized API client service. - final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); - Classroom service = new Classroom.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) - .setApplicationName(APPLICATION_NAME) - .build(); + public static void main(String... args) throws IOException, GeneralSecurityException { + // Build a new authorized API client service. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Classroom service = + new Classroom.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) + .setApplicationName(APPLICATION_NAME) + .build(); - // List the first 10 courses that the user has access to. - ListCoursesResponse response = service.courses().list() - .setPageSize(10) - .execute(); - List courses = response.getCourses(); - if (courses == null || courses.size() == 0) { - System.out.println("No courses found."); - } else { - System.out.println("Courses:"); - for (Course course : courses) { - System.out.printf("%s\n", course.getName()); - } - } + // List the first 10 courses that the user has access to. + ListCoursesResponse response = service.courses().list() + .setPageSize(10) + .execute(); + List courses = response.getCourses(); + if (courses == null || courses.size() == 0) { + System.out.println("No courses found."); + } else { + System.out.println("Courses:"); + for (Course course : courses) { + System.out.printf("%s\n", course.getName()); + } } + } } // [END classroom_quickstart] diff --git a/classroom/snippets/src/main/java/AddStudent.java b/classroom/snippets/src/main/java/AddStudent.java index b3237c9a..142072a3 100644 --- a/classroom/snippets/src/main/java/AddStudent.java +++ b/classroom/snippets/src/main/java/AddStudent.java @@ -14,6 +14,7 @@ // [START classroom_add_student] + import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; @@ -29,52 +30,52 @@ /* Class to demonstrate the use of Classroom Add Student API */ public class AddStudent { - /** - * Add a student in a specified 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. - */ - public static Student addStudent(String courseId, String enrollmentCode) - throws IOException { + /** + * Add a student in a specified 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. + */ + 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); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_ROSTERS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the classroom API client - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom samples") - .build(); + // Create the classroom API client + Classroom service = new Classroom.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Classroom samples") + .build(); - Student student = new Student().setUserId("me"); - try { - // Enrolling a student to a specified course - 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", - student.getProfile().getName().getFullName(), courseId); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 409) { - System.out.println("You are already a member of this course."); - } else if (error.getCode() == 403) { - System.out.println("The caller does not have permission.\n"); - } else { - throw e; - } - } - return student; + Student student = new Student().setUserId("me"); + try { + // Enrolling a student to a specified course + 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", + student.getProfile().getName().getFullName(), courseId); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 409) { + System.out.println("You are already a member of this course."); + } else if (error.getCode() == 403) { + System.out.println("The caller does not have permission.\n"); + } else { + throw e; + } } + return student; + } } // [END classroom_add_student] \ No newline at end of file diff --git a/classroom/snippets/src/main/java/AddTeacher.java b/classroom/snippets/src/main/java/AddTeacher.java index bede3367..9f5652e3 100644 --- a/classroom/snippets/src/main/java/AddTeacher.java +++ b/classroom/snippets/src/main/java/AddTeacher.java @@ -14,6 +14,7 @@ // [START classroom_add_teacher] + import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; @@ -29,50 +30,50 @@ /* Class to demonstrate the use of Classroom Add Teacher API */ public class AddTeacher { - /** - * Add teacher to a specific 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. - */ - public static Teacher addTeacher(String courseId, String teacherEmail) - throws IOException { + /** + * Add teacher to a specific 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. + */ + 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); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_ROSTERS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the classroom API client - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom samples") - .build(); + // Create the classroom API client + Classroom service = new Classroom.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .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", - teacher.getProfile().getName().getFullName(), courseId); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 409) { - System.out.printf("User '%s' is already a member of this course.\n", teacherEmail); - } else if (error.getCode() == 403) { - System.out.println("The caller does not have permission.\n"); - } else { - throw e; - } - } - return teacher; + 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", + teacher.getProfile().getName().getFullName(), courseId); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 409) { + System.out.printf("User '%s' is already a member of this course.\n", teacherEmail); + } else if (error.getCode() == 403) { + System.out.println("The caller does not have permission.\n"); + } else { + throw e; + } } + return teacher; + } } // [END classroom_add_teacher] \ No newline at end of file diff --git a/classroom/snippets/src/main/java/BatchAddStudents.java b/classroom/snippets/src/main/java/BatchAddStudents.java index 676cddc3..9588ec3d 100644 --- a/classroom/snippets/src/main/java/BatchAddStudents.java +++ b/classroom/snippets/src/main/java/BatchAddStudents.java @@ -14,6 +14,7 @@ // [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.json.GoogleJsonError; @@ -32,46 +33,46 @@ /* Class to demonstrate the use of Classroom Batch Add Students API */ public class BatchAddStudents { - /** - * Add multiple students in a specified course. - * - * @param courseId - Id of the course to add students. - * @param studentEmails - Email address of the students. - * @throws IOException - if credentials file not found. - */ - public static void batchAddStudents(String courseId, List studentEmails) - throws IOException { + /** + * Add multiple students in a specified course. + * + * @param courseId - Id of the course to add students. + * @param studentEmails - Email address of the students. + * @throws IOException - if credentials file not found. + */ + 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); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_ROSTERS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the classroom API client - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom samples") - .build(); + // Create the classroom API client + Classroom service = new Classroom.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .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()); - } + 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()); + } - 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); - } - batch.execute(); + 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); } + batch.execute(); + } } // [END classroom_batch_add_students] \ No newline at end of file diff --git a/classroom/snippets/src/main/java/Courses.java b/classroom/snippets/src/main/java/Courses.java deleted file mode 100644 index 0526ddd5..00000000 --- a/classroom/snippets/src/main/java/Courses.java +++ /dev/null @@ -1,273 +0,0 @@ -/* - * 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. - */ - -import com.google.api.client.googleapis.batch.BatchRequest; -import com.google.api.client.googleapis.batch.json.JsonBatchCallback; -import com.google.api.client.googleapis.json.GoogleJsonError; -import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpHeaders; -import com.google.api.services.classroom.Classroom; -import com.google.api.services.classroom.model.Course; -import com.google.api.services.classroom.model.CourseAlias; -import com.google.api.services.classroom.model.ListCourseAliasesResponse; -import com.google.api.services.classroom.model.ListCoursesResponse; -import com.google.api.services.classroom.model.Student; -import com.google.api.services.classroom.model.Teacher; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - - -public class Courses { - public static Course createCourse(Classroom service) throws IOException { - // [START createCourse] - Course 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"); - course = service.courses().create(course).execute(); - System.out.printf("Course created: %s (%s)\n", course.getName(), course.getId()); - // [END createCourse] - return course; - } - - public static Course getCourse(Classroom service, String _courseId) throws IOException { - // [START getCourse] - String courseId = "123456"; - // [START_EXCLUDE silent] - courseId = _courseId; - // [END_EXCLUDE] - Course course = null; - try { - course = service.courses().get(courseId).execute(); - System.out.printf("Course '%s' found.\n", course.getName()); - } catch (GoogleJsonResponseException e) { - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 404) { - System.out.printf("Course with ID '%s' not found.\n", courseId); - } else { - throw e; - } - } - // [END getCourse] - return course; - } - - public static List listCourses(Classroom service) throws IOException { - // [START listCourses] - String pageToken = null; - List courses = new ArrayList(); - - do { - ListCoursesResponse response = service.courses().list() - .setPageSize(100) - .setPageToken(pageToken) - .execute(); - courses.addAll(response.getCourses()); - pageToken = response.getNextPageToken(); - } while (pageToken != null); - - if (courses.isEmpty()) { - System.out.println("No courses found."); - } else { - System.out.println("Courses:"); - for (Course course : courses) { - System.out.printf("%s (%s)\n", course.getName(), course.getId()); - } - } - // [END listCourses] - return courses; - } - - public static Course updateCourse(Classroom service, String _courseId) throws IOException { - // [START updateCourse] - String courseId = "123456"; - // [START_EXCLUDE silent] - courseId = _courseId; - // [END_EXCLUDE] - Course course = service.courses().get(courseId).execute(); - course.setSection("Period 3"); - course.setRoom("302"); - course = service.courses().update(courseId, course).execute(); - System.out.printf("Course '%s' updated.\n", course.getName()); - // [END updateCourse] - return course; - } - - public static Course patchCourse(Classroom service, String _courseId) throws IOException { - // [START patchCourse] - String courseId = "123456"; - // [START_EXCLUDE silent] - courseId = _courseId; - // [END_EXCLUDE] - Course 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()); - // [END patchCourse] - return course; - } - - public static CourseAlias createCourseAlias(Classroom service, String _courseId, String _alias) - throws IOException { - // [START createCourseAlias] - String courseId = "123456"; - String alias = "p:bio10p2"; - // [START_EXCLUDE silent] - courseId = _courseId; - alias = _alias; - // [END_EXCLUDE] - CourseAlias courseAlias = new CourseAlias().setAlias(alias); - try { - courseAlias = service.courses().aliases().create(courseId, courseAlias).execute(); - System.out.printf("Alias '%s' created.\n", courseAlias.getAlias()); - } catch (GoogleJsonResponseException e) { - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 409) { - System.out.printf("Alias '%s' is already in use.\n", alias); - } else { - throw e; - } - } - // [END createCourseAlias] - return courseAlias; - } - - public static List listCourseAliases(Classroom service, String _courseId) - throws IOException { - // [START listCourseAliases] - String courseId = "123456"; - // [START_EXCLUDE silent] - courseId = _courseId; - // [END_EXCLUDE] - String pageToken = null; - List courseAliases = new ArrayList(); - - do { - ListCourseAliasesResponse response = service.courses().aliases().list(courseId) - .setPageSize(100) - .setPageToken(pageToken) - .execute(); - courseAliases.addAll(response.getAliases()); - pageToken = response.getNextPageToken(); - } while (pageToken != null); - - if (courseAliases.isEmpty()) { - System.out.println("No aliases found."); - } else { - System.out.println("Aliases:"); - for (CourseAlias courseAlias : courseAliases) { - System.out.println(courseAlias.getAlias()); - } - } - // [END listCourseAliases] - return courseAliases; - } - - public static Teacher addTeacher(Classroom service, String _courseId, String _teacherEmail) - throws IOException { - // [START addTeacher] - String courseId = "123456"; - String teacherEmail = "alice@example.edu"; - // [START_EXCLUDE silent] - courseId = _courseId; - teacherEmail = _teacherEmail; - // [END_EXCLUDE] - Teacher teacher = new Teacher().setUserId(teacherEmail); - try { - teacher = service.courses().teachers().create(courseId, teacher).execute(); - 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) { - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 409) { - System.out.printf("User '%s' is already a member of this course.\n", teacherEmail); - } else { - throw e; - } - } - // [END addTeacher] - return teacher; - } - - public static Student enrollAsStudent(Classroom service, String _courseId, - String _enrollmentCode) throws IOException { - // [START enrollAsStudent] - String courseId = "123456"; - String enrollmentCode = "abcdef"; - // [START_EXCLUDE silent] - courseId = _courseId; - enrollmentCode = _enrollmentCode; - // [END_EXCLUDE] - Student student = new Student().setUserId("me"); - try { - student = service.courses().students().create(courseId, student) - .setEnrollmentCode(enrollmentCode) - .execute(); - 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) { - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 409) { - System.out.println("You are already a member of this course."); - } else { - throw e; - } - } - // [END enrollAsStudent] - return student; - } - - public static void batchAddStudents(Classroom service, String _courseId, - List _studentEmails) throws IOException{ - // [START batchAddStudents] - String courseId = "123456"; - List studentEmails = Arrays.asList("alice@example.edu", "bob@example.edu"); - // [START_EXCLUDE silent] - courseId = _courseId; - studentEmails = _studentEmails; - // [END_EXCLUDE] - 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()); - } - - public void onFailure(GoogleJsonError error, HttpHeaders responseHeaders) - throws IOException { - 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); - } - batch.execute(); - // [END batchAddStudents] - } -} diff --git a/classroom/snippets/src/main/java/CreateCourse.java b/classroom/snippets/src/main/java/CreateCourse.java index d1bca2d4..ce33dd4d 100644 --- a/classroom/snippets/src/main/java/CreateCourse.java +++ b/classroom/snippets/src/main/java/CreateCourse.java @@ -14,6 +14,7 @@ // [START classroom_create_course] + import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; @@ -29,53 +30,53 @@ /* Class to demonstrate the use of Classroom Create Course API */ public class CreateCourse { - /** - * Creates a course - * - * @return newly created course - * @throws IOException - if credentials file not found. - */ - public static Course createCourse() throws IOException { + /** + * Creates a course + * + * @return newly created course + * @throws IOException - if credentials file not found. + */ + 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); + 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(); + // Create the classroom API client + Classroom service = new Classroom.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .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"); - 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()); - } catch (GoogleJsonResponseException e) { - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 400) { - System.err.println("Unable to create course, ownerId not specified.\n"); - } else { - throw e; - } - } - return course; + 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"); + 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()); + } catch (GoogleJsonResponseException e) { + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 400) { + System.err.println("Unable to create course, ownerId not specified.\n"); + } else { + throw e; + } } + return course; + } } // [END classroom_create_course] \ No newline at end of file diff --git a/classroom/snippets/src/main/java/GetCourse.java b/classroom/snippets/src/main/java/GetCourse.java index ff20a729..7955f1da 100644 --- a/classroom/snippets/src/main/java/GetCourse.java +++ b/classroom/snippets/src/main/java/GetCourse.java @@ -14,6 +14,7 @@ // [START classroom_get_course] + import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; @@ -29,43 +30,43 @@ /* Class to demonstrate the use of Classroom Get Course API */ public class GetCourse { - /** - * Retrieve a single course's metadata. - * - * @param courseId - Id of the course to return. - * @return a course - * @throws IOException - if credentials file not found. - */ - public static Course getCourse(String courseId) throws IOException { + /** + * Retrieve a single course's metadata. + * + * @param courseId - Id of the course to return. + * @return a course + * @throws IOException - if credentials file not found. + */ + 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); + 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(); + // Create the classroom API client + Classroom service = new Classroom.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Classroom samples") + .build(); - Course course = null; - try { - course = service.courses().get(courseId).execute(); - System.out.printf("Course '%s' found.\n", course.getName()); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 404) { - System.out.printf("Course with ID '%s' not found.\n", courseId); - } else { - throw e; - } - } - return course; + Course course = null; + try { + course = service.courses().get(courseId).execute(); + System.out.printf("Course '%s' found.\n", course.getName()); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("Course with ID '%s' not found.\n", courseId); + } else { + throw e; + } } + return course; + } } // [END classroom_get_course] \ No newline at end of file diff --git a/classroom/snippets/src/main/java/ListCourseAliases.java b/classroom/snippets/src/main/java/ListCourseAliases.java index 71101eb1..171f4fa6 100644 --- a/classroom/snippets/src/main/java/ListCourseAliases.java +++ b/classroom/snippets/src/main/java/ListCourseAliases.java @@ -14,6 +14,7 @@ // [START classroom_list_aliases] + import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; @@ -32,62 +33,62 @@ /* Class to demonstrate the use of Classroom List Alias API */ public class ListCourseAliases { - /** - * Retrieve the aliases for a course. - * - * @param courseId - id of the course. - * @return list of course aliases - * @throws IOException - if credentials file not found. - */ - public static List listCourseAliases(String courseId) - throws IOException { + /** + * Retrieve the aliases for a course. + * + * @param courseId - id of the course. + * @return list of course aliases + * @throws IOException - if credentials file not found. + */ + 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); + 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(); + // Create the classroom API client + Classroom service = new Classroom.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Classroom samples") + .build(); - String pageToken = null; - List courseAliases = new ArrayList<>(); + String pageToken = null; + List courseAliases = new ArrayList<>(); - try { - // List of aliases of specified course - do { - ListCourseAliasesResponse response = service.courses().aliases().list(courseId) - .setPageSize(100) - .setPageToken(pageToken) - .execute(); - courseAliases.addAll(response.getAliases()); - pageToken = response.getNextPageToken(); - } while (pageToken != null); + try { + // List of aliases of specified course + do { + ListCourseAliasesResponse response = service.courses().aliases().list(courseId) + .setPageSize(100) + .setPageToken(pageToken) + .execute(); + courseAliases.addAll(response.getAliases()); + pageToken = response.getNextPageToken(); + } while (pageToken != null); - if (courseAliases.isEmpty()) { - System.out.println("No aliases found."); - } else { - System.out.println("Aliases:"); - for (CourseAlias courseAlias : courseAliases) { - System.out.println(courseAlias.getAlias()); - } - } - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 404) { - System.err.println("Course does not exist.\n"); - } else { - throw e; - } + if (courseAliases.isEmpty()) { + System.out.println("No aliases found."); + } else { + System.out.println("Aliases:"); + for (CourseAlias courseAlias : courseAliases) { + System.out.println(courseAlias.getAlias()); } - return courseAliases; + } + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.err.println("Course does not exist.\n"); + } else { + throw e; + } } + return courseAliases; + } } // [END classroom_list_aliases] \ No newline at end of file diff --git a/classroom/snippets/src/main/java/ListCourses.java b/classroom/snippets/src/main/java/ListCourses.java index 65a2be80..5b7bd58f 100644 --- a/classroom/snippets/src/main/java/ListCourses.java +++ b/classroom/snippets/src/main/java/ListCourses.java @@ -14,6 +14,7 @@ // [START classroom_list_courses] + import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; @@ -31,54 +32,54 @@ /* Class to demonstrate the use of Classroom List Course API */ public class ListCourses { - /** - * Retrieves all courses with metadata - * - * @return list of courses with its metadata - * @throws IOException - if credentials file not found. - */ - public static List listCourses() throws IOException { + /** + * Retrieves all courses with metadata + * + * @return list of courses with its metadata + * @throws IOException - if credentials file not found. + */ + 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); + 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(); + // Create the classroom API client + Classroom service = new Classroom.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Classroom samples") + .build(); - String pageToken = null; - List courses = new ArrayList<>(); + String pageToken = null; + List courses = new ArrayList<>(); - try { - do { - ListCoursesResponse response = service.courses().list() - .setPageSize(100) - .setPageToken(pageToken) - .execute(); - courses.addAll(response.getCourses()); - pageToken = response.getNextPageToken(); - } while (pageToken != null); + try { + do { + ListCoursesResponse response = service.courses().list() + .setPageSize(100) + .setPageToken(pageToken) + .execute(); + courses.addAll(response.getCourses()); + pageToken = response.getNextPageToken(); + } while (pageToken != null); - if (courses.isEmpty()) { - System.out.println("No courses found."); - } else { - System.out.println("Courses:"); - for (Course course : courses) { - System.out.printf("%s (%s)\n", course.getName(), course.getId()); - } - } - } catch (NullPointerException ne) { - // TODO(developer) - handle error appropriately - System.err.println("No courses found.\n"); + if (courses.isEmpty()) { + System.out.println("No courses found."); + } else { + System.out.println("Courses:"); + for (Course course : courses) { + System.out.printf("%s (%s)\n", course.getName(), course.getId()); } - return courses; + } + } catch (NullPointerException ne) { + // TODO(developer) - handle error appropriately + System.err.println("No courses found.\n"); } + return courses; + } } // [END classroom_list_courses] \ No newline at end of file diff --git a/classroom/snippets/src/main/java/PatchCourse.java b/classroom/snippets/src/main/java/PatchCourse.java index fd0f8e5b..e8c5d31b 100644 --- a/classroom/snippets/src/main/java/PatchCourse.java +++ b/classroom/snippets/src/main/java/PatchCourse.java @@ -14,6 +14,7 @@ // [START classroom_patch_course] + import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; @@ -29,47 +30,47 @@ /* Class to demonstrate the use of Classroom Patch Course API */ public class PatchCourse { - /** - * 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. - */ - public static Course patchCourse(String courseId) throws IOException { + /** + * 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. + */ + 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); + 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(); - Course course = null; - try { - 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 - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 404) { - System.err.println("Course does not exist.\n"); - } else { - throw e; - } - } - return course; + // 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(); + System.out.printf("Course '%s' updated.\n", course.getName()); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.err.println("Course does not exist.\n"); + } else { + throw e; + } } + return course; + } } // [END classroom_patch_course] \ No newline at end of file diff --git a/classroom/snippets/src/main/java/UpdateCourse.java b/classroom/snippets/src/main/java/UpdateCourse.java index bdd577cf..9e0d63ed 100644 --- a/classroom/snippets/src/main/java/UpdateCourse.java +++ b/classroom/snippets/src/main/java/UpdateCourse.java @@ -14,6 +14,7 @@ // [START classroom_update_course] + import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; @@ -29,48 +30,48 @@ /* Class to demonstrate the use of Classroom Update Course API */ public class UpdateCourse { - /** - * Updates a course's metadata. - * - * @param courseId - Id of the course to update. - * @return updated course - * @throws IOException - if credentials file not found. - */ - public static Course updateCourse(String courseId) throws IOException { + /** + * Updates a course's metadata. + * + * @param courseId - Id of the course to update. + * @return updated course + * @throws IOException - if credentials file not found. + */ + 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); + 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(); + // Create the classroom API client + Classroom service = new Classroom.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Classroom samples") + .build(); - Course course = null; - try { - // Updating the section and room in a course - course = service.courses().get(courseId).execute(); - course.setSection("Period 3"); - course.setRoom("302"); - course = service.courses().update(courseId, course).execute(); - // Prints the updated course - System.out.printf("Course '%s' updated.\n", course.getName()); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 404) { - System.err.println("Course does not exist.\n"); - } else { - throw e; - } - } - return course; + Course course = null; + try { + // Updating the section and room in a course + course = service.courses().get(courseId).execute(); + course.setSection("Period 3"); + course.setRoom("302"); + course = service.courses().update(courseId, course).execute(); + // Prints the updated course + System.out.printf("Course '%s' updated.\n", course.getName()); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.err.println("Course does not exist.\n"); + } else { + throw e; + } } + return course; + } } // [END classroom_update_course] \ No newline at end of file diff --git a/classroom/snippets/src/test/java/BaseTest.java b/classroom/snippets/src/test/java/BaseTest.java index 4b69228f..c1e46717 100644 --- a/classroom/snippets/src/test/java/BaseTest.java +++ b/classroom/snippets/src/test/java/BaseTest.java @@ -29,57 +29,57 @@ import java.io.IOException; import java.util.UUID; - // Base class for integration tests. +// Base class for integration tests. public class BaseTest { - protected Classroom service; - protected Course testCourse; + protected Classroom service; + protected Course testCourse; - /** - * Creates a default authorization Classroom client service. - * - * @return an authorized Classroom client service - * @throws IOException - if credentials file not found. - */ - protected Classroom buildService() throws IOException { + /** + * Creates a default authorization Classroom client service. + * + * @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); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(ClassroomScopes.CLASSROOM_ROSTERS); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the classroom API client - Classroom service = new Classroom.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Classroom Snippets") - .build(); + // Create the classroom API client + Classroom service = new Classroom.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Classroom Snippets") + .build(); - return service; - } + return service; + } - @Before - public void setup() throws IOException{ - this.service = buildService(); - this.testCourse = CreateCourse.createCourse(); - createAlias(this.testCourse.getId()); - } + @Before + public void setup() throws IOException { + this.service = buildService(); + this.testCourse = CreateCourse.createCourse(); + createAlias(this.testCourse.getId()); + } - @After - public void tearDown() throws IOException{ - deleteCourse(this.testCourse.getId()); - this.testCourse = null; - } + @After + public void tearDown() throws IOException { + deleteCourse(this.testCourse.getId()); + this.testCourse = null; + } - public CourseAlias 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; - } + public CourseAlias 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; + } - public void deleteCourse(String courseId) throws IOException { - this.service.courses().delete(courseId).execute(); - } + public void deleteCourse(String courseId) throws IOException { + this.service.courses().delete(courseId).execute(); + } } diff --git a/classroom/snippets/src/test/java/CoursesTest.java b/classroom/snippets/src/test/java/CoursesTest.java index 858d4540..81b6de6e 100644 --- a/classroom/snippets/src/test/java/CoursesTest.java +++ b/classroom/snippets/src/test/java/CoursesTest.java @@ -34,109 +34,109 @@ * Tests for the courses snippets. */ public class CoursesTest extends BaseTest { - private Classroom service; - private Course testCourse; - private String otherUser = "erics@homeroomacademy.com"; - - public CoursesTest() throws IOException { - this.service = this.getService(); - } - - @Before - public void setUp() throws IOException { - this.testCourse = createTestCourse("me"); - } - - @After - public void tearDown() throws IOException { - deleteCourse(this.testCourse.getId()); - this.testCourse = null; - } - - @Test - public void testCreateCourse() throws IOException { - Course course = Courses.createCourse(this.service); - Assert.assertNotNull("Course not returned.", course); - deleteCourse(course.getId()); - } - - @Test - public void testGetCourse() throws IOException { - Course course = Courses.getCourse(this.service, this.testCourse.getId()); - Assert.assertNotNull("Course not returned.", course); - Assert.assertEquals("Wrong course returned.", this.testCourse.getId(), course.getId()); - } - - @Test - public void testListCourses() throws IOException { - List courses = Courses.listCourses(this.service); - Assert.assertTrue("No courses returned.", courses.size() > 0); - } - - @Test - public void testUpdateCourse() throws IOException { - Course course = Courses.updateCourse(this.service, this.testCourse.getId()); - Assert.assertNotNull("Course not returned.", course); - Assert.assertEquals("Wrong course returned.", this.testCourse.getId(), course.getId()); - } - - @Test - public void testPatchCourse() throws IOException { - Course course = Courses.patchCourse(this.service, this.testCourse.getId()); - Assert.assertNotNull("Course not returned.", course); - Assert.assertEquals("Wrong course returned.", this.testCourse.getId(), course.getId()); - } - - @Test - public void testCreateCourseAlias() throws IOException { - String alias = "p:" + UUID.randomUUID().toString(); - CourseAlias courseAlias = - Courses.createCourseAlias(this.service, this.testCourse.getId(), alias); - Assert.assertNotNull("Course alias not returned.", courseAlias); - Assert.assertEquals("Wrong course alias returned.", alias, courseAlias.getAlias()); - } - - @Test - public void testListCourseAliases() throws IOException { - List courseAliases = - Courses.listCourseAliases(this.service, this.testCourse.getId()); - Assert.assertTrue("Incorrect number of course aliases returned.", courseAliases.size() == 1); - } - - @Test - public void testAddTeacher() throws IOException { - Teacher teacher = Courses.addTeacher(this.service, this.testCourse.getId(), this.otherUser); - Assert.assertNotNull("Teacher not returned.", teacher); - Assert.assertEquals("Teacher added to wrong course.", this.testCourse.getId(), - teacher.getCourseId()); - } - - @Test - public void testEnrollAsStudent() throws IOException { - Course course = this.createTestCourse(this.otherUser); - Student student = - Courses.enrollAsStudent(this.service, course.getId(), course.getEnrollmentCode()); - this.deleteCourse(course.getId()); - Assert.assertNotNull("Student not returned.", student); - Assert.assertEquals("Student added to wrong course.", course.getId(), - student.getCourseId()); - } - - @Test - public void testBatchAddStudents() throws IOException { - List studentEmails = - Arrays.asList("erics@homeroomacademy.com", "zach@homeroomacademy.com"); - Courses.batchAddStudents(this.service, this.testCourse.getId(), studentEmails); - } - - private Course createTestCourse(String ownerId) throws IOException { - String alias = "p:" + UUID.randomUUID().toString(); - Course course = new Course().setId(alias).setName("Test Course").setSection("Section") - .setOwnerId(ownerId); - return this.service.courses().create(course).execute(); - } - - private void deleteCourse(String courseId) throws IOException { - this.service.courses().delete(courseId).execute(); - } + private Classroom service; + private Course testCourse; + private String otherUser = "erics@homeroomacademy.com"; + + public CoursesTest() throws IOException { + this.service = this.getService(); + } + + @Before + public void setUp() throws IOException { + this.testCourse = createTestCourse("me"); + } + + @After + public void tearDown() throws IOException { + deleteCourse(this.testCourse.getId()); + this.testCourse = null; + } + + @Test + public void testCreateCourse() throws IOException { + Course course = Courses.createCourse(this.service); + Assert.assertNotNull("Course not returned.", course); + deleteCourse(course.getId()); + } + + @Test + public void testGetCourse() throws IOException { + Course course = Courses.getCourse(this.service, this.testCourse.getId()); + Assert.assertNotNull("Course not returned.", course); + Assert.assertEquals("Wrong course returned.", this.testCourse.getId(), course.getId()); + } + + @Test + public void testListCourses() throws IOException { + List courses = Courses.listCourses(this.service); + Assert.assertTrue("No courses returned.", courses.size() > 0); + } + + @Test + public void testUpdateCourse() throws IOException { + Course course = Courses.updateCourse(this.service, this.testCourse.getId()); + Assert.assertNotNull("Course not returned.", course); + Assert.assertEquals("Wrong course returned.", this.testCourse.getId(), course.getId()); + } + + @Test + public void testPatchCourse() throws IOException { + Course course = Courses.patchCourse(this.service, this.testCourse.getId()); + Assert.assertNotNull("Course not returned.", course); + Assert.assertEquals("Wrong course returned.", this.testCourse.getId(), course.getId()); + } + + @Test + public void testCreateCourseAlias() throws IOException { + String alias = "p:" + UUID.randomUUID().toString(); + CourseAlias courseAlias = + Courses.createCourseAlias(this.service, this.testCourse.getId(), alias); + Assert.assertNotNull("Course alias not returned.", courseAlias); + Assert.assertEquals("Wrong course alias returned.", alias, courseAlias.getAlias()); + } + + @Test + public void testListCourseAliases() throws IOException { + List courseAliases = + Courses.listCourseAliases(this.service, this.testCourse.getId()); + Assert.assertTrue("Incorrect number of course aliases returned.", courseAliases.size() == 1); + } + + @Test + public void testAddTeacher() throws IOException { + Teacher teacher = Courses.addTeacher(this.service, this.testCourse.getId(), this.otherUser); + Assert.assertNotNull("Teacher not returned.", teacher); + Assert.assertEquals("Teacher added to wrong course.", this.testCourse.getId(), + teacher.getCourseId()); + } + + @Test + public void testEnrollAsStudent() throws IOException { + Course course = this.createTestCourse(this.otherUser); + Student student = + Courses.enrollAsStudent(this.service, course.getId(), course.getEnrollmentCode()); + this.deleteCourse(course.getId()); + Assert.assertNotNull("Student not returned.", student); + Assert.assertEquals("Student added to wrong course.", course.getId(), + student.getCourseId()); + } + + @Test + public void testBatchAddStudents() throws IOException { + List studentEmails = + Arrays.asList("erics@homeroomacademy.com", "zach@homeroomacademy.com"); + Courses.batchAddStudents(this.service, this.testCourse.getId(), studentEmails); + } + + private Course createTestCourse(String ownerId) throws IOException { + String alias = "p:" + UUID.randomUUID().toString(); + Course course = new Course().setId(alias).setName("Test Course").setSection("Section") + .setOwnerId(ownerId); + return this.service.courses().create(course).execute(); + } + + private void deleteCourse(String courseId) throws IOException { + this.service.courses().delete(courseId).execute(); + } } diff --git a/classroom/snippets/src/test/java/TestAddStudent.java b/classroom/snippets/src/test/java/TestAddStudent.java index 8d6a9bb9..f023989a 100644 --- a/classroom/snippets/src/test/java/TestAddStudent.java +++ b/classroom/snippets/src/test/java/TestAddStudent.java @@ -19,15 +19,15 @@ import java.io.IOException; // Unit test class for Add Student classroom snippet -public class TestAddStudent extends BaseTest{ +public class TestAddStudent extends BaseTest { - @Test - public void testAddStudent() throws IOException { - Course course = CreateCourse.createCourse(); - Student student = AddStudent.addStudent(course.getId(), course.getEnrollmentCode()); - deleteCourse(course.getId()); - Assert.assertNotNull("Student not returned.", student); - Assert.assertEquals("Student added to wrong course.", course.getId(), - student.getCourseId()); - } + @Test + public void testAddStudent() throws IOException { + Course course = CreateCourse.createCourse(); + Student student = AddStudent.addStudent(course.getId(), course.getEnrollmentCode()); + deleteCourse(course.getId()); + Assert.assertNotNull("Student not returned.", student); + Assert.assertEquals("Student added to wrong course.", course.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 f66ce0bd..f2846ddf 100644 --- a/classroom/snippets/src/test/java/TestAddTeacher.java +++ b/classroom/snippets/src/test/java/TestAddTeacher.java @@ -18,14 +18,14 @@ import java.io.IOException; // Unit test class for Add Teacher classroom snippet -public class TestAddTeacher extends BaseTest{ - private String otherUser = "gduser1@workspacesamples.dev"; +public class TestAddTeacher extends BaseTest { + private String otherUser = "gduser1@workspacesamples.dev"; - @Test - public void testAddTeacher() throws IOException { - Teacher teacher = AddTeacher.addTeacher(testCourse.getId(), this.otherUser); - Assert.assertNotNull("Teacher not returned.", teacher); - Assert.assertEquals("Teacher added to wrong course.", testCourse.getId(), - teacher.getCourseId()); - } + @Test + public void testAddTeacher() throws IOException { + Teacher teacher = AddTeacher.addTeacher(testCourse.getId(), this.otherUser); + Assert.assertNotNull("Teacher not returned.", teacher); + 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 c21eb3f2..04ee930e 100644 --- a/classroom/snippets/src/test/java/TestBatchAddStudents.java +++ b/classroom/snippets/src/test/java/TestBatchAddStudents.java @@ -20,10 +20,10 @@ // 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"); - BatchAddStudents.batchAddStudents(testCourse.getId(), studentEmails); - } + @Test + public void testBatchAddStudents() throws IOException { + List studentEmails = Arrays.asList("gduser2@workpsacesamples.dev", + "gduser3@workpsacesamples.dev"); + 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 caa70281..381f2c2c 100644 --- a/classroom/snippets/src/test/java/TestCreateCourse.java +++ b/classroom/snippets/src/test/java/TestCreateCourse.java @@ -18,12 +18,12 @@ import java.io.IOException; // Unit test class for Create Course classroom snippet -public class TestCreateCourse extends BaseTest{ +public class TestCreateCourse extends BaseTest { - @Test - public void testCreateCourse() throws IOException{ - Course course = CreateCourse.createCourse(); - Assert.assertNotNull("Course not returned.", course); - deleteCourse(course.getId()); - } + @Test + public void testCreateCourse() throws IOException { + Course course = CreateCourse.createCourse(); + Assert.assertNotNull("Course not returned.", course); + deleteCourse(course.getId()); + } } diff --git a/classroom/snippets/src/test/java/TestGetCourse.java b/classroom/snippets/src/test/java/TestGetCourse.java index a17cf197..c43059f7 100644 --- a/classroom/snippets/src/test/java/TestGetCourse.java +++ b/classroom/snippets/src/test/java/TestGetCourse.java @@ -18,12 +18,12 @@ import java.io.IOException; // Unit test class for Get Course classroom snippet -public class TestGetCourse extends BaseTest{ +public class TestGetCourse extends BaseTest { - @Test - public void testGetCourse() throws IOException { - Course course = GetCourse.getCourse(testCourse.getId()); - Assert.assertNotNull("Course not returned.", course); - Assert.assertEquals("Wrong course returned.", testCourse.getId(), course.getId()); - } + @Test + public void testGetCourse() throws IOException { + 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/TestListCourseAliases.java b/classroom/snippets/src/test/java/TestListCourseAliases.java index b7396361..f18c1cce 100644 --- a/classroom/snippets/src/test/java/TestListCourseAliases.java +++ b/classroom/snippets/src/test/java/TestListCourseAliases.java @@ -19,11 +19,11 @@ import java.util.List; // Unit test class for List Course Aliases classroom snippet -public class TestListCourseAliases extends BaseTest{ +public class TestListCourseAliases extends BaseTest { - @Test - public void testListCourseAliases() throws IOException { - List courseAliases = ListCourseAliases.listCourseAliases(testCourse.getId()); - Assert.assertTrue("Incorrect number of course aliases returned.", courseAliases.size() == 1); - } + @Test + public void testListCourseAliases() throws IOException { + 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 55a3a1fc..fe254b76 100644 --- a/classroom/snippets/src/test/java/TestListCourses.java +++ b/classroom/snippets/src/test/java/TestListCourses.java @@ -21,9 +21,9 @@ // Unit test class for List Course classroom snippet public class TestListCourses { - @Test - public void testListCourses() throws IOException { - List courses = ListCourses.listCourses(); - Assert.assertTrue("No courses returned.", courses.size() > 0); - } + @Test + public void testListCourses() throws IOException { + List courses = ListCourses.listCourses(); + Assert.assertTrue("No courses returned.", courses.size() > 0); + } } diff --git a/classroom/snippets/src/test/java/TestPatchCourse.java b/classroom/snippets/src/test/java/TestPatchCourse.java index 3cf341c8..51e05a43 100644 --- a/classroom/snippets/src/test/java/TestPatchCourse.java +++ b/classroom/snippets/src/test/java/TestPatchCourse.java @@ -18,12 +18,12 @@ import java.io.IOException; // Unit test class for Patch Course classroom snippet -public class TestPatchCourse extends BaseTest{ +public class TestPatchCourse extends BaseTest { - @Test - public void testPatchCourse() throws IOException { - Course course = PatchCourse.patchCourse(testCourse.getId()); - Assert.assertNotNull("Course not returned.", course); - Assert.assertEquals("Wrong course returned.", testCourse.getId(), course.getId()); - } + @Test + public void testPatchCourse() throws IOException { + 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 3926443e..f5e0080d 100644 --- a/classroom/snippets/src/test/java/TestUpdateCourse.java +++ b/classroom/snippets/src/test/java/TestUpdateCourse.java @@ -18,12 +18,12 @@ import java.io.IOException; // Unit test class for Update Course classroom snippet -public class TestUpdateCourse extends BaseTest{ +public class TestUpdateCourse extends BaseTest { - @Test - public void testUpdateCourse() throws IOException { - Course course = UpdateCourse.updateCourse(testCourse.getId()); - Assert.assertNotNull("Course not returned.", course); - Assert.assertEquals("Wrong course returned.", testCourse.getId(), course.getId()); - } + @Test + public void testUpdateCourse() throws IOException { + Course course = UpdateCourse.updateCourse(testCourse.getId()); + Assert.assertNotNull("Course not returned.", course); + Assert.assertEquals("Wrong course returned.", testCourse.getId(), course.getId()); + } } diff --git a/docs/outputJSON/src/main/java/OutputJSON.java b/docs/outputJSON/src/main/java/OutputJSON.java index 84e41f4e..e7ad0715 100644 --- a/docs/outputJSON/src/main/java/OutputJSON.java +++ b/docs/outputJSON/src/main/java/OutputJSON.java @@ -35,59 +35,60 @@ import java.util.List; // [START docs_output_json] + /** * OutputJSON prints the JSON representation of a Google Doc. */ public class OutputJSON { - private static final String APPLICATION_NAME = "Google Docs API Document Contents"; - private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); - private static final String TOKENS_DIRECTORY_PATH = "tokens"; - private static final String DOCUMENT_ID = "YOUR_DOCUMENT_ID"; + private static final String APPLICATION_NAME = "Google Docs API Document Contents"; + private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); + private static final String TOKENS_DIRECTORY_PATH = "tokens"; + private static final String DOCUMENT_ID = "YOUR_DOCUMENT_ID"; - /** - * Global instance of the scopes required by this sample. If modifying these scopes, delete - * your previously saved tokens/ folder. - */ - private static final List SCOPES = - Collections.singletonList(DocsScopes.DOCUMENTS_READONLY); + /** + * Global instance of the scopes required by this sample. If modifying these scopes, delete + * your previously saved tokens/ folder. + */ + private static final List SCOPES = + Collections.singletonList(DocsScopes.DOCUMENTS_READONLY); - private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; + private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; - /** - * Creates an authorized Credential object. - * - * @param HTTP_TRANSPORT The network HTTP Transport. - * @return An authorized Credential object. - * @throws IOException If the credentials.json file cannot be found. - */ - private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) - throws IOException { - // Load client secrets. - InputStream in = OutputJSON.class.getResourceAsStream(CREDENTIALS_FILE_PATH); - GoogleClientSecrets credentials = - GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in)); + /** + * Creates an authorized Credential object. + * + * @param HTTP_TRANSPORT The network HTTP Transport. + * @return An authorized Credential object. + * @throws IOException If the credentials.json file cannot be found. + */ + private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) + throws IOException { + // Load client secrets. + InputStream in = OutputJSON.class.getResourceAsStream(CREDENTIALS_FILE_PATH); + GoogleClientSecrets credentials = + GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in)); - // Build flow and trigger user authorization request. - GoogleAuthorizationCodeFlow flow = - new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, credentials, 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"); - } + // Build flow and trigger user authorization request. + GoogleAuthorizationCodeFlow flow = + new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, credentials, 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"); + } - public static void main(String... args) throws IOException, GeneralSecurityException { - // Build a new authorized API client service. - final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); - Docs docsService = - new Docs.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) - .setApplicationName(APPLICATION_NAME) - .build(); + public static void main(String... args) throws IOException, GeneralSecurityException { + // Build a new authorized API client service. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Docs docsService = + new Docs.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) + .setApplicationName(APPLICATION_NAME) + .build(); - Document response = docsService.documents().get(DOCUMENT_ID).execute(); - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - System.out.println(gson.toJson(response)); - } + Document response = docsService.documents().get(DOCUMENT_ID).execute(); + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + System.out.println(gson.toJson(response)); + } } // [END docs_output_json] diff --git a/docs/quickstart/src/main/java/DocsQuickstart.java b/docs/quickstart/src/main/java/DocsQuickstart.java index f8321a67..431c8394 100644 --- a/docs/quickstart/src/main/java/DocsQuickstart.java +++ b/docs/quickstart/src/main/java/DocsQuickstart.java @@ -13,6 +13,7 @@ // limitations under the License. // [START docs_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; @@ -37,60 +38,70 @@ /* class to demonstarte use of Docs get documents API */ public class DocsQuickstart { - /** Application name. */ - private static final String APPLICATION_NAME = "Google Docs API Java Quickstart"; - /** Global instance of the JSON factory. */ - private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); - /** Directory to store authorization tokens for this application. */ - private static final String TOKENS_DIRECTORY_PATH = "tokens"; - private static final String DOCUMENT_ID = "195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE"; - - /** - * 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(DocsScopes.DOCUMENTS_READONLY); - private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; + /** + * Application name. + */ + private static final String APPLICATION_NAME = "Google Docs API Java Quickstart"; + /** + * Global instance of the JSON factory. + */ + private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); + /** + * Directory to store authorization tokens for this application. + */ + private static final String TOKENS_DIRECTORY_PATH = "tokens"; + private static final String DOCUMENT_ID = "195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE"; - /** - * Creates an authorized Credential object. - * @param HTTP_TRANSPORT The network HTTP Transport. - * @return An authorized Credential object. - * @throws IOException If the credentials.json file cannot be found. - */ - private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException { - // Load client secrets. - InputStream in = DocsQuickstart.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)); + /** + * 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(DocsScopes.DOCUMENTS_READONLY); + private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; - // 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(); - Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user"); - //returns an authorized Credential object. - return credential; + /** + * Creates an authorized Credential object. + * + * @param HTTP_TRANSPORT The network HTTP Transport. + * @return An authorized Credential object. + * @throws IOException If the credentials.json file cannot be found. + */ + private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) + throws IOException { + // Load client secrets. + InputStream in = DocsQuickstart.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)); - public static void main(String... args) throws IOException, GeneralSecurityException { - // Build a new authorized API client service. - final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); - Docs service = new Docs.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) - .setApplicationName(APPLICATION_NAME) - .build(); + // 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(); + Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user"); + //returns an authorized Credential object. + return credential; + } - // Prints the title of the requested doc: - // https://docs.google.com/document/d/195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE/edit - Document response = service.documents().get(DOCUMENT_ID).execute(); - String title = response.getTitle(); + public static void main(String... args) throws IOException, GeneralSecurityException { + // Build a new authorized API client service. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Docs service = new Docs.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) + .setApplicationName(APPLICATION_NAME) + .build(); - System.out.printf("The title of the doc is: %s\n", title); - } + // Prints the title of the requested doc: + // https://docs.google.com/document/d/195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE/edit + Document response = service.documents().get(DOCUMENT_ID).execute(); + String title = response.getTitle(); + + System.out.printf("The title of the doc is: %s\n", title); + } } // [END docs_quickstart] diff --git a/drive/activity-v2/quickstart/src/main/java/DriveActivityQuickstart.java b/drive/activity-v2/quickstart/src/main/java/DriveActivityQuickstart.java index db0b7c36..6e2c9b16 100644 --- a/drive/activity-v2/quickstart/src/main/java/DriveActivityQuickstart.java +++ b/drive/activity-v2/quickstart/src/main/java/DriveActivityQuickstart.java @@ -13,6 +13,7 @@ // limitations under the License. // [START drive_activity_v2_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; @@ -36,182 +37,205 @@ import java.util.stream.Collectors; public class DriveActivityQuickstart { - /** Application name. */ - private static final String APPLICATION_NAME = "Drive Activity API Java Quickstart"; - - /** Directory to store authorization tokens for this application. */ - private static final java.io.File DATA_STORE_DIR = new java.io.File("tokens"); - - /** Global instance of the {@link FileDataStoreFactory}. */ - private static FileDataStoreFactory DATA_STORE_FACTORY; - - /** Global instance of the JSON factory. */ - private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); - - /** Global instance of the HTTP transport. */ - private static HttpTransport HTTP_TRANSPORT; - - /** - * Global instance of the scopes required by this quickstart. - * - *

If modifying these scopes, delete your previously saved tokens/ folder. - */ - private static final List SCOPES = - Arrays.asList(DriveActivityScopes.DRIVE_ACTIVITY_READONLY); - private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; - - static { - try { - HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); - DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR); - } catch (Throwable t) { - t.printStackTrace(); - System.exit(1); - } - } - - /** - * Creates an authorized Credential object. - * - * @return an authorized Credential object. - * @throws IOException - */ - public static Credential authorize() throws IOException { - // Load client secrets. - InputStream in = DriveActivityQuickstart.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(DATA_STORE_FACTORY) - .setAccessType("offline") - .build(); - Credential credential = - new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()) - .authorize("user"); - System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath()); - return credential; + /** + * Application name. + */ + private static final String APPLICATION_NAME = "Drive Activity API Java Quickstart"; + + /** + * Directory to store authorization tokens for this application. + */ + private static final java.io.File DATA_STORE_DIR = new java.io.File("tokens"); + /** + * Global instance of the JSON factory. + */ + private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); + /** + * Global instance of the scopes required by this quickstart. + * + *

If modifying these scopes, delete your previously saved tokens/ folder. + */ + private static final List SCOPES = + Arrays.asList(DriveActivityScopes.DRIVE_ACTIVITY_READONLY); + private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; + /** + * Global instance of the {@link FileDataStoreFactory}. + */ + private static FileDataStoreFactory DATA_STORE_FACTORY; + /** + * Global instance of the HTTP transport. + */ + private static HttpTransport HTTP_TRANSPORT; + + static { + try { + HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR); + } catch (Throwable t) { + t.printStackTrace(); + System.exit(1); } - - /** - * Build and return an authorized Drive Activity client service. - * - * @return an authorized DriveActivity client service - * @throws IOException - */ - public static com.google.api.services.driveactivity.v2.DriveActivity getDriveActivityService() - throws IOException { - Credential credential = authorize(); - com.google.api.services.driveactivity.v2.DriveActivity service = new com.google.api.services.driveactivity.v2.DriveActivity.Builder( - HTTP_TRANSPORT, JSON_FACTORY, credential) - .setApplicationName(APPLICATION_NAME) - .build(); - return service; + } + + /** + * Creates an authorized Credential object. + * + * @return an authorized Credential object. + * @throws IOException + */ + public static Credential authorize() throws IOException { + // Load client secrets. + InputStream in = DriveActivityQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH); + if (in == null) { + throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH); } - - public static void main(String[] args) throws IOException { - // Build a new authorized API client service. - com.google.api.services.driveactivity.v2.DriveActivity service = getDriveActivityService(); - - // Print the recent activity in your Google Drive. - QueryDriveActivityResponse result = - service.activity().query(new QueryDriveActivityRequest().setPageSize(10)).execute(); - List activities = result.getActivities(); - if (activities == null || activities.size() == 0) { - System.out.println("No activity."); - } else { - System.out.println("Recent activity:"); - for (DriveActivity activity : activities) { - String time = getTimeInfo(activity); - String action = getActionInfo(activity.getPrimaryActionDetail()); - List actors = - activity.getActors().stream() - .map(DriveActivityQuickstart::getActorInfo) - .collect(Collectors.toList()); - List targets = - activity.getTargets().stream() - .map(DriveActivityQuickstart::getTargetInfo) - .collect(Collectors.toList()); - System.out.printf( - "%s: %s, %s, %s\n", time, truncated(actors), action, truncated(targets)); - } - } - } - - /** Returns a string representation of the first elements in a list. */ - private static String truncated(List array) { - return truncatedTo(array, 2); + 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(DATA_STORE_FACTORY) + .setAccessType("offline") + .build(); + Credential credential = + new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()) + .authorize("user"); + System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath()); + return credential; + } + + /** + * Build and return an authorized Drive Activity client service. + * + * @return an authorized DriveActivity client service + * @throws IOException + */ + public static com.google.api.services.driveactivity.v2.DriveActivity getDriveActivityService() + throws IOException { + Credential credential = authorize(); + com.google.api.services.driveactivity.v2.DriveActivity service = + new com.google.api.services.driveactivity.v2.DriveActivity.Builder( + HTTP_TRANSPORT, JSON_FACTORY, credential) + .setApplicationName(APPLICATION_NAME) + .build(); + return service; + } + + public static void main(String[] args) throws IOException { + // Build a new authorized API client service. + com.google.api.services.driveactivity.v2.DriveActivity service = getDriveActivityService(); + + // Print the recent activity in your Google Drive. + QueryDriveActivityResponse result = + service.activity().query(new QueryDriveActivityRequest().setPageSize(10)).execute(); + List activities = result.getActivities(); + if (activities == null || activities.size() == 0) { + System.out.println("No activity."); + } else { + System.out.println("Recent activity:"); + for (DriveActivity activity : activities) { + String time = getTimeInfo(activity); + String action = getActionInfo(activity.getPrimaryActionDetail()); + List actors = + activity.getActors().stream() + .map(DriveActivityQuickstart::getActorInfo) + .collect(Collectors.toList()); + List targets = + activity.getTargets().stream() + .map(DriveActivityQuickstart::getTargetInfo) + .collect(Collectors.toList()); + System.out.printf( + "%s: %s, %s, %s\n", time, truncated(actors), action, truncated(targets)); + } } - - /** Returns a string representation of the first elements in a list. */ - private static String truncatedTo(List array, int limit) { - String contents = array.stream().limit(limit).collect(Collectors.joining(", ")); - String more = array.size() > limit ? ", ..." : ""; - return "[" + contents + more + "]"; + } + + /** + * Returns a string representation of the first elements in a list. + */ + private static String truncated(List array) { + return truncatedTo(array, 2); + } + + /** + * Returns a string representation of the first elements in a list. + */ + private static String truncatedTo(List array, int limit) { + String contents = array.stream().limit(limit).collect(Collectors.joining(", ")); + String more = array.size() > limit ? ", ..." : ""; + return "[" + contents + more + "]"; + } + + /** + * Returns the name of a set property in an object, or else "unknown". + */ + private static String getOneOf(AbstractMap obj) { + Iterator iterator = obj.keySet().iterator(); + return iterator.hasNext() ? iterator.next() : "unknown"; + } + + /** + * Returns a time associated with an activity. + */ + private static String getTimeInfo(DriveActivity activity) { + if (activity.getTimestamp() != null) { + return activity.getTimestamp(); } - - /** Returns the name of a set property in an object, or else "unknown". */ - private static String getOneOf(AbstractMap obj) { - Iterator iterator = obj.keySet().iterator(); - return iterator.hasNext() ? iterator.next() : "unknown"; + if (activity.getTimeRange() != null) { + return activity.getTimeRange().getEndTime(); } - - /** Returns a time associated with an activity. */ - private static String getTimeInfo(DriveActivity activity) { - if (activity.getTimestamp() != null) { - return activity.getTimestamp(); - } - if (activity.getTimeRange() != null) { - return activity.getTimeRange().getEndTime(); - } - return "unknown"; + return "unknown"; + } + + /** + * Returns the type of action. + */ + private static String getActionInfo(ActionDetail actionDetail) { + return getOneOf(actionDetail); + } + + /** + * Returns user information, or the type of user if not a known user. + */ + private static String getUserInfo(User user) { + if (user.getKnownUser() != null) { + KnownUser knownUser = user.getKnownUser(); + Boolean isMe = knownUser.getIsCurrentUser(); + return (isMe != null && isMe) ? "people/me" : knownUser.getPersonName(); } - - /** Returns the type of action. */ - private static String getActionInfo(ActionDetail actionDetail) { - return getOneOf(actionDetail); + return getOneOf(user); + } + + /** + * Returns actor information, or the type of actor if not a user. + */ + private static String getActorInfo(Actor actor) { + if (actor.getUser() != null) { + return getUserInfo(actor.getUser()); } - - /** Returns user information, or the type of user if not a known user. */ - private static String getUserInfo(User user) { - if (user.getKnownUser() != null) { - KnownUser knownUser = user.getKnownUser(); - Boolean isMe = knownUser.getIsCurrentUser(); - return (isMe != null && isMe) ? "people/me" : knownUser.getPersonName(); - } - return getOneOf(user); + return getOneOf(actor); + } + + /** + * Returns the type of a target and an associated title. + */ + private static String getTargetInfo(Target target) { + if (target.getDriveItem() != null) { + return "driveItem:\"" + target.getDriveItem().getTitle() + "\""; } - - /** Returns actor information, or the type of actor if not a user. */ - private static String getActorInfo(Actor actor) { - if (actor.getUser() != null) { - return getUserInfo(actor.getUser()); - } - return getOneOf(actor); + if (target.getDrive() != null) { + return "drive:\"" + target.getDrive().getTitle() + "\""; } - - /** Returns the type of a target and an associated title. */ - private static String getTargetInfo(Target target) { - if (target.getDriveItem() != null) { - return "driveItem:\"" + target.getDriveItem().getTitle() + "\""; - } - if (target.getDrive() != null) { - return "drive:\"" + target.getDrive().getTitle() + "\""; - } - if (target.getFileComment() != null) { - DriveItem parent = target.getFileComment().getParent(); - if (parent != null) { - return "fileComment:\"" + parent.getTitle() + "\""; - } - return "fileComment:unknown"; - } - return getOneOf(target); + if (target.getFileComment() != null) { + DriveItem parent = target.getFileComment().getParent(); + if (parent != null) { + return "fileComment:\"" + parent.getTitle() + "\""; + } + return "fileComment:unknown"; } + return getOneOf(target); + } } // [END drive_activity_v2_quickstart] diff --git a/drive/activity/quickstart/src/main/java/DriveActivityQuickstart.java b/drive/activity/quickstart/src/main/java/DriveActivityQuickstart.java index c28cdd13..e72a2c24 100644 --- a/drive/activity/quickstart/src/main/java/DriveActivityQuickstart.java +++ b/drive/activity/quickstart/src/main/java/DriveActivityQuickstart.java @@ -13,6 +13,7 @@ // limitations under the License. // [START drive_activity_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; @@ -20,14 +21,12 @@ import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; -import com.google.api.client.json.gson.GsonFactory; 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.services.appsactivity.Appsactivity; import com.google.api.services.appsactivity.AppsactivityScopes; import com.google.api.services.appsactivity.model.*; -import com.google.api.services.appsactivity.Appsactivity; - import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; @@ -37,116 +36,125 @@ /* class to demonstarte use of Drive Activity list API */ public class DriveActivityQuickstart { - /** Application name. */ - private static final String APPLICATION_NAME = - "Drive Activity API Java Quickstart"; - - /** Directory to store authorization tokens for this application. */ - private static final java.io.File DATA_STORE_DIR = new java.io.File("tokens"); + /** + * Application name. + */ + private static final String APPLICATION_NAME = + "Drive Activity API Java Quickstart"; - /** Global instance of the {@link FileDataStoreFactory}. */ - private static FileDataStoreFactory DATA_STORE_FACTORY; + /** + * Directory to store authorization tokens for this application. + */ + private static final java.io.File DATA_STORE_DIR = new java.io.File("tokens"); + /** + * Global instance of the JSON factory. + */ + private static final JsonFactory JSON_FACTORY = + GsonFactory.getDefaultInstance(); + /** + * Global instance of the scopes required by this quickstart. + * + *

If modifying these scopes, delete your previously saved tokens/ folder. + */ + private static final List SCOPES = Arrays.asList(AppsactivityScopes.ACTIVITY); + private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; + /** + * Global instance of the {@link FileDataStoreFactory}. + */ + private static FileDataStoreFactory DATA_STORE_FACTORY; + /** + * Global instance of the HTTP transport. + */ + private static HttpTransport HTTP_TRANSPORT; - /** Global instance of the JSON factory. */ - private static final JsonFactory JSON_FACTORY = - GsonFactory.getDefaultInstance(); - - /** Global instance of the HTTP transport. */ - private static HttpTransport HTTP_TRANSPORT; - - /** Global instance of the scopes required by this quickstart. - * - *

If modifying these scopes, delete your previously saved tokens/ folder. - */ - private static final List SCOPES = Arrays.asList(AppsactivityScopes.ACTIVITY); - private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; - - static { - try { - HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); - DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR); - } catch (Throwable t) { - t.printStackTrace(); - System.exit(1); - } + static { + try { + HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR); + } catch (Throwable t) { + t.printStackTrace(); + System.exit(1); } + } - /** - * Creates an authorized Credential object. - * @return an authorized Credential object. - * @throws IOException - */ - public static Credential authorize() throws IOException { - // Load client secrets. - InputStream in = - DriveActivityQuickstart.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(DATA_STORE_FACTORY) - .setAccessType("offline") - .build(); - Credential credential = new AuthorizationCodeInstalledApp( - flow, new LocalServerReceiver()).authorize("user"); - System.out.println( - "Credentials saved to " + DATA_STORE_DIR.getAbsolutePath()); - //returns an authorized Credential object. - return credential; + /** + * Creates an authorized Credential object. + * + * @return an authorized Credential object. + * @throws IOException + */ + public static Credential authorize() throws IOException { + // Load client secrets. + InputStream in = + DriveActivityQuickstart.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 and return an authorized Apps Activity client service. - * @return an authorized Appsactivity client service - * @throws IOException - */ - public static Appsactivity getAppsactivityService() throws IOException { - Credential credential = authorize(); - Appsactivity service = new Appsactivity.Builder( - HTTP_TRANSPORT, JSON_FACTORY, credential) - .setApplicationName(APPLICATION_NAME) - .build(); - return service; - } + // Build flow and trigger user authorization request. + GoogleAuthorizationCodeFlow flow = + new GoogleAuthorizationCodeFlow.Builder( + HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES) + .setDataStoreFactory(DATA_STORE_FACTORY) + .setAccessType("offline") + .build(); + Credential credential = new AuthorizationCodeInstalledApp( + flow, new LocalServerReceiver()).authorize("user"); + System.out.println( + "Credentials saved to " + DATA_STORE_DIR.getAbsolutePath()); + //returns an authorized Credential object. + return credential; + } + + /** + * Build and return an authorized Apps Activity client service. + * + * @return an authorized Appsactivity client service + * @throws IOException + */ + public static Appsactivity getAppsactivityService() throws IOException { + Credential credential = authorize(); + Appsactivity service = new Appsactivity.Builder( + HTTP_TRANSPORT, JSON_FACTORY, credential) + .setApplicationName(APPLICATION_NAME) + .build(); + return service; + } - public static void main(String[] args) throws IOException { - // Build a new authorized API client service. - Appsactivity service = getAppsactivityService(); + public static void main(String[] args) throws IOException { + // Build a new authorized API client service. + Appsactivity service = getAppsactivityService(); - // Print the recent activity in your Google Drive. - ListActivitiesResponse result = service.activities().list() - .setSource("drive.google.com") - .setDriveAncestorId("root") - .setPageSize(10) - .execute(); - List activities = result.getActivities(); - if (activities == null || activities.size() == 0) { - System.out.println("No activity."); - } else { - System.out.println("Recent activity:"); - for (Activity activity : activities) { - Event event = activity.getCombinedEvent(); - User user = event.getUser(); - Target target = event.getTarget(); - if (user == null || target == null ) { - continue; - } - String date = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") - .format(new java.util.Date(event.getEventTimeMillis().longValue())); - System.out.printf("%s: %s, %s, %s (%s)\n", - date, - user.getName(), - event.getPrimaryEventType(), - target.getName(), - target.getMimeType()); - } + // Print the recent activity in your Google Drive. + ListActivitiesResponse result = service.activities().list() + .setSource("drive.google.com") + .setDriveAncestorId("root") + .setPageSize(10) + .execute(); + List activities = result.getActivities(); + if (activities == null || activities.size() == 0) { + System.out.println("No activity."); + } else { + System.out.println("Recent activity:"); + for (Activity activity : activities) { + Event event = activity.getCombinedEvent(); + User user = event.getUser(); + Target target = event.getTarget(); + if (user == null || target == null) { + continue; } + String date = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") + .format(new java.util.Date(event.getEventTimeMillis().longValue())); + System.out.printf("%s: %s, %s, %s (%s)\n", + date, + user.getName(), + event.getPrimaryEventType(), + target.getName(), + target.getMimeType()); + } } + } } // [END drive_activity_quickstart] diff --git a/drive/quickstart/src/main/java/DriveQuickstart.java b/drive/quickstart/src/main/java/DriveQuickstart.java index b9df6ab6..c88f9063 100644 --- a/drive/quickstart/src/main/java/DriveQuickstart.java +++ b/drive/quickstart/src/main/java/DriveQuickstart.java @@ -13,6 +13,7 @@ // limitations under the License. // [START drive_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; @@ -27,7 +28,6 @@ import com.google.api.services.drive.DriveScopes; import com.google.api.services.drive.model.File; import com.google.api.services.drive.model.FileList; - import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; @@ -38,67 +38,77 @@ /* class to demonstarte use of Drive files list API */ public class DriveQuickstart { - /** Application name. */ - private static final String APPLICATION_NAME = "Google Drive API Java Quickstart"; - /** Global instance of the JSON factory. */ - private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); - /** Directory to store authorization tokens for this application. */ - private static final String TOKENS_DIRECTORY_PATH = "tokens"; + /** + * Application name. + */ + private static final String APPLICATION_NAME = "Google Drive API Java Quickstart"; + /** + * Global instance of the JSON factory. + */ + private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); + /** + * 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(DriveScopes.DRIVE_METADATA_READONLY); - private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; + /** + * 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(DriveScopes.DRIVE_METADATA_READONLY); + private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; - /** - * Creates an authorized Credential object. - * @param HTTP_TRANSPORT The network HTTP Transport. - * @return An authorized Credential object. - * @throws IOException If the credentials.json file cannot be found. - */ - private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException { - // Load client secrets. - InputStream in = DriveQuickstart.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(); - Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user"); - //returns an authorized Credential object. - return credential; + /** + * Creates an authorized Credential object. + * + * @param HTTP_TRANSPORT The network HTTP Transport. + * @return An authorized Credential object. + * @throws IOException If the credentials.json file cannot be found. + */ + private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) + throws IOException { + // Load client secrets. + InputStream in = DriveQuickstart.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(); + Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user"); + //returns an authorized Credential object. + return credential; + } - public static void main(String... args) throws IOException, GeneralSecurityException { - // Build a new authorized API client service. - final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); - Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) - .setApplicationName(APPLICATION_NAME) - .build(); + public static void main(String... args) throws IOException, GeneralSecurityException { + // Build a new authorized API client service. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) + .setApplicationName(APPLICATION_NAME) + .build(); - // Print the names and IDs for up to 10 files. - FileList result = service.files().list() - .setPageSize(10) - .setFields("nextPageToken, files(id, name)") - .execute(); - List files = result.getFiles(); - if (files == null || files.isEmpty()) { - System.out.println("No files found."); - } else { - System.out.println("Files:"); - for (File file : files) { - System.out.printf("%s (%s)\n", file.getName(), file.getId()); - } - } + // Print the names and IDs for up to 10 files. + FileList result = service.files().list() + .setPageSize(10) + .setFields("nextPageToken, files(id, name)") + .execute(); + List files = result.getFiles(); + if (files == null || files.isEmpty()) { + System.out.println("No files found."); + } else { + System.out.println("Files:"); + for (File file : files) { + System.out.printf("%s (%s)\n", file.getName(), file.getId()); + } } + } } // [END drive_quickstart] diff --git a/drive/snippets/drive_v2/files/config.json b/drive/snippets/drive_v2/files/config.json index 3d2519ed..b42f309e 100644 --- a/drive/snippets/drive_v2/files/config.json +++ b/drive/snippets/drive_v2/files/config.json @@ -1,3 +1,3 @@ { - "foo" : "bar" + "foo": "bar" } \ No newline at end of file diff --git a/drive/snippets/drive_v2/src/main/java/AppDataSnippets.java b/drive/snippets/drive_v2/src/main/java/AppDataSnippets.java index cee70b57..6d13d7a4 100644 --- a/drive/snippets/drive_v2/src/main/java/AppDataSnippets.java +++ b/drive/snippets/drive_v2/src/main/java/AppDataSnippets.java @@ -19,7 +19,6 @@ import com.google.api.services.drive.model.File; import com.google.api.services.drive.model.FileList; import com.google.api.services.drive.model.ParentReference; - import java.io.IOException; import java.util.Collections; diff --git a/drive/snippets/drive_v2/src/main/java/ChangeSnippets.java b/drive/snippets/drive_v2/src/main/java/ChangeSnippets.java index ae8d4558..b3999d88 100644 --- a/drive/snippets/drive_v2/src/main/java/ChangeSnippets.java +++ b/drive/snippets/drive_v2/src/main/java/ChangeSnippets.java @@ -18,7 +18,6 @@ import com.google.api.services.drive.model.Change; import com.google.api.services.drive.model.ChangeList; import com.google.api.services.drive.model.StartPageToken; - import java.io.IOException; public class ChangeSnippets { diff --git a/drive/snippets/drive_v2/src/main/java/CreateDrive.java b/drive/snippets/drive_v2/src/main/java/CreateDrive.java index 70da1fe3..31265b2e 100644 --- a/drive/snippets/drive_v2/src/main/java/CreateDrive.java +++ b/drive/snippets/drive_v2/src/main/java/CreateDrive.java @@ -17,12 +17,10 @@ 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.drive.Drive; import com.google.api.services.drive.DriveScopes; import com.google.api.services.drive.model.Drive; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.Arrays; import java.util.UUID; @@ -30,42 +28,45 @@ /* class to demonstrate use-case of Drive's create drive. */ public class CreateDrive { - /** - * Create a drive. - * @return Newly created drive id. - * @throws IOException if service account credentials file not found. - */ - public static String createDrive() throws IOException { + /** + * Create a drive. + * + * @return Newly created drive id. + * @throws IOException if service account credentials file not found. + */ + public static String createDrive() 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(Arrays.asList(DriveScopes.DRIVE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = + GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - com.google.api.services.drive.Drive service = new com.google.api.services.drive.Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); + // Build a new authorized API client service. + com.google.api.services.drive.Drive service = + new com.google.api.services.drive.Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); - Drive driveMetadata = new Drive(); - driveMetadata.setName("Project Resources"); - String requestId = UUID.randomUUID().toString(); - try { - Drive drive = service.drives().insert(requestId, - driveMetadata) - .execute(); - System.out.println("Drive ID: " + drive.getId()); + Drive driveMetadata = new Drive(); + driveMetadata.setName("Project Resources"); + String requestId = UUID.randomUUID().toString(); + try { + Drive drive = service.drives().insert(requestId, + driveMetadata) + .execute(); + System.out.println("Drive ID: " + drive.getId()); - return drive.getId(); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to create drive: " + e.getDetails()); - throw e; - } + return drive.getId(); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to create drive: " + e.getDetails()); + throw e; } + } } // [END drive_create_drive] diff --git a/drive/snippets/drive_v2/src/main/java/CreateFolder.java b/drive/snippets/drive_v2/src/main/java/CreateFolder.java index 169c796d..ed909ecf 100644 --- a/drive/snippets/drive_v2/src/main/java/CreateFolder.java +++ b/drive/snippets/drive_v2/src/main/java/CreateFolder.java @@ -29,39 +29,41 @@ public class CreateFolder { - /** - * Create new folder. - * @return Inserted folder id if successful, {@code null} otherwise. - * @throws IOException if service account credentials file not found. - */ - public static String createFolder() 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + /** + * Create new folder. + * + * @return Inserted folder id if successful, {@code null} otherwise. + * @throws IOException if service account credentials file not found. + */ + public static String createFolder() 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(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); - // File's metadata. - File fileMetadata = new File(); - fileMetadata.setTitle("Test"); - fileMetadata.setMimeType("application/vnd.google-apps.folder"); - try { - File file = service.files().insert(fileMetadata) - .setFields("id") - .execute(); - System.out.println("Folder ID: " + file.getId()); - return file.getId(); - } catch (IOException e) { - System.out.println("An error occurred: " + e); - return null; - } + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); + // File's metadata. + File fileMetadata = new File(); + fileMetadata.setTitle("Test"); + fileMetadata.setMimeType("application/vnd.google-apps.folder"); + try { + File file = service.files().insert(fileMetadata) + .setFields("id") + .execute(); + System.out.println("Folder ID: " + file.getId()); + return file.getId(); + } catch (IOException e) { + System.out.println("An error occurred: " + e); + return null; } + } } // [END drive_create_folder] diff --git a/drive/snippets/drive_v2/src/main/java/CreateShortcut.java b/drive/snippets/drive_v2/src/main/java/CreateShortcut.java index 35393483..0e4b817c 100644 --- a/drive/snippets/drive_v2/src/main/java/CreateShortcut.java +++ b/drive/snippets/drive_v2/src/main/java/CreateShortcut.java @@ -23,46 +23,47 @@ import com.google.api.services.drive.model.File; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.Arrays; /* Class to demonstrate Drive's create shortcut use-case */ public class CreateShortcut { - /** - * Creates shortcut for file. - * @throws IOException if service account credentials file not found. - */ - public static String createShortcut() throws IOException{ + /** + * Creates shortcut for file. + * + * @throws IOException if service account credentials file not found. + */ + public static String createShortcut() 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); - try { - // Create Shortcut for file. - File fileMetadata = new File(); - fileMetadata.setTitle("Project plan"); - fileMetadata.setMimeType("application/vnd.google-apps.drive-sdk"); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); + try { + // Create Shortcut for file. + File fileMetadata = new File(); + fileMetadata.setTitle("Project plan"); + fileMetadata.setMimeType("application/vnd.google-apps.drive-sdk"); - File file = service.files().insert(fileMetadata) - .setFields("id") - .execute(); - System.out.println("File ID: " + file.getId()); - return file.getId(); - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to create shortcut: " + e.getDetails()); - throw e; - } + File file = service.files().insert(fileMetadata) + .setFields("id") + .execute(); + System.out.println("File ID: " + file.getId()); + return file.getId(); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to create shortcut: " + e.getDetails()); + throw e; } + } } // [END drive_create_shortcut] diff --git a/drive/snippets/drive_v2/src/main/java/CreateTeamDrive.java b/drive/snippets/drive_v2/src/main/java/CreateTeamDrive.java index 8dad2711..dff70011 100644 --- a/drive/snippets/drive_v2/src/main/java/CreateTeamDrive.java +++ b/drive/snippets/drive_v2/src/main/java/CreateTeamDrive.java @@ -17,12 +17,10 @@ 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.drive.Drive; import com.google.api.services.drive.DriveScopes; import com.google.api.services.drive.model.TeamDrive; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.Arrays; import java.util.UUID; @@ -30,39 +28,42 @@ /* class to demonstrate use-case of Drive's create team drive. */ public class CreateTeamDrive { - /** - * Create a drive for team. - * @return Newly created drive id. - * @throws IOException if service account credentials file not found. - */ - public static String createTeamDrive() throws IOException { + /** + * Create a drive for team. + * + * @return Newly created drive id. + * @throws IOException if service account credentials file not found. + */ + public static String createTeamDrive() 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(Arrays.asList(DriveScopes.DRIVE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = + GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - com.google.api.services.drive.Drive service = new com.google.api.services.drive.Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); - try { - TeamDrive teamDriveMetadata = new TeamDrive(); - teamDriveMetadata.setName("Project Resources"); - String requestId = UUID.randomUUID().toString(); - TeamDrive teamDrive = service.teamdrives().insert(requestId, teamDriveMetadata) - .execute(); - System.out.println("Team Drive ID: " + teamDrive.getId()); - return teamDrive.getId(); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to create team drive: " + e.getDetails()); - throw e; - } + // Build a new authorized API client service. + com.google.api.services.drive.Drive service = + new com.google.api.services.drive.Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); + try { + TeamDrive teamDriveMetadata = new TeamDrive(); + teamDriveMetadata.setName("Project Resources"); + String requestId = UUID.randomUUID().toString(); + TeamDrive teamDrive = service.teamdrives().insert(requestId, teamDriveMetadata) + .execute(); + System.out.println("Team Drive ID: " + teamDrive.getId()); + return teamDrive.getId(); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to create team drive: " + e.getDetails()); + throw e; } + } } // [END drive_create_team_drive] diff --git a/drive/snippets/drive_v2/src/main/java/DownloadFile.java b/drive/snippets/drive_v2/src/main/java/DownloadFile.java index 0931acc5..2098d1a9 100644 --- a/drive/snippets/drive_v2/src/main/java/DownloadFile.java +++ b/drive/snippets/drive_v2/src/main/java/DownloadFile.java @@ -22,7 +22,6 @@ import com.google.api.services.drive.DriveScopes; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; @@ -31,39 +30,41 @@ /* Class to demonstrate use-case of drive's download file. */ public class DownloadFile { - /** - * Download a Document file in PDF format. - * @param realFileId file ID of any workspace document format file. - * @return byte array stream if successful, {@code null} otherwise. - * @throws IOException if service account credentials file not found. - */ - public static ByteArrayOutputStream downloadFile(String realFileId) throws IOException{ + /** + * Download a Document file in PDF format. + * + * @param realFileId file ID of any workspace document format file. + * @return byte array stream if successful, {@code null} otherwise. + * @throws IOException if service account credentials file not found. + */ + public static ByteArrayOutputStream downloadFile(String realFileId) 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); - try { - OutputStream outputStream = new ByteArrayOutputStream(); + try { + OutputStream outputStream = new ByteArrayOutputStream(); - service.files().get(realFileId) - .executeMediaAndDownloadTo(outputStream); + service.files().get(realFileId) + .executeMediaAndDownloadTo(outputStream); - return (ByteArrayOutputStream) outputStream; - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to move file: " + e.getDetails()); - throw e; - } + return (ByteArrayOutputStream) outputStream; + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to move file: " + e.getDetails()); + throw e; } + } } // [END drive_download_file] diff --git a/drive/snippets/drive_v2/src/main/java/DriveSnippets.java b/drive/snippets/drive_v2/src/main/java/DriveSnippets.java index 8c70c3da..a40483bc 100644 --- a/drive/snippets/drive_v2/src/main/java/DriveSnippets.java +++ b/drive/snippets/drive_v2/src/main/java/DriveSnippets.java @@ -17,7 +17,6 @@ import com.google.api.services.drive.model.Drive; import com.google.api.services.drive.model.DriveList; import com.google.api.services.drive.model.Permission; - import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -37,14 +36,14 @@ public String createDrive() throws IOException { driveMetadata.setName("Project Resources"); String requestId = UUID.randomUUID().toString(); Drive drive = driveService.drives().insert(requestId, driveMetadata) - .execute(); + .execute(); System.out.println("Drive ID: " + drive.getId()); // [END createDrive] return drive.getId(); } public List recoverDrives(String realUser) - throws IOException { + throws IOException { com.google.api.services.drive.Drive driveService = this.service; List drives = new ArrayList(); // [START recoverDrives] @@ -57,33 +56,33 @@ public List recoverDrives(String realUser) // organizer is assigned. String pageToken = null; Permission newOrganizerPermission = new Permission() - .setType("user") - .setRole("organizer") - .setValue("user@example.com"); + .setType("user") + .setRole("organizer") + .setValue("user@example.com"); // [START_EXCLUDE silent] newOrganizerPermission.setValue(realUser); // [END_EXCLUDE] do { DriveList result = driveService.drives().list() - .setQ("organizerCount = 0") - .setUseDomainAdminAccess(true) - .setFields("nextPageToken, items(id, name)") - .setPageToken(pageToken) - .execute(); + .setQ("organizerCount = 0") + .setUseDomainAdminAccess(true) + .setFields("nextPageToken, items(id, name)") + .setPageToken(pageToken) + .execute(); for (Drive drive : result.getItems()) { System.out.printf("Found drive without organizer: %s (%s)\n", - drive.getName(), drive.getId()); + drive.getName(), drive.getId()); // Note: For improved efficiency, consider batching // permission insert requests Permission permissionResult = driveService.permissions() - .insert(drive.getId(), newOrganizerPermission) - .setUseDomainAdminAccess(true) - .setSupportsAllDrives(true) - .setFields("id") - .execute(); + .insert(drive.getId(), newOrganizerPermission) + .setUseDomainAdminAccess(true) + .setSupportsAllDrives(true) + .setFields("id") + .execute(); System.out.printf("Added organizer permission: %s\n", - permissionResult.getId()); + permissionResult.getId()); } // [START_EXCLUDE silent] diff --git a/drive/snippets/drive_v2/src/main/java/ExportPdf.java b/drive/snippets/drive_v2/src/main/java/ExportPdf.java index 16d86539..789e232a 100644 --- a/drive/snippets/drive_v2/src/main/java/ExportPdf.java +++ b/drive/snippets/drive_v2/src/main/java/ExportPdf.java @@ -22,7 +22,6 @@ import com.google.api.services.drive.DriveScopes; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; @@ -31,38 +30,40 @@ /* Class to demonstrate use-case of drive's export pdf. */ public class ExportPdf { - /** - * Download a Document file in PDF format. - * @param realFileId file ID of any workspace document format file. - * @return byte array stream if successful, {@code null} otherwise. - * @throws IOException if service account credentials file not found. - */ - public static ByteArrayOutputStream exportPdf(String realFileId) 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + /** + * Download a Document file in PDF format. + * + * @param realFileId file ID of any workspace document format file. + * @return byte array stream if successful, {@code null} otherwise. + * @throws IOException if service account credentials file not found. + */ + public static ByteArrayOutputStream exportPdf(String realFileId) 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(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); - OutputStream outputStream = new ByteArrayOutputStream(); - try { - service.files().export(realFileId, "application/pdf") - .executeMediaAndDownloadTo(outputStream); + OutputStream outputStream = new ByteArrayOutputStream(); + try { + service.files().export(realFileId, "application/pdf") + .executeMediaAndDownloadTo(outputStream); - return (ByteArrayOutputStream) outputStream; - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to export file: " + e.getDetails()); - throw e; - } + return (ByteArrayOutputStream) outputStream; + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to export file: " + e.getDetails()); + throw e; } + } } // [END drive_export_pdf] diff --git a/drive/snippets/drive_v2/src/main/java/FetchAppDataFolder.java b/drive/snippets/drive_v2/src/main/java/FetchAppDataFolder.java index c402a18a..16c27b6f 100644 --- a/drive/snippets/drive_v2/src/main/java/FetchAppDataFolder.java +++ b/drive/snippets/drive_v2/src/main/java/FetchAppDataFolder.java @@ -14,61 +14,59 @@ // [START drive_fetch_appdata_folder] import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.FileContent; 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.drive.Drive; import com.google.api.services.drive.DriveScopes; import com.google.api.services.drive.model.File; -import com.google.api.services.drive.model.FileList; -import com.google.api.services.drive.model.ParentReference; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; -import java.security.GeneralSecurityException; import java.util.Arrays; -import java.util.Collections; -/** Class to demonstrate use-case of list out application data folder and prints folder Id. */ +/** + * Class to demonstrate use-case of list out application data folder and prints folder Id. + */ public class FetchAppDataFolder { - /** - * Fetches appDataFolder and prints it's folder id. - * @return Application data folder's ID. - */ - public static String fetchAppDataFolder() throws IOException { + /** + * Fetches appDataFolder and prints it's folder id. + * + * @return Application data folder's ID. + */ + public static String fetchAppDataFolder() 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 = null; - try { - credentials = GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE_APPDATA)); - } catch (IOException e) { - e.printStackTrace(); - } - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = null; + try { + credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Arrays.asList(DriveScopes.DRIVE_APPDATA)); + } catch (IOException e) { + e.printStackTrace(); + } + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); - try { - File file = service.files().get("appDataFolder") - .setFields("id") - .execute(); - System.out.println("Folder ID: " + file.getId()); + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); + try { + File file = service.files().get("appDataFolder") + .setFields("id") + .execute(); + System.out.println("Folder ID: " + file.getId()); - return file.getId(); - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to fetch appdata folder: " + e.getDetails()); - throw e; - } + return file.getId(); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to fetch appdata folder: " + e.getDetails()); + throw e; } + } } // [END drive_fetch_appdata_folder] diff --git a/drive/snippets/drive_v2/src/main/java/FetchChanges.java b/drive/snippets/drive_v2/src/main/java/FetchChanges.java index 3ff6e584..d2154eaa 100644 --- a/drive/snippets/drive_v2/src/main/java/FetchChanges.java +++ b/drive/snippets/drive_v2/src/main/java/FetchChanges.java @@ -20,60 +20,60 @@ import com.google.api.services.drive.Drive; import com.google.api.services.drive.DriveScopes; import com.google.api.services.drive.model.ChangeList; -import com.google.api.services.drive.model.StartPageToken; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.Arrays; /* Class to demonstrate use-case of Drive's fetch changes in file. */ public class FetchChanges { - /** - * Retrieve the list of changes for the currently authenticated user. - * @param savedStartPageToken Last saved start token for this user. - * @return Saved token after last page. - * @throws IOException if file is not found - */ - public static String fetchChanges(String savedStartPageToken) throws IOException { + /** + * Retrieve the list of changes for the currently authenticated user. + * + * @param savedStartPageToken Last saved start token for this user. + * @return Saved token after last page. + * @throws IOException if file is not found + */ + public static String fetchChanges(String savedStartPageToken) 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); - - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); - try { - // Begin with our last saved start token for this user or the - // current token from getStartPageToken() - String pageToken = savedStartPageToken; - while (pageToken != null) { - ChangeList changes = service.changes().list().setPageToken(pageToken) - .execute(); - for (com.google.api.services.drive.model.Change change : changes.getItems()) { - // Process change - System.out.println("Change found for file: " + change.getFileId()); - } - if (changes.getNewStartPageToken() != null) { - // Last page, save this token for the next polling interval - savedStartPageToken = changes.getNewStartPageToken(); - } - pageToken = changes.getNextPageToken(); - } + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - return savedStartPageToken; - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to fetch changes: " + e.getDetails()); - throw e; + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); + try { + // Begin with our last saved start token for this user or the + // current token from getStartPageToken() + String pageToken = savedStartPageToken; + while (pageToken != null) { + ChangeList changes = service.changes().list().setPageToken(pageToken) + .execute(); + for (com.google.api.services.drive.model.Change change : changes.getItems()) { + // Process change + System.out.println("Change found for file: " + change.getFileId()); } + if (changes.getNewStartPageToken() != null) { + // Last page, save this token for the next polling interval + savedStartPageToken = changes.getNewStartPageToken(); + } + pageToken = changes.getNextPageToken(); + } + + return savedStartPageToken; + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to fetch changes: " + e.getDetails()); + throw e; } + } } // [END drive_fetch_changes] diff --git a/drive/snippets/drive_v2/src/main/java/FetchStartPageToken.java b/drive/snippets/drive_v2/src/main/java/FetchStartPageToken.java index c77419a6..a3445c7a 100644 --- a/drive/snippets/drive_v2/src/main/java/FetchStartPageToken.java +++ b/drive/snippets/drive_v2/src/main/java/FetchStartPageToken.java @@ -19,49 +19,49 @@ import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.drive.Drive; import com.google.api.services.drive.DriveScopes; -import com.google.api.services.drive.model.ChangeList; import com.google.api.services.drive.model.StartPageToken; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.Arrays; /* Class to demonstrate use-case of Drive's fetch start page token */ public class FetchStartPageToken { - /** - * Retrieve the start page token for the first time. - * @return Start page token as String. - * @throws IOException if file is not found - */ - public static String fetchStartPageToken() throws IOException { + /** + * Retrieve the start page token for the first time. + * + * @return Start page token as String. + * @throws IOException if file is not found + */ + public static String fetchStartPageToken() 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); - try { - StartPageToken response = service.changes() - .getStartPageToken().execute(); - System.out.println("Start token: " + response.getStartPageToken()); + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); + try { + StartPageToken response = service.changes() + .getStartPageToken().execute(); + System.out.println("Start token: " + response.getStartPageToken()); - return response.getStartPageToken(); - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to fetch start page token: " + e.getDetails()); - throw e; - } + return response.getStartPageToken(); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to fetch start page token: " + e.getDetails()); + throw e; } + } } // [END drive_fetch_start_page_token] diff --git a/drive/snippets/drive_v2/src/main/java/ListAppData.java b/drive/snippets/drive_v2/src/main/java/ListAppData.java index 7ed0782e..1628c42b 100644 --- a/drive/snippets/drive_v2/src/main/java/ListAppData.java +++ b/drive/snippets/drive_v2/src/main/java/ListAppData.java @@ -14,7 +14,6 @@ // [START drive_list_appdata] import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.FileContent; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; @@ -22,59 +21,59 @@ import com.google.api.services.drive.DriveScopes; import com.google.api.services.drive.model.File; import com.google.api.services.drive.model.FileList; -import com.google.api.services.drive.model.ParentReference; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; -import java.security.GeneralSecurityException; import java.util.Arrays; -import java.util.Collections; -/** Class to demonstrate use-case of list 10 files in the application data folder. */ +/** + * Class to demonstrate use-case of list 10 files in the application data folder. + */ public class ListAppData { - /** - * list down files in the application data folder. - * @return list of 10 files. - */ - public static FileList listAppData() throws IOException { + /** + * list down files in the application data folder. + * + * @return list of 10 files. + */ + public static FileList listAppData() 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 = null; - try { - credentials = GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE_APPDATA)); - } catch (IOException e) { - e.printStackTrace(); - } - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = null; + try { + credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Arrays.asList(DriveScopes.DRIVE_APPDATA)); + } catch (IOException e) { + e.printStackTrace(); + } + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); - try { - FileList files = service.files().list() - .setSpaces("appDataFolder") - .setFields("nextPageToken, items(id, title)") - .setMaxResults(10) - .execute(); - for (File file : files.getItems()) { - System.out.printf("Found file: %s (%s)\n", - file.getTitle(), file.getId()); - } + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); + try { + FileList files = service.files().list() + .setSpaces("appDataFolder") + .setFields("nextPageToken, items(id, title)") + .setMaxResults(10) + .execute(); + for (File file : files.getItems()) { + System.out.printf("Found file: %s (%s)\n", + file.getTitle(), file.getId()); + } - return files; - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to list files: " + e.getDetails()); - throw e; - } + return files; + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to list files: " + e.getDetails()); + throw e; } + } } // [END drive_list_appdata] \ No newline at end of file diff --git a/drive/snippets/drive_v2/src/main/java/MoveFileToFolder.java b/drive/snippets/drive_v2/src/main/java/MoveFileToFolder.java index c45ba0e2..15dcf2b9 100644 --- a/drive/snippets/drive_v2/src/main/java/MoveFileToFolder.java +++ b/drive/snippets/drive_v2/src/main/java/MoveFileToFolder.java @@ -16,7 +16,6 @@ import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.FileContent; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; @@ -26,65 +25,64 @@ import com.google.api.services.drive.model.ParentReference; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -import java.util.stream.Stream; /* Class to demonstrate use case for moving file to folder.*/ public class MoveFileToFolder { - /** - * @param fileId Id of file to be moved. - * @param folderId Id of folder where the fill will be moved. - * @return list of parent ids for the file. - * */ - public static List moveFileToFolder(String fileId, String folderId) - throws IOException { + /** + * @param fileId Id of file to be moved. + * @param folderId Id of folder where the fill will be moved. + * @return list of parent ids for the file. + */ + public static List moveFileToFolder(String fileId, String folderId) + 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); - // Retrieve the existing parents to remove - File file = service.files().get(fileId) - .setFields("parents") - .execute(); - List parentIds = file.getParents() - .stream() - .map(ParentReference::getId) - .collect(Collectors.toList()); - String previousParents = String.join(",", parentIds); - try { - // Move the file to the new folder - file = service.files().update(fileId, null) - .setAddParents(folderId) - .setRemoveParents(previousParents) - .setFields("id, parents") - .execute(); + // Retrieve the existing parents to remove + File file = service.files().get(fileId) + .setFields("parents") + .execute(); + List parentIds = file.getParents() + .stream() + .map(ParentReference::getId) + .collect(Collectors.toList()); + String previousParents = String.join(",", parentIds); + try { + // Move the file to the new folder + file = service.files().update(fileId, null) + .setAddParents(folderId) + .setRemoveParents(previousParents) + .setFields("id, parents") + .execute(); - List parents = new ArrayList<>(); - for (ParentReference parent : file.getParents()) { - parents.add(parent.getId()); - } - return parents; - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to move file: " + e.getDetails()); - throw e; - } + List parents = new ArrayList<>(); + for (ParentReference parent : file.getParents()) { + parents.add(parent.getId()); + } + return parents; + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to move file: " + e.getDetails()); + throw e; } + } } // [END drive_move_file_to_folder] diff --git a/drive/snippets/drive_v2/src/main/java/RecoverDrive.java b/drive/snippets/drive_v2/src/main/java/RecoverDrive.java index 038f1a57..d00de913 100644 --- a/drive/snippets/drive_v2/src/main/java/RecoverDrive.java +++ b/drive/snippets/drive_v2/src/main/java/RecoverDrive.java @@ -17,14 +17,12 @@ 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.drive.Drive; import com.google.api.services.drive.DriveScopes; import com.google.api.services.drive.model.Drive; import com.google.api.services.drive.model.DriveList; import com.google.api.services.drive.model.Permission; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; @@ -33,74 +31,77 @@ /* class to demonstrate use-case of Drive's shared drive without an organizer. */ public class RecoverDrive { - /** - * Find all shared drives without an organizer and add one. - * @param realUser User's email id. - * @return All shared drives without an organizer. - * @throws IOException if shared drive not found. - */ - public static List recoverDrives(String realUser) - throws IOException { + /** + * Find all shared drives without an organizer and add one. + * + * @param realUser User's email id. + * @return All shared drives without an organizer. + * @throws IOException if shared drive not found. + */ + public static List recoverDrives(String realUser) + 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(Arrays.asList(DriveScopes.DRIVE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = + GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - com.google.api.services.drive.Drive service = new com.google.api.services.drive.Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); - List drives = new ArrayList(); + // Build a new authorized API client service. + com.google.api.services.drive.Drive service = + new com.google.api.services.drive.Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); + List drives = new ArrayList(); - // Find all shared drives without an organizer and add one. - // Note: This example does not capture all cases. Shared drives - // that have an empty group as the sole organizer, or an - // organizer outside the organization are not captured. A - // more exhaustive approach would evaluate each shared drive - // and the associated permissions and groups to ensure an active - // organizer is assigned. - String pageToken = null; - Permission newOrganizerPermission = new Permission() - .setType("user") - .setRole("organizer") - .setValue("user@example.com"); + // Find all shared drives without an organizer and add one. + // Note: This example does not capture all cases. Shared drives + // that have an empty group as the sole organizer, or an + // organizer outside the organization are not captured. A + // more exhaustive approach would evaluate each shared drive + // and the associated permissions and groups to ensure an active + // organizer is assigned. + String pageToken = null; + Permission newOrganizerPermission = new Permission() + .setType("user") + .setRole("organizer") + .setValue("user@example.com"); - newOrganizerPermission.setValue(realUser); + newOrganizerPermission.setValue(realUser); - do { - DriveList result = service.drives().list() - .setQ("organizerCount = 0") - .setUseDomainAdminAccess(true) - .setFields("nextPageToken, items(id, name)") - .setPageToken(pageToken) - .execute(); - for (Drive drive : result.getItems()) { - System.out.printf("Found drive without organizer: %s (%s)\n", - drive.getName(), drive.getId()); - // Note: For improved efficiency, consider batching - // permission insert requests - Permission permissionResult = service.permissions() - .insert(drive.getId(), newOrganizerPermission) - .setUseDomainAdminAccess(true) - .setSupportsAllDrives(true) - .setFields("id") - .execute(); - System.out.printf("Added organizer permission: %s\n", - permissionResult.getId()); + do { + DriveList result = service.drives().list() + .setQ("organizerCount = 0") + .setUseDomainAdminAccess(true) + .setFields("nextPageToken, items(id, name)") + .setPageToken(pageToken) + .execute(); + for (Drive drive : result.getItems()) { + System.out.printf("Found drive without organizer: %s (%s)\n", + drive.getName(), drive.getId()); + // Note: For improved efficiency, consider batching + // permission insert requests + Permission permissionResult = service.permissions() + .insert(drive.getId(), newOrganizerPermission) + .setUseDomainAdminAccess(true) + .setSupportsAllDrives(true) + .setFields("id") + .execute(); + System.out.printf("Added organizer permission: %s\n", + permissionResult.getId()); - } - drives.addAll(result.getItems()); + } + drives.addAll(result.getItems()); - pageToken = result.getNextPageToken(); - } while (pageToken != null); + pageToken = result.getNextPageToken(); + } while (pageToken != null); - return drives; - } + return drives; + } } // [END drive_recover_drives] diff --git a/drive/snippets/drive_v2/src/main/java/RecoverTeamDrive.java b/drive/snippets/drive_v2/src/main/java/RecoverTeamDrive.java index a11d4a24..84705826 100644 --- a/drive/snippets/drive_v2/src/main/java/RecoverTeamDrive.java +++ b/drive/snippets/drive_v2/src/main/java/RecoverTeamDrive.java @@ -17,14 +17,12 @@ 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.drive.Drive; import com.google.api.services.drive.DriveScopes; import com.google.api.services.drive.model.Permission; import com.google.api.services.drive.model.TeamDrive; import com.google.api.services.drive.model.TeamDriveList; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; @@ -33,77 +31,80 @@ /* class to demonstrate use-case of Drive's recover all team drives without an organizer. */ public class RecoverTeamDrive { - /** - * Finds all Team Drives without an organizer and add one. - * @param realUser User ID for the new organizer. - * @return All team drives without an organizer. - * @throws IOException if service account credentials file not found. - */ - public static List recoverTeamDrives(String realUser) throws IOException { + /** + * Finds all Team Drives without an organizer and add one. + * + * @param realUser User ID for the new organizer. + * @return All team drives without an organizer. + * @throws IOException if service account credentials file not found. + */ + public static List recoverTeamDrives(String realUser) 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(Arrays.asList(DriveScopes.DRIVE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = + GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - com.google.api.services.drive.Drive service = new com.google.api.services.drive.Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); - List teamDrives = new ArrayList(); + // Build a new authorized API client service. + com.google.api.services.drive.Drive service = + new com.google.api.services.drive.Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); + List teamDrives = new ArrayList(); - // Find all Team Drives without an organizer and add one. - // Note: This example does not capture all cases. Team Drives - // that have an empty group as the sole organizer, or an - // organizer outside the organization are not captured. A - // more exhaustive approach would evaluate each Team Drive - // and the associated permissions and groups to ensure an active - // organizer is assigned. - String pageToken = null; - Permission newOrganizerPermission = new Permission() - .setType("user") - .setRole("organizer") - .setValue("user@example.com"); + // Find all Team Drives without an organizer and add one. + // Note: This example does not capture all cases. Team Drives + // that have an empty group as the sole organizer, or an + // organizer outside the organization are not captured. A + // more exhaustive approach would evaluate each Team Drive + // and the associated permissions and groups to ensure an active + // organizer is assigned. + String pageToken = null; + Permission newOrganizerPermission = new Permission() + .setType("user") + .setRole("organizer") + .setValue("user@example.com"); - newOrganizerPermission.setValue(realUser); - try { - do { - TeamDriveList result = service.teamdrives().list() - .setQ("organizerCount = 0") - .setUseDomainAdminAccess(true) - .setFields("nextPageToken, items(id, name)") - .setPageToken(pageToken) - .execute(); - for (TeamDrive teamDrive : result.getItems()) { - System.out.printf("Found Team Drive without organizer: %s (%s)\n", - teamDrive.getName(), teamDrive.getId()); - // Note: For improved efficiency, consider batching - // permission insert requests - Permission permissionResult = service.permissions() - .insert(teamDrive.getId(), newOrganizerPermission) - .setUseDomainAdminAccess(true) - .setSupportsTeamDrives(true) - .setFields("id") - .execute(); - System.out.printf("Added organizer permission: %s\n", - permissionResult.getId()); - } + newOrganizerPermission.setValue(realUser); + try { + do { + TeamDriveList result = service.teamdrives().list() + .setQ("organizerCount = 0") + .setUseDomainAdminAccess(true) + .setFields("nextPageToken, items(id, name)") + .setPageToken(pageToken) + .execute(); + for (TeamDrive teamDrive : result.getItems()) { + System.out.printf("Found Team Drive without organizer: %s (%s)\n", + teamDrive.getName(), teamDrive.getId()); + // Note: For improved efficiency, consider batching + // permission insert requests + Permission permissionResult = service.permissions() + .insert(teamDrive.getId(), newOrganizerPermission) + .setUseDomainAdminAccess(true) + .setSupportsTeamDrives(true) + .setFields("id") + .execute(); + System.out.printf("Added organizer permission: %s\n", + permissionResult.getId()); + } - teamDrives.addAll(result.getItems()); + teamDrives.addAll(result.getItems()); - pageToken = result.getNextPageToken(); - } while (pageToken != null); + pageToken = result.getNextPageToken(); + } while (pageToken != null); - return teamDrives; - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to recover team drive: " + e.getDetails()); - throw e; - } + return teamDrives; + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to recover team drive: " + e.getDetails()); + throw e; } + } } // [END drive_recover_team_drives] diff --git a/drive/snippets/drive_v2/src/main/java/SearchFile.java b/drive/snippets/drive_v2/src/main/java/SearchFile.java index 242c575b..f6543292 100644 --- a/drive/snippets/drive_v2/src/main/java/SearchFile.java +++ b/drive/snippets/drive_v2/src/main/java/SearchFile.java @@ -23,7 +23,6 @@ import com.google.api.services.drive.model.FileList; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; @@ -32,47 +31,49 @@ /* Class to demonstrate use-case of search files. */ public class SearchFile { - /** - * Search for specific set of files. - * @return search result list. - * @throws IOException if service account credentials file not found. - */ - public static List searchFile() throws IOException{ + /** + * Search for specific set of files. + * + * @return search result list. + * @throws IOException if service account credentials file not found. + */ + public static List searchFile() 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); - List files = new ArrayList(); + List files = new ArrayList(); - String pageToken = null; - do { - FileList result = service.files().list() - .setQ("mimeType='image/jpeg'") - .setSpaces("drive") - .setFields("nextPageToken, items(id, title)") - .setPageToken(pageToken) - .execute(); - for (File file : result.getItems()) { - System.out.printf("Found file: %s (%s)\n", - file.getTitle(), file.getId()); - } + String pageToken = null; + do { + FileList result = service.files().list() + .setQ("mimeType='image/jpeg'") + .setSpaces("drive") + .setFields("nextPageToken, items(id, title)") + .setPageToken(pageToken) + .execute(); + for (File file : result.getItems()) { + System.out.printf("Found file: %s (%s)\n", + file.getTitle(), file.getId()); + } - files.addAll(result.getItems()); + files.addAll(result.getItems()); - pageToken = result.getNextPageToken(); - } while (pageToken != null); + pageToken = result.getNextPageToken(); + } while (pageToken != null); - return files; - } + return files; + } } // [END drive_search_files] diff --git a/drive/snippets/drive_v2/src/main/java/ShareFile.java b/drive/snippets/drive_v2/src/main/java/ShareFile.java index 1b423722..ecbd3bf1 100644 --- a/drive/snippets/drive_v2/src/main/java/ShareFile.java +++ b/drive/snippets/drive_v2/src/main/java/ShareFile.java @@ -27,7 +27,6 @@ import com.google.api.services.drive.model.Permission; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; @@ -36,80 +35,83 @@ /* Class to demonstrate use-case of modify permissions. */ public class ShareFile { - /** - * Batch permission modification. - * realFileId file Id. - * realUser User Id. - * realDomain Domain of the user ID. - * @return list of modified permissions if successful, {@code null} otherwise. - * @throws IOException if service account credentials file not found. - */ - public static List shareFile(String realFileId, String realUser, String realDomain) throws IOException{ + /** + * Batch permission modification. + * realFileId file Id. + * realUser User Id. + * realDomain Domain of the user ID. + * + * @return list of modified permissions if successful, {@code null} otherwise. + * @throws IOException if service account credentials file not found. + */ + public static List shareFile(String realFileId, String realUser, String realDomain) + 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.application*/ - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); - - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); - - final List ids = new ArrayList(); - - - JsonBatchCallback callback = new JsonBatchCallback() { - @Override - public void onFailure(GoogleJsonError e, - HttpHeaders responseHeaders) - throws IOException { - // Handle error - System.err.println(e.getMessage()); - } - - @Override - public void onSuccess(Permission permission, - HttpHeaders responseHeaders) - throws IOException { - System.out.println("Permission ID: " + permission.getId()); - - ids.add(permission.getId()); - - } - }; - BatchRequest batch = service.batch(); - Permission userPermission = new Permission() - .setType("user") - .setRole("writer"); - - userPermission.setValue(realUser); - try { - service.permissions().insert(realFileId, userPermission) - .setFields("id") - .queue(batch, callback); - - Permission domainPermission = new Permission() - .setType("domain") - .setRole("reader"); - - domainPermission.setValue(realDomain); - - service.permissions().insert(realFileId, domainPermission) - .setFields("id") - .queue(batch, callback); - - batch.execute(); - - return ids; - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to modify permission: " + e.getDetails()); - throw e; - } + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); + + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); + + final List ids = new ArrayList(); + + + JsonBatchCallback callback = new JsonBatchCallback() { + @Override + public void onFailure(GoogleJsonError e, + HttpHeaders responseHeaders) + throws IOException { + // Handle error + System.err.println(e.getMessage()); + } + + @Override + public void onSuccess(Permission permission, + HttpHeaders responseHeaders) + throws IOException { + System.out.println("Permission ID: " + permission.getId()); + + ids.add(permission.getId()); + + } + }; + BatchRequest batch = service.batch(); + Permission userPermission = new Permission() + .setType("user") + .setRole("writer"); + + userPermission.setValue(realUser); + try { + service.permissions().insert(realFileId, userPermission) + .setFields("id") + .queue(batch, callback); + + Permission domainPermission = new Permission() + .setType("domain") + .setRole("reader"); + + domainPermission.setValue(realDomain); + + service.permissions().insert(realFileId, domainPermission) + .setFields("id") + .queue(batch, callback); + + batch.execute(); + + return ids; + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to modify permission: " + e.getDetails()); + throw e; } + } } // [END drive_share_file] diff --git a/drive/snippets/drive_v2/src/main/java/TouchFile.java b/drive/snippets/drive_v2/src/main/java/TouchFile.java index 31ee8f82..6875d862 100644 --- a/drive/snippets/drive_v2/src/main/java/TouchFile.java +++ b/drive/snippets/drive_v2/src/main/java/TouchFile.java @@ -24,7 +24,6 @@ import com.google.api.services.drive.model.File; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.Arrays; @@ -32,47 +31,48 @@ public class TouchFile { - /** - * @param realFileId Id of file to be modified. - * @param realTimestamp Timestamp in miliseconds. - * @return long file's latest modification date value. - * @throws IOException if service account credentials file not found. - * */ - public static long touchFile(String realFileId, long realTimestamp) - throws IOException { + /** + * @param realFileId Id of file to be modified. + * @param realTimestamp Timestamp in miliseconds. + * @return long file's latest modification date value. + * @throws IOException if service account credentials file not found. + */ + public static long touchFile(String realFileId, long realTimestamp) + 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); - String fileId = "1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ"; - File fileMetadata = new File(); - fileMetadata.setModifiedDate(new DateTime(System.currentTimeMillis())); + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); + String fileId = "1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ"; + File fileMetadata = new File(); + fileMetadata.setModifiedDate(new DateTime(System.currentTimeMillis())); - fileId = realFileId; - fileMetadata.setModifiedDate(new DateTime(realTimestamp)); + fileId = realFileId; + fileMetadata.setModifiedDate(new DateTime(realTimestamp)); - try { - File file = service.files().update(fileId, fileMetadata) - .setSetModifiedDate(true) - .setFields("id, modifiedDate") - .execute(); - System.out.println("Modified time: " + file.getModifiedDate()); - return file.getModifiedDate().getValue(); - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to move file: " + e.getDetails()); - throw e; - } + try { + File file = service.files().update(fileId, fileMetadata) + .setSetModifiedDate(true) + .setFields("id, modifiedDate") + .execute(); + System.out.println("Modified time: " + file.getModifiedDate()); + return file.getModifiedDate().getValue(); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to move file: " + e.getDetails()); + throw e; } + } } // [END drive_touch_file] diff --git a/drive/snippets/drive_v2/src/main/java/UploadAppData.java b/drive/snippets/drive_v2/src/main/java/UploadAppData.java index 7731be4e..2bd4f557 100644 --- a/drive/snippets/drive_v2/src/main/java/UploadAppData.java +++ b/drive/snippets/drive_v2/src/main/java/UploadAppData.java @@ -21,62 +21,64 @@ import com.google.api.services.drive.Drive; import com.google.api.services.drive.DriveScopes; import com.google.api.services.drive.model.File; -import com.google.api.services.drive.model.FileList; import com.google.api.services.drive.model.ParentReference; 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 use-case of create file in the application data folder. */ +/** + * Class to demonstrate use-case of create file in the application data folder. + */ public class UploadAppData { - /** - * Creates a file in the application data folder. - * @return Created file's Id. - */ - public static String uploadAppData() throws IOException { + /** + * Creates a file in the application data folder. + * + * @return Created file's Id. + */ + public static String uploadAppData() 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 = null; - try { - credentials = GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE_APPDATA)); - } catch (IOException e) { - e.printStackTrace(); - } - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = null; + try { + credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Arrays.asList(DriveScopes.DRIVE_APPDATA)); + } catch (IOException e) { + e.printStackTrace(); + } + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); - try { - // File's metadata. - File fileMetadata = new File(); - fileMetadata.setTitle("config.json"); - fileMetadata.setParents(Collections.singletonList( - new ParentReference().setId("appDataFolder"))); - java.io.File filePath = new java.io.File("files/config.json"); - // Specify media type and file-path for file. - FileContent mediaContent = new FileContent("application/json", filePath); - File file = service.files().insert(fileMetadata, mediaContent) - .setFields("id") - .execute(); - System.out.println("File ID: " + file.getId()); + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); + try { + // File's metadata. + File fileMetadata = new File(); + fileMetadata.setTitle("config.json"); + fileMetadata.setParents(Collections.singletonList( + new ParentReference().setId("appDataFolder"))); + java.io.File filePath = new java.io.File("files/config.json"); + // Specify media type and file-path for file. + FileContent mediaContent = new FileContent("application/json", filePath); + File file = service.files().insert(fileMetadata, mediaContent) + .setFields("id") + .execute(); + System.out.println("File ID: " + file.getId()); - return file.getId(); - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to create file: " + e.getDetails()); - throw e; - } + return file.getId(); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to create file: " + e.getDetails()); + throw e; } + } } // [END drive_upload_appdata] \ No newline at end of file diff --git a/drive/snippets/drive_v2/src/main/java/UploadBasic.java b/drive/snippets/drive_v2/src/main/java/UploadBasic.java index dc99bb5b..374f240b 100644 --- a/drive/snippets/drive_v2/src/main/java/UploadBasic.java +++ b/drive/snippets/drive_v2/src/main/java/UploadBasic.java @@ -23,49 +23,50 @@ import com.google.api.services.drive.model.File; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.Arrays; /* Class to demonstrate use of Drive insert file API */ public class UploadBasic { - /** - * Upload new file. - * @return Inserted file metadata if successful, {@code null} otherwise. - * @throws IOException if service account credentials file not found. - */ - public static String uploadBasic() 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + /** + * Upload new file. + * + * @return Inserted file metadata if successful, {@code null} otherwise. + * @throws IOException if service account credentials file not found. + */ + public static String uploadBasic() 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(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); - // Upload file photo.jpg on drive. - File fileMetadata = new File(); - fileMetadata.setTitle("photo.jpg"); - // File's content. - java.io.File filePath = new java.io.File("files/photo.jpg"); - // Specify media type and file-path for file. - FileContent mediaContent = new FileContent("image/jpeg", filePath); - try { - File file = service.files().insert(fileMetadata, mediaContent) - .setFields("id") - .execute(); - System.out.println("File ID: " + file.getId()); - return file.getId(); - } catch (IOException e) { - System.out.println("An error occurred: " + e); - return null; - } + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); + // Upload file photo.jpg on drive. + File fileMetadata = new File(); + fileMetadata.setTitle("photo.jpg"); + // File's content. + java.io.File filePath = new java.io.File("files/photo.jpg"); + // Specify media type and file-path for file. + FileContent mediaContent = new FileContent("image/jpeg", filePath); + try { + File file = service.files().insert(fileMetadata, mediaContent) + .setFields("id") + .execute(); + System.out.println("File ID: " + file.getId()); + return file.getId(); + } catch (IOException e) { + System.out.println("An error occurred: " + e); + return null; } + } } // [END drive_upload_basic] diff --git a/drive/snippets/drive_v2/src/main/java/UploadRevision.java b/drive/snippets/drive_v2/src/main/java/UploadRevision.java index c9fccd93..460abe3b 100644 --- a/drive/snippets/drive_v2/src/main/java/UploadRevision.java +++ b/drive/snippets/drive_v2/src/main/java/UploadRevision.java @@ -24,49 +24,50 @@ import com.google.api.services.drive.model.File; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.Arrays; /* Class to demonstrate use-case of drive's upload revision */ public class UploadRevision { - /** - * Replace the old file with new one on same file ID. - * @param realFileId ID of the file to be replaced. - * @return Inserted file ID if successful, {@code null} otherwise. - * @throws IOException if service account credentials file not found. - */ - public static String uploadRevision(String realFileId) 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + /** + * Replace the old file with new one on same file ID. + * + * @param realFileId ID of the file to be replaced. + * @return Inserted file ID if successful, {@code null} otherwise. + * @throws IOException if service account credentials file not found. + */ + public static String uploadRevision(String realFileId) 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(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); - java.io.File filePath = new java.io.File("files/photo.jpg"); - FileContent mediaContent = new FileContent("image/jpeg", filePath); - try { - Drive.Files.Update request = service.files().update(realFileId, new File(), mediaContent) - .setFields("id"); - request.getMediaHttpUploader().setDirectUploadEnabled(true); - File file = request.execute(); - System.out.println("File ID: " + file.getId()); - return file.getId(); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to upload file: " + e.getDetails()); - throw e; - } + java.io.File filePath = new java.io.File("files/photo.jpg"); + FileContent mediaContent = new FileContent("image/jpeg", filePath); + try { + Drive.Files.Update request = service.files().update(realFileId, new File(), mediaContent) + .setFields("id"); + request.getMediaHttpUploader().setDirectUploadEnabled(true); + File file = request.execute(); + System.out.println("File ID: " + file.getId()); + return file.getId(); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to upload file: " + e.getDetails()); + throw e; } + } } // [END drive_upload_revision] diff --git a/drive/snippets/drive_v2/src/main/java/UploadToFolder.java b/drive/snippets/drive_v2/src/main/java/UploadToFolder.java index ac0f156d..fead5537 100644 --- a/drive/snippets/drive_v2/src/main/java/UploadToFolder.java +++ b/drive/snippets/drive_v2/src/main/java/UploadToFolder.java @@ -32,45 +32,47 @@ /* Class to demonstrate Drive's upload to folder use-case. */ public class UploadToFolder { - /** - * Upload a file to the specified folder. - * @param realFolderId Id of the folder. - * @return Inserted file metadata if successful, {@code null} otherwise. - * @throws IOException if service account credentials file not found. - */ - public static File uploadToFolder(String realFolderId) 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + /** + * Upload a file to the specified folder. + * + * @param realFolderId Id of the folder. + * @return Inserted file metadata if successful, {@code null} otherwise. + * @throws IOException if service account credentials file not found. + */ + public static File uploadToFolder(String realFolderId) 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(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); - // File's metadata. - File fileMetadata = new File(); - fileMetadata.setTitle("photo.jpg"); - fileMetadata.setParents(Collections.singletonList( - new ParentReference().setId(realFolderId))); - java.io.File filePath = new java.io.File("files/photo.jpg"); - FileContent mediaContent = new FileContent("image/jpeg", filePath); - try { - File file = service.files().insert(fileMetadata, mediaContent) - .setFields("id, parents") - .execute(); - System.out.println("File ID: " + file.getId()); - return file; - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to move file: " + e.getDetails()); - throw e; - } + // File's metadata. + File fileMetadata = new File(); + fileMetadata.setTitle("photo.jpg"); + fileMetadata.setParents(Collections.singletonList( + new ParentReference().setId(realFolderId))); + java.io.File filePath = new java.io.File("files/photo.jpg"); + FileContent mediaContent = new FileContent("image/jpeg", filePath); + try { + File file = service.files().insert(fileMetadata, mediaContent) + .setFields("id, parents") + .execute(); + System.out.println("File ID: " + file.getId()); + return file; + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to move file: " + e.getDetails()); + throw e; } + } } // [END drive_upload_to_folder] diff --git a/drive/snippets/drive_v2/src/main/java/UploadWithConversion.java b/drive/snippets/drive_v2/src/main/java/UploadWithConversion.java index 36602e10..da62bf44 100644 --- a/drive/snippets/drive_v2/src/main/java/UploadWithConversion.java +++ b/drive/snippets/drive_v2/src/main/java/UploadWithConversion.java @@ -22,54 +22,54 @@ import com.google.api.services.drive.Drive; import com.google.api.services.drive.DriveScopes; import com.google.api.services.drive.model.File; -import com.google.api.services.drive.model.ParentReference; 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 Drive's upload with conversion use-case. */ public class UploadWithConversion { - /** - * Upload file with conversion. - * @return Inserted file id if successful, {@code null} otherwise. - * @throws IOException if service account credentials file not found. - */ - public static String uploadWithConversion() 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + /** + * Upload file with conversion. + * + * @return Inserted file id if successful, {@code null} otherwise. + * @throws IOException if service account credentials file not found. + */ + public static String uploadWithConversion() 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(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); - // File's metadata. - File fileMetadata = new File(); - fileMetadata.setTitle("My Report"); - fileMetadata.setMimeType("application/vnd.google-apps.spreadsheet"); + // File's metadata. + File fileMetadata = new File(); + fileMetadata.setTitle("My Report"); + fileMetadata.setMimeType("application/vnd.google-apps.spreadsheet"); - java.io.File filePath = new java.io.File("files/report.csv"); - FileContent mediaContent = new FileContent("text/csv", filePath); - try { - File file = service.files().insert(fileMetadata, mediaContent) - .setFields("id") - .execute(); - System.out.println("File ID: " + file.getId()); - return file.getId(); - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to move file: " + e.getDetails()); - throw e; - } + java.io.File filePath = new java.io.File("files/report.csv"); + FileContent mediaContent = new FileContent("text/csv", filePath); + try { + File file = service.files().insert(fileMetadata, mediaContent) + .setFields("id") + .execute(); + System.out.println("File ID: " + file.getId()); + return file.getId(); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to move file: " + e.getDetails()); + throw e; } + } } // [END drive_upload_with_conversion] diff --git a/drive/snippets/drive_v2/src/test/java/AppDataSnippetsTest.java b/drive/snippets/drive_v2/src/test/java/AppDataSnippetsTest.java index b4237983..31726d4e 100644 --- a/drive/snippets/drive_v2/src/test/java/AppDataSnippetsTest.java +++ b/drive/snippets/drive_v2/src/test/java/AppDataSnippetsTest.java @@ -14,15 +14,13 @@ * limitations under the License. */ -import com.google.api.services.drive.model.File; -import com.google.api.services.drive.model.FileList; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertNotNull; +import com.google.api.services.drive.model.FileList; import java.io.IOException; import java.security.GeneralSecurityException; - -import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; public class AppDataSnippetsTest extends BaseTest { diff --git a/drive/snippets/drive_v2/src/test/java/BaseTest.java b/drive/snippets/drive_v2/src/test/java/BaseTest.java index 1bbf6e2e..1bf73c68 100644 --- a/drive/snippets/drive_v2/src/test/java/BaseTest.java +++ b/drive/snippets/drive_v2/src/test/java/BaseTest.java @@ -14,26 +14,27 @@ * limitations under the License. */ -import com.google.api.client.http.HttpRequestInitializer; -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.auth.oauth2.GoogleCredentials; import com.google.api.client.http.FileContent; +import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.drive.Drive; import com.google.api.services.drive.DriveScopes; import com.google.api.services.drive.model.File; -import org.junit.After; -import org.junit.Before; - +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; import java.security.GeneralSecurityException; -import java.util.*; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; +import org.junit.After; +import org.junit.Before; public class BaseTest { static { @@ -69,7 +70,8 @@ public void publish(LogRecord record) { public GoogleCredentials getCredential() throws IOException { return GoogleCredentials.getApplicationDefault() - .createScoped(Arrays.asList(DriveScopes.DRIVE, DriveScopes.DRIVE_APPDATA,DriveScopes.DRIVE_FILE)); + .createScoped( + Arrays.asList(DriveScopes.DRIVE, DriveScopes.DRIVE_APPDATA, DriveScopes.DRIVE_FILE)); } /** @@ -84,14 +86,14 @@ protected Drive buildService() throws IOException { guides on implementing OAuth2 for your application. */ GoogleCredentials credentials = getCredential(); HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + credentials); // Create the classroom API client Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive Snippets") - .build(); + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive Snippets") + .build(); return service; } diff --git a/drive/snippets/drive_v2/src/test/java/ChangeSnippetsTest.java b/drive/snippets/drive_v2/src/test/java/ChangeSnippetsTest.java index 4323cc7d..7ad14676 100644 --- a/drive/snippets/drive_v2/src/test/java/ChangeSnippetsTest.java +++ b/drive/snippets/drive_v2/src/test/java/ChangeSnippetsTest.java @@ -14,14 +14,13 @@ * limitations under the License. */ -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; - import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; +import java.io.IOException; +import org.junit.Before; +import org.junit.Test; + public class ChangeSnippetsTest extends BaseTest { private ChangeSnippets snippets; diff --git a/drive/snippets/drive_v2/src/test/java/DriveSnippetsTest.java b/drive/snippets/drive_v2/src/test/java/DriveSnippetsTest.java index 42bbaf53..ebe24d24 100644 --- a/drive/snippets/drive_v2/src/test/java/DriveSnippetsTest.java +++ b/drive/snippets/drive_v2/src/test/java/DriveSnippetsTest.java @@ -14,18 +14,17 @@ * limitations under the License. */ +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; + import com.google.api.services.drive.model.Drive; import com.google.api.services.drive.model.Permission; import com.google.api.services.drive.model.PermissionList; -import org.junit.Before; -import org.junit.Test; - import java.io.IOException; import java.security.GeneralSecurityException; import java.util.List; - -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; +import org.junit.Before; +import org.junit.Test; public class DriveSnippetsTest extends BaseTest { diff --git a/drive/snippets/drive_v2/src/test/java/FileSnippetsTest.java b/drive/snippets/drive_v2/src/test/java/FileSnippetsTest.java index 1efd149b..7703c464 100644 --- a/drive/snippets/drive_v2/src/test/java/FileSnippetsTest.java +++ b/drive/snippets/drive_v2/src/test/java/FileSnippetsTest.java @@ -14,17 +14,18 @@ * limitations under the License. */ -import com.google.api.services.drive.model.File; -import com.google.api.services.drive.model.FileList; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import com.google.api.services.drive.model.File; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.List; - -import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; public class FileSnippetsTest extends BaseTest { diff --git a/drive/snippets/drive_v2/src/test/java/TeamDriveSnippetsTest.java b/drive/snippets/drive_v2/src/test/java/TeamDriveSnippetsTest.java index bfed9e79..a0f53e9c 100644 --- a/drive/snippets/drive_v2/src/test/java/TeamDriveSnippetsTest.java +++ b/drive/snippets/drive_v2/src/test/java/TeamDriveSnippetsTest.java @@ -14,18 +14,17 @@ * limitations under the License. */ -import com.google.api.services.drive.model.TeamDrive; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; + import com.google.api.services.drive.model.Permission; import com.google.api.services.drive.model.PermissionList; -import org.junit.Before; -import org.junit.Test; - +import com.google.api.services.drive.model.TeamDrive; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.List; - -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; +import org.junit.Before; +import org.junit.Test; public class TeamDriveSnippetsTest extends BaseTest { diff --git a/drive/snippets/drive_v2/src/test/java/TestCreateDrive.java b/drive/snippets/drive_v2/src/test/java/TestCreateDrive.java index 4db53c7b..9bd04c2c 100644 --- a/drive/snippets/drive_v2/src/test/java/TestCreateDrive.java +++ b/drive/snippets/drive_v2/src/test/java/TestCreateDrive.java @@ -14,18 +14,17 @@ * limitations under the License. */ -import org.junit.Test; +import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.security.GeneralSecurityException; +import org.junit.Test; -import static org.junit.Assert.assertNotNull; - -public class TestCreateDrive extends BaseTest{ - @Test - public void createDrive() throws IOException, GeneralSecurityException { - String id = CreateDrive.createDrive(); - assertNotNull(id); - this.service.drives().delete(id); - } +public class TestCreateDrive extends BaseTest { + @Test + public void createDrive() throws IOException, GeneralSecurityException { + String id = CreateDrive.createDrive(); + assertNotNull(id); + this.service.drives().delete(id); + } } diff --git a/drive/snippets/drive_v2/src/test/java/TestCreateFolder.java b/drive/snippets/drive_v2/src/test/java/TestCreateFolder.java index 0c7a25af..1c4cffb7 100644 --- a/drive/snippets/drive_v2/src/test/java/TestCreateFolder.java +++ b/drive/snippets/drive_v2/src/test/java/TestCreateFolder.java @@ -14,17 +14,16 @@ * limitations under the License. */ -import org.junit.Test; +import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.security.GeneralSecurityException; - -import static org.junit.Assert.assertNotNull; +import org.junit.Test; public class TestCreateFolder { - @Test - public void createFolder() throws IOException, GeneralSecurityException { - String id = CreateFolder.createFolder(); - assertNotNull(id); - } + @Test + public void createFolder() throws IOException, GeneralSecurityException { + String id = CreateFolder.createFolder(); + assertNotNull(id); + } } diff --git a/drive/snippets/drive_v2/src/test/java/TestCreateShortcut.java b/drive/snippets/drive_v2/src/test/java/TestCreateShortcut.java index 1853773d..ab3e0f2f 100644 --- a/drive/snippets/drive_v2/src/test/java/TestCreateShortcut.java +++ b/drive/snippets/drive_v2/src/test/java/TestCreateShortcut.java @@ -14,18 +14,17 @@ * limitations under the License. */ -import org.junit.Test; +import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.security.GeneralSecurityException; +import org.junit.Test; -import static org.junit.Assert.assertNotNull; - -public class TestCreateShortcut extends BaseTest{ - @Test - public void createShortcut() throws IOException, GeneralSecurityException { - String id = CreateShortcut.createShortcut(); - assertNotNull(id); - deleteFileOnCleanup(id); - } +public class TestCreateShortcut extends BaseTest { + @Test + public void createShortcut() throws IOException, GeneralSecurityException { + String id = CreateShortcut.createShortcut(); + assertNotNull(id); + deleteFileOnCleanup(id); + } } diff --git a/drive/snippets/drive_v2/src/test/java/TestCreateTeamDrive.java b/drive/snippets/drive_v2/src/test/java/TestCreateTeamDrive.java index 72695b33..daccae50 100644 --- a/drive/snippets/drive_v2/src/test/java/TestCreateTeamDrive.java +++ b/drive/snippets/drive_v2/src/test/java/TestCreateTeamDrive.java @@ -14,18 +14,17 @@ * limitations under the License. */ -import org.junit.Test; +import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.security.GeneralSecurityException; +import org.junit.Test; -import static org.junit.Assert.assertNotNull; - -public class TestCreateTeamDrive extends BaseTest{ - @Test - public void createTeamDrive() throws IOException, GeneralSecurityException { - String id = CreateTeamDrive.createTeamDrive(); - assertNotNull(id); - this.service.teamdrives().delete(id); - } +public class TestCreateTeamDrive extends BaseTest { + @Test + public void createTeamDrive() throws IOException, GeneralSecurityException { + String id = CreateTeamDrive.createTeamDrive(); + assertNotNull(id); + this.service.teamdrives().delete(id); + } } diff --git a/drive/snippets/drive_v2/src/test/java/TestDownloadFile.java b/drive/snippets/drive_v2/src/test/java/TestDownloadFile.java index ce285417..526dea94 100644 --- a/drive/snippets/drive_v2/src/test/java/TestDownloadFile.java +++ b/drive/snippets/drive_v2/src/test/java/TestDownloadFile.java @@ -14,21 +14,20 @@ * limitations under the License. */ -import org.junit.Test; +import static org.junit.Assert.assertEquals; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.security.GeneralSecurityException; +import org.junit.Test; -import static org.junit.Assert.assertEquals; - -public class TestDownloadFile extends BaseTest{ - @Test - public void downloadFile() throws IOException, GeneralSecurityException { - String id = createTestBlob(); - ByteArrayOutputStream out = DownloadFile.downloadFile(id); - byte[] bytes = out.toByteArray(); - assertEquals((byte) 0xFF, bytes[0]); - assertEquals((byte) 0xD8, bytes[1]); - } +public class TestDownloadFile extends BaseTest { + @Test + public void downloadFile() throws IOException, GeneralSecurityException { + String id = createTestBlob(); + ByteArrayOutputStream out = DownloadFile.downloadFile(id); + byte[] bytes = out.toByteArray(); + assertEquals((byte) 0xFF, bytes[0]); + assertEquals((byte) 0xD8, bytes[1]); + } } diff --git a/drive/snippets/drive_v2/src/test/java/TestExportPdf.java b/drive/snippets/drive_v2/src/test/java/TestExportPdf.java index fc6deabb..16ede7b4 100644 --- a/drive/snippets/drive_v2/src/test/java/TestExportPdf.java +++ b/drive/snippets/drive_v2/src/test/java/TestExportPdf.java @@ -14,19 +14,18 @@ * limitations under the License. */ -import org.junit.Test; +import static org.junit.Assert.assertEquals; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.security.GeneralSecurityException; +import org.junit.Test; -import static org.junit.Assert.assertEquals; - -public class TestExportPdf extends BaseTest{ - @Test - public void exportPdf() throws IOException, GeneralSecurityException { - String id = createTestDocument(); - ByteArrayOutputStream out = ExportPdf.exportPdf(id); - assertEquals("%PDF", out.toString("UTF-8").substring(0, 4)); - } +public class TestExportPdf extends BaseTest { + @Test + public void exportPdf() throws IOException, GeneralSecurityException { + String id = createTestDocument(); + ByteArrayOutputStream out = ExportPdf.exportPdf(id); + assertEquals("%PDF", out.toString("UTF-8").substring(0, 4)); + } } diff --git a/drive/snippets/drive_v2/src/test/java/TestFetchAppdataFolder.java b/drive/snippets/drive_v2/src/test/java/TestFetchAppdataFolder.java index f53dcd75..8a2ed14b 100644 --- a/drive/snippets/drive_v2/src/test/java/TestFetchAppdataFolder.java +++ b/drive/snippets/drive_v2/src/test/java/TestFetchAppdataFolder.java @@ -12,18 +12,17 @@ // See the License for the specific language governing permissions and // limitations under the License. -import org.junit.Test; +import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.security.GeneralSecurityException; - -import static org.junit.Assert.assertNotNull; +import org.junit.Test; // Unit test class for testing of FetchAppDataFolder snippet public class TestFetchAppdataFolder { - @Test - public void fetchAppDataFolder() throws IOException, GeneralSecurityException { - String id = FetchAppDataFolder.fetchAppDataFolder(); - assertNotNull(id); - } + @Test + public void fetchAppDataFolder() throws IOException, GeneralSecurityException { + String id = FetchAppDataFolder.fetchAppDataFolder(); + assertNotNull(id); + } } diff --git a/drive/snippets/drive_v2/src/test/java/TestFetchChanges.java b/drive/snippets/drive_v2/src/test/java/TestFetchChanges.java index 751c47ec..353d1186 100644 --- a/drive/snippets/drive_v2/src/test/java/TestFetchChanges.java +++ b/drive/snippets/drive_v2/src/test/java/TestFetchChanges.java @@ -14,20 +14,19 @@ * limitations under the License. */ -import org.junit.Test; - -import java.io.IOException; - import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; -public class TestFetchChanges extends BaseTest{ - @Test - public void fetchChanges() throws IOException { - String startPageToken = FetchStartPageToken.fetchStartPageToken(); - this.createTestBlob(); - String newStartPageToken = FetchChanges.fetchChanges(startPageToken); - assertNotNull(newStartPageToken); - assertNotEquals(startPageToken, newStartPageToken); - } +import java.io.IOException; +import org.junit.Test; + +public class TestFetchChanges extends BaseTest { + @Test + public void fetchChanges() throws IOException { + String startPageToken = FetchStartPageToken.fetchStartPageToken(); + this.createTestBlob(); + String newStartPageToken = FetchChanges.fetchChanges(startPageToken); + assertNotNull(newStartPageToken); + assertNotEquals(startPageToken, newStartPageToken); + } } diff --git a/drive/snippets/drive_v2/src/test/java/TestFetchStartPageToken.java b/drive/snippets/drive_v2/src/test/java/TestFetchStartPageToken.java index 270d09a1..ec781a28 100644 --- a/drive/snippets/drive_v2/src/test/java/TestFetchStartPageToken.java +++ b/drive/snippets/drive_v2/src/test/java/TestFetchStartPageToken.java @@ -14,16 +14,15 @@ * limitations under the License. */ -import org.junit.Test; +import static org.junit.Assert.assertNotNull; import java.io.IOException; +import org.junit.Test; -import static org.junit.Assert.assertNotNull; - -public class TestFetchStartPageToken extends BaseTest{ - @Test - public void fetchStartPageToken() throws IOException { - String token = FetchStartPageToken.fetchStartPageToken(); - assertNotNull(token); - } +public class TestFetchStartPageToken extends BaseTest { + @Test + public void fetchStartPageToken() throws IOException { + String token = FetchStartPageToken.fetchStartPageToken(); + assertNotNull(token); + } } diff --git a/drive/snippets/drive_v2/src/test/java/TestListAppdata.java b/drive/snippets/drive_v2/src/test/java/TestListAppdata.java index fe137a43..3aa6558b 100644 --- a/drive/snippets/drive_v2/src/test/java/TestListAppdata.java +++ b/drive/snippets/drive_v2/src/test/java/TestListAppdata.java @@ -13,20 +13,17 @@ // limitations under the License. import com.google.api.services.drive.model.FileList; -import org.junit.Test; - import java.io.IOException; import java.security.GeneralSecurityException; - -import static org.junit.Assert.assertNotEquals; +import org.junit.Test; // Unit test class for testing of ListAppData snippet -public class TestListAppdata extends BaseTest{ - @Test - public void listAppData() throws IOException, GeneralSecurityException { - String id = UploadAppData.uploadAppData(); - deleteFileOnCleanup(id); - FileList files = ListAppData.listAppData(); - assertNotEquals(0, files.getItems().size()); - } +public class TestListAppdata extends BaseTest { + @Test + public void listAppData() throws IOException, GeneralSecurityException { + String id = UploadAppData.uploadAppData(); + deleteFileOnCleanup(id); + FileList files = ListAppData.listAppData(); + assertNotEquals(0, files.getItems().size()); + } } diff --git a/drive/snippets/drive_v2/src/test/java/TestMoveFileToFolder.java b/drive/snippets/drive_v2/src/test/java/TestMoveFileToFolder.java index 7ad8f1bf..7e914647 100644 --- a/drive/snippets/drive_v2/src/test/java/TestMoveFileToFolder.java +++ b/drive/snippets/drive_v2/src/test/java/TestMoveFileToFolder.java @@ -14,25 +14,24 @@ * limitations under the License. */ -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.List; +import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class TestMoveFileToFolder extends BaseTest{ - @Test - public void moveFileToFolder() - throws IOException, GeneralSecurityException { - String folderId = CreateFolder.createFolder(); - deleteFileOnCleanup(folderId); - String fileId = this.createTestBlob(); - List parents = MoveFileToFolder.moveFileToFolder(fileId, folderId); - assertEquals(1, parents.size()); - assertTrue(parents.contains(folderId)); - } +public class TestMoveFileToFolder extends BaseTest { + @Test + public void moveFileToFolder() + throws IOException, GeneralSecurityException { + String folderId = CreateFolder.createFolder(); + deleteFileOnCleanup(folderId); + String fileId = this.createTestBlob(); + List parents = MoveFileToFolder.moveFileToFolder(fileId, folderId); + assertEquals(1, parents.size()); + assertTrue(parents.contains(folderId)); + } } diff --git a/drive/snippets/drive_v2/src/test/java/TestRecoverDrives.java b/drive/snippets/drive_v2/src/test/java/TestRecoverDrives.java index c214234e..731f3f18 100644 --- a/drive/snippets/drive_v2/src/test/java/TestRecoverDrives.java +++ b/drive/snippets/drive_v2/src/test/java/TestRecoverDrives.java @@ -14,36 +14,35 @@ * limitations under the License. */ +import static org.junit.Assert.assertNotEquals; + import com.google.api.services.drive.model.Drive; import com.google.api.services.drive.model.Permission; import com.google.api.services.drive.model.PermissionList; -import org.junit.Test; - import java.io.IOException; import java.util.List; +import org.junit.Test; -import static org.junit.Assert.assertNotEquals; - -public class TestRecoverDrives extends BaseTest{ - @Test - public void recoverDrives() throws IOException { - String id = this.createOrphanedDrive(); - List results = RecoverDrive.recoverDrives( - "sbazyl@test.appsdevtesting.com"); - assertNotEquals(0, results.size()); - this.service.drives().delete(id).execute(); - } +public class TestRecoverDrives extends BaseTest { + @Test + public void recoverDrives() throws IOException { + String id = this.createOrphanedDrive(); + List results = RecoverDrive.recoverDrives( + "sbazyl@test.appsdevtesting.com"); + assertNotEquals(0, results.size()); + this.service.drives().delete(id).execute(); + } - private String createOrphanedDrive() throws IOException { - String driveId = CreateDrive.createDrive(); - PermissionList response = this.service.permissions().list(driveId) - .setSupportsAllDrives(true) - .execute(); - for (Permission permission : response.getItems()) { - this.service.permissions().delete(driveId, permission.getId()) - .setSupportsAllDrives(true) - .execute(); - } - return driveId; + private String createOrphanedDrive() throws IOException { + String driveId = CreateDrive.createDrive(); + PermissionList response = this.service.permissions().list(driveId) + .setSupportsAllDrives(true) + .execute(); + for (Permission permission : response.getItems()) { + this.service.permissions().delete(driveId, permission.getId()) + .setSupportsAllDrives(true) + .execute(); } + return driveId; + } } diff --git a/drive/snippets/drive_v2/src/test/java/TestRecoverTeamDrives.java b/drive/snippets/drive_v2/src/test/java/TestRecoverTeamDrives.java index 9b1a7892..c9b9a07f 100644 --- a/drive/snippets/drive_v2/src/test/java/TestRecoverTeamDrives.java +++ b/drive/snippets/drive_v2/src/test/java/TestRecoverTeamDrives.java @@ -14,35 +14,35 @@ * limitations under the License. */ +import static org.junit.Assert.assertNotEquals; + import com.google.api.services.drive.model.Permission; import com.google.api.services.drive.model.PermissionList; import com.google.api.services.drive.model.TeamDrive; -import org.junit.Test; - import java.io.IOException; import java.util.List; +import org.junit.Test; -import static org.junit.Assert.assertNotEquals; +public class TestRecoverTeamDrives extends BaseTest { + @Test + public void recoverTeamDrives() throws IOException { + String id = this.createOrphanedTeamDrive(); + List results = RecoverTeamDrive.recoverTeamDrives( + "sbazyl@test.appsdevtesting.com"); + assertNotEquals(0, results.size()); + this.service.teamdrives().delete(id).execute(); + } -public class TestRecoverTeamDrives extends BaseTest{ - @Test - public void recoverTeamDrives() throws IOException { - String id = this.createOrphanedTeamDrive(); - List results = RecoverTeamDrive.recoverTeamDrives( - "sbazyl@test.appsdevtesting.com"); - assertNotEquals(0, results.size()); - this.service.teamdrives().delete(id).execute(); - } - private String createOrphanedTeamDrive() throws IOException { - String teamDriveId = CreateTeamDrive.createTeamDrive(); - PermissionList response = this.service.permissions().list(teamDriveId) - .setSupportsTeamDrives(true) - .execute(); - for (Permission permission : response.getItems()) { - this.service.permissions().delete(teamDriveId, permission.getId()) - .setSupportsTeamDrives(true) - .execute(); - } - return teamDriveId; + private String createOrphanedTeamDrive() throws IOException { + String teamDriveId = CreateTeamDrive.createTeamDrive(); + PermissionList response = this.service.permissions().list(teamDriveId) + .setSupportsTeamDrives(true) + .execute(); + for (Permission permission : response.getItems()) { + this.service.permissions().delete(teamDriveId, permission.getId()) + .setSupportsTeamDrives(true) + .execute(); } + return teamDriveId; + } } diff --git a/drive/snippets/drive_v2/src/test/java/TestSearchFiles.java b/drive/snippets/drive_v2/src/test/java/TestSearchFiles.java index 6772cb40..280c6b9c 100644 --- a/drive/snippets/drive_v2/src/test/java/TestSearchFiles.java +++ b/drive/snippets/drive_v2/src/test/java/TestSearchFiles.java @@ -14,21 +14,20 @@ * limitations under the License. */ -import com.google.api.services.drive.model.File; -import org.junit.Test; +import static org.junit.Assert.assertNotEquals; +import com.google.api.services.drive.model.File; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.List; +import org.junit.Test; -import static org.junit.Assert.assertNotEquals; - -public class TestSearchFiles extends BaseTest{ - @Test - public void searchFiles() - throws IOException, GeneralSecurityException { - this.createTestBlob(); - List files = SearchFile.searchFile(); - assertNotEquals(0, files.size()); - } +public class TestSearchFiles extends BaseTest { + @Test + public void searchFiles() + throws IOException, GeneralSecurityException { + this.createTestBlob(); + List files = SearchFile.searchFile(); + assertNotEquals(0, files.size()); + } } diff --git a/drive/snippets/drive_v2/src/test/java/TestShareFile.java b/drive/snippets/drive_v2/src/test/java/TestShareFile.java index c47ec72c..167a7ec7 100644 --- a/drive/snippets/drive_v2/src/test/java/TestShareFile.java +++ b/drive/snippets/drive_v2/src/test/java/TestShareFile.java @@ -14,20 +14,19 @@ * limitations under the License. */ -import org.junit.Test; +import static org.junit.Assert.assertEquals; import java.io.IOException; import java.util.List; +import org.junit.Test; -import static org.junit.Assert.assertEquals; - -public class TestShareFile extends BaseTest{ - @Test - public void shareFile() throws IOException { - String fileId = this.createTestBlob(); - List ids = ShareFile.shareFile(fileId, - "user@test.appsdevtesting.com", - "test.appsdevtesting.com"); - assertEquals(2, ids.size()); - } +public class TestShareFile extends BaseTest { + @Test + public void shareFile() throws IOException { + String fileId = this.createTestBlob(); + List ids = ShareFile.shareFile(fileId, + "user@test.appsdevtesting.com", + "test.appsdevtesting.com"); + assertEquals(2, ids.size()); + } } diff --git a/drive/snippets/drive_v2/src/test/java/TestTouchFile.java b/drive/snippets/drive_v2/src/test/java/TestTouchFile.java index aecfabf4..9d7d80b8 100644 --- a/drive/snippets/drive_v2/src/test/java/TestTouchFile.java +++ b/drive/snippets/drive_v2/src/test/java/TestTouchFile.java @@ -14,19 +14,18 @@ * limitations under the License. */ -import org.junit.Test; +import static org.junit.Assert.assertEquals; import java.io.IOException; import java.security.GeneralSecurityException; +import org.junit.Test; -import static org.junit.Assert.assertEquals; - -public class TestTouchFile extends BaseTest{ - @Test - public void touchFile() throws IOException, GeneralSecurityException { - String id = this.createTestBlob(); - long now = System.currentTimeMillis(); - long modifiedTime = TouchFile.touchFile(id, now); - assertEquals(now, modifiedTime); - } +public class TestTouchFile extends BaseTest { + @Test + public void touchFile() throws IOException, GeneralSecurityException { + String id = this.createTestBlob(); + long now = System.currentTimeMillis(); + long modifiedTime = TouchFile.touchFile(id, now); + assertEquals(now, modifiedTime); + } } diff --git a/drive/snippets/drive_v2/src/test/java/TestUploadAppdata.java b/drive/snippets/drive_v2/src/test/java/TestUploadAppdata.java index d5cd5e9e..c9c13961 100644 --- a/drive/snippets/drive_v2/src/test/java/TestUploadAppdata.java +++ b/drive/snippets/drive_v2/src/test/java/TestUploadAppdata.java @@ -12,20 +12,19 @@ // See the License for the specific language governing permissions and // limitations under the License. -import org.junit.Test; +import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.security.GeneralSecurityException; - -import static org.junit.Assert.assertNotNull; +import org.junit.Test; // Unit test class for testing of UploadAppData snippet -public class TestUploadAppdata extends BaseTest{ - @Test - public void uploadAppData() - throws IOException, GeneralSecurityException { - String id = UploadAppData.uploadAppData(); - assertNotNull(id); - deleteFileOnCleanup(id); - } +public class TestUploadAppdata extends BaseTest { + @Test + public void uploadAppData() + throws IOException, GeneralSecurityException { + String id = UploadAppData.uploadAppData(); + assertNotNull(id); + deleteFileOnCleanup(id); + } } diff --git a/drive/snippets/drive_v2/src/test/java/TestUploadBasic.java b/drive/snippets/drive_v2/src/test/java/TestUploadBasic.java index 79617d8d..f083eb65 100644 --- a/drive/snippets/drive_v2/src/test/java/TestUploadBasic.java +++ b/drive/snippets/drive_v2/src/test/java/TestUploadBasic.java @@ -14,18 +14,17 @@ * limitations under the License. */ -import org.junit.Test; +import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.security.GeneralSecurityException; - -import static org.junit.Assert.assertNotNull; +import org.junit.Test; public class TestUploadBasic { - @Test - public void uploadBasic() throws IOException, GeneralSecurityException { - String id = UploadBasic.uploadBasic(); - assertNotNull(id); - } + @Test + public void uploadBasic() throws IOException, GeneralSecurityException { + String id = UploadBasic.uploadBasic(); + assertNotNull(id); + } } diff --git a/drive/snippets/drive_v2/src/test/java/TestUploadRevision.java b/drive/snippets/drive_v2/src/test/java/TestUploadRevision.java index de932e4f..ea7e7eea 100644 --- a/drive/snippets/drive_v2/src/test/java/TestUploadRevision.java +++ b/drive/snippets/drive_v2/src/test/java/TestUploadRevision.java @@ -14,21 +14,20 @@ * limitations under the License. */ -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.security.GeneralSecurityException; +import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -public class TestUploadRevision extends BaseTest{ - @Test - public void uploadRevision() throws IOException, GeneralSecurityException { - String id = UploadBasic.uploadBasic(); - assertNotNull(id); - deleteFileOnCleanup(id); - String id2 = UploadRevision.uploadRevision(id); - assertEquals(id, id2); - } +public class TestUploadRevision extends BaseTest { + @Test + public void uploadRevision() throws IOException, GeneralSecurityException { + String id = UploadBasic.uploadBasic(); + assertNotNull(id); + deleteFileOnCleanup(id); + String id2 = UploadRevision.uploadRevision(id); + assertEquals(id, id2); + } } diff --git a/drive/snippets/drive_v2/src/test/java/TestUploadToFolder.java b/drive/snippets/drive_v2/src/test/java/TestUploadToFolder.java index 815982d9..fcec0691 100644 --- a/drive/snippets/drive_v2/src/test/java/TestUploadToFolder.java +++ b/drive/snippets/drive_v2/src/test/java/TestUploadToFolder.java @@ -14,21 +14,20 @@ * limitations under the License. */ -import com.google.api.services.drive.model.File; -import org.junit.Test; +import static org.junit.Assert.assertTrue; +import com.google.api.services.drive.model.File; import java.io.IOException; import java.security.GeneralSecurityException; - -import static org.junit.Assert.assertTrue; +import org.junit.Test; public class TestUploadToFolder extends BaseTest { - @Test - public void uploadToFolder() throws IOException, GeneralSecurityException { - String folderId = CreateFolder.createFolder(); - File file = UploadToFolder.uploadToFolder(folderId); - assertTrue(file.getParents().get(0).getId().equals(folderId)); - deleteFileOnCleanup(file.getId()); - deleteFileOnCleanup(folderId); - } + @Test + public void uploadToFolder() throws IOException, GeneralSecurityException { + String folderId = CreateFolder.createFolder(); + File file = UploadToFolder.uploadToFolder(folderId); + assertTrue(file.getParents().get(0).getId().equals(folderId)); + deleteFileOnCleanup(file.getId()); + deleteFileOnCleanup(folderId); + } } diff --git a/drive/snippets/drive_v2/src/test/java/TestUploadWithConversion.java b/drive/snippets/drive_v2/src/test/java/TestUploadWithConversion.java index ae3a889c..11b5f2f9 100644 --- a/drive/snippets/drive_v2/src/test/java/TestUploadWithConversion.java +++ b/drive/snippets/drive_v2/src/test/java/TestUploadWithConversion.java @@ -14,19 +14,18 @@ * limitations under the License. */ -import org.junit.Test; +import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.security.GeneralSecurityException; +import org.junit.Test; -import static org.junit.Assert.assertNotNull; - -public class TestUploadWithConversion extends BaseTest{ - @Test - public void uploadWithConversion() - throws IOException, GeneralSecurityException { - String id = UploadWithConversion.uploadWithConversion(); - assertNotNull(id); - deleteFileOnCleanup(id); - } +public class TestUploadWithConversion extends BaseTest { + @Test + public void uploadWithConversion() + throws IOException, GeneralSecurityException { + String id = UploadWithConversion.uploadWithConversion(); + assertNotNull(id); + deleteFileOnCleanup(id); + } } diff --git a/drive/snippets/drive_v3/src/main/java/AppDataSnippets.java b/drive/snippets/drive_v3/src/main/java/AppDataSnippets.java index 975aafb6..5f75f5c4 100644 --- a/drive/snippets/drive_v3/src/main/java/AppDataSnippets.java +++ b/drive/snippets/drive_v3/src/main/java/AppDataSnippets.java @@ -18,7 +18,6 @@ import com.google.api.services.drive.Drive; import com.google.api.services.drive.model.File; import com.google.api.services.drive.model.FileList; - import java.io.IOException; import java.util.Collections; diff --git a/drive/snippets/drive_v3/src/main/java/ChangeSnippets.java b/drive/snippets/drive_v3/src/main/java/ChangeSnippets.java index 5710478b..141991bc 100644 --- a/drive/snippets/drive_v3/src/main/java/ChangeSnippets.java +++ b/drive/snippets/drive_v3/src/main/java/ChangeSnippets.java @@ -18,7 +18,6 @@ import com.google.api.services.drive.model.Change; import com.google.api.services.drive.model.ChangeList; import com.google.api.services.drive.model.StartPageToken; - import java.io.IOException; public class ChangeSnippets { diff --git a/drive/snippets/drive_v3/src/main/java/CreateDrive.java b/drive/snippets/drive_v3/src/main/java/CreateDrive.java index be69cbec..ceb53f9b 100644 --- a/drive/snippets/drive_v3/src/main/java/CreateDrive.java +++ b/drive/snippets/drive_v3/src/main/java/CreateDrive.java @@ -21,7 +21,6 @@ import com.google.api.services.drive.model.Drive; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.Arrays; import java.util.UUID; @@ -29,42 +28,45 @@ /* class to demonstrate use-case of Drive's create drive. */ public class CreateDrive { - /** - * Create a drive. - * @return Newly created drive id. - * @throws IOException if service account credentials file not found. - */ - public static String createDrive() throws IOException { + /** + * Create a drive. + * + * @return Newly created drive id. + * @throws IOException if service account credentials file not found. + */ + public static String createDrive() 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(Arrays.asList(DriveScopes.DRIVE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = + GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - com.google.api.services.drive.Drive service = new com.google.api.services.drive.Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); + // Build a new authorized API client service. + com.google.api.services.drive.Drive service = + new com.google.api.services.drive.Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); - Drive driveMetadata = new Drive(); - driveMetadata.setName("Project Resources"); - String requestId = UUID.randomUUID().toString(); - try { - Drive drive = service.drives().create(requestId, - driveMetadata) - .execute(); - System.out.println("Drive ID: " + drive.getId()); + Drive driveMetadata = new Drive(); + driveMetadata.setName("Project Resources"); + String requestId = UUID.randomUUID().toString(); + try { + Drive drive = service.drives().create(requestId, + driveMetadata) + .execute(); + System.out.println("Drive ID: " + drive.getId()); - return drive.getId(); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to create drive: " + e.getDetails()); - throw e; - } + return drive.getId(); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to create drive: " + e.getDetails()); + throw e; } + } } // [END drive_create_drive] diff --git a/drive/snippets/drive_v3/src/main/java/CreateFolder.java b/drive/snippets/drive_v3/src/main/java/CreateFolder.java index c9ee24b8..e907cb7d 100644 --- a/drive/snippets/drive_v3/src/main/java/CreateFolder.java +++ b/drive/snippets/drive_v3/src/main/java/CreateFolder.java @@ -23,7 +23,6 @@ import com.google.api.services.drive.model.File; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.Arrays; @@ -31,40 +30,42 @@ public class CreateFolder { - /** - * Create new folder. - * @return Inserted folder id if successful, {@code null} otherwise. - * @throws IOException if service account credentials file not found. - */ - public static String createFolder() 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + /** + * Create new folder. + * + * @return Inserted folder id if successful, {@code null} otherwise. + * @throws IOException if service account credentials file not found. + */ + public static String createFolder() 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(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); - // File's metadata. - File fileMetadata = new File(); - fileMetadata.setName("Test"); - fileMetadata.setMimeType("application/vnd.google-apps.folder"); - try { - File file = service.files().create(fileMetadata) - .setFields("id") - .execute(); - System.out.println("Folder ID: " + file.getId()); - return file.getId(); - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to create folder: " + e.getDetails()); - throw e; - } + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); + // File's metadata. + File fileMetadata = new File(); + fileMetadata.setName("Test"); + fileMetadata.setMimeType("application/vnd.google-apps.folder"); + try { + File file = service.files().create(fileMetadata) + .setFields("id") + .execute(); + System.out.println("Folder ID: " + file.getId()); + return file.getId(); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to create folder: " + e.getDetails()); + throw e; } + } } // [END drive_create_folder] diff --git a/drive/snippets/drive_v3/src/main/java/CreateShortcut.java b/drive/snippets/drive_v3/src/main/java/CreateShortcut.java index d75f104e..12acc6e7 100644 --- a/drive/snippets/drive_v3/src/main/java/CreateShortcut.java +++ b/drive/snippets/drive_v3/src/main/java/CreateShortcut.java @@ -23,46 +23,47 @@ import com.google.api.services.drive.model.File; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.Arrays; /* Class to demonstrate Drive's create shortcut use-case */ public class CreateShortcut { - /** - * Creates shortcut for file. - * @throws IOException if service account credentials file not found. - */ - public static String createShortcut() throws IOException{ + /** + * Creates shortcut for file. + * + * @throws IOException if service account credentials file not found. + */ + public static String createShortcut() 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); - try { - // Create Shortcut for file. - File fileMetadata = new File(); - fileMetadata.setName("Project plan"); - fileMetadata.setMimeType("application/vnd.google-apps.drive-sdk"); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); + try { + // Create Shortcut for file. + File fileMetadata = new File(); + fileMetadata.setName("Project plan"); + fileMetadata.setMimeType("application/vnd.google-apps.drive-sdk"); - File file = service.files().create(fileMetadata) - .setFields("id") - .execute(); - System.out.println("File ID: " + file.getId()); - return file.getId(); - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to create shortcut: " + e.getDetails()); - throw e; - } + File file = service.files().create(fileMetadata) + .setFields("id") + .execute(); + System.out.println("File ID: " + file.getId()); + return file.getId(); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to create shortcut: " + e.getDetails()); + throw e; } + } } // [END drive_create_shortcut] diff --git a/drive/snippets/drive_v3/src/main/java/DownloadFile.java b/drive/snippets/drive_v3/src/main/java/DownloadFile.java index 0931acc5..2098d1a9 100644 --- a/drive/snippets/drive_v3/src/main/java/DownloadFile.java +++ b/drive/snippets/drive_v3/src/main/java/DownloadFile.java @@ -22,7 +22,6 @@ import com.google.api.services.drive.DriveScopes; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; @@ -31,39 +30,41 @@ /* Class to demonstrate use-case of drive's download file. */ public class DownloadFile { - /** - * Download a Document file in PDF format. - * @param realFileId file ID of any workspace document format file. - * @return byte array stream if successful, {@code null} otherwise. - * @throws IOException if service account credentials file not found. - */ - public static ByteArrayOutputStream downloadFile(String realFileId) throws IOException{ + /** + * Download a Document file in PDF format. + * + * @param realFileId file ID of any workspace document format file. + * @return byte array stream if successful, {@code null} otherwise. + * @throws IOException if service account credentials file not found. + */ + public static ByteArrayOutputStream downloadFile(String realFileId) 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); - try { - OutputStream outputStream = new ByteArrayOutputStream(); + try { + OutputStream outputStream = new ByteArrayOutputStream(); - service.files().get(realFileId) - .executeMediaAndDownloadTo(outputStream); + service.files().get(realFileId) + .executeMediaAndDownloadTo(outputStream); - return (ByteArrayOutputStream) outputStream; - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to move file: " + e.getDetails()); - throw e; - } + return (ByteArrayOutputStream) outputStream; + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to move file: " + e.getDetails()); + throw e; } + } } // [END drive_download_file] diff --git a/drive/snippets/drive_v3/src/main/java/DriveSnippets.java b/drive/snippets/drive_v3/src/main/java/DriveSnippets.java index 3bedd15e..9fa22647 100644 --- a/drive/snippets/drive_v3/src/main/java/DriveSnippets.java +++ b/drive/snippets/drive_v3/src/main/java/DriveSnippets.java @@ -14,12 +14,9 @@ * limitations under the License. */ -import com.google.api.client.http.FileContent; -//import com.google.api.services.drive.Drive; import com.google.api.services.drive.model.Drive; import com.google.api.services.drive.model.DriveList; import com.google.api.services.drive.model.Permission; - import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -39,7 +36,7 @@ public String createDrive() throws IOException { driveMetadata.setName("Project Resources"); String requestId = UUID.randomUUID().toString(); Drive drive = driveService.drives().create(requestId, - driveMetadata) + driveMetadata) .execute(); System.out.println("Drive ID: " + drive.getId()); // [END createDrive] diff --git a/drive/snippets/drive_v3/src/main/java/ExportPdf.java b/drive/snippets/drive_v3/src/main/java/ExportPdf.java index 16d86539..789e232a 100644 --- a/drive/snippets/drive_v3/src/main/java/ExportPdf.java +++ b/drive/snippets/drive_v3/src/main/java/ExportPdf.java @@ -22,7 +22,6 @@ import com.google.api.services.drive.DriveScopes; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; @@ -31,38 +30,40 @@ /* Class to demonstrate use-case of drive's export pdf. */ public class ExportPdf { - /** - * Download a Document file in PDF format. - * @param realFileId file ID of any workspace document format file. - * @return byte array stream if successful, {@code null} otherwise. - * @throws IOException if service account credentials file not found. - */ - public static ByteArrayOutputStream exportPdf(String realFileId) 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + /** + * Download a Document file in PDF format. + * + * @param realFileId file ID of any workspace document format file. + * @return byte array stream if successful, {@code null} otherwise. + * @throws IOException if service account credentials file not found. + */ + public static ByteArrayOutputStream exportPdf(String realFileId) 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(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); - OutputStream outputStream = new ByteArrayOutputStream(); - try { - service.files().export(realFileId, "application/pdf") - .executeMediaAndDownloadTo(outputStream); + OutputStream outputStream = new ByteArrayOutputStream(); + try { + service.files().export(realFileId, "application/pdf") + .executeMediaAndDownloadTo(outputStream); - return (ByteArrayOutputStream) outputStream; - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to export file: " + e.getDetails()); - throw e; - } + return (ByteArrayOutputStream) outputStream; + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to export file: " + e.getDetails()); + throw e; } + } } // [END drive_export_pdf] diff --git a/drive/snippets/drive_v3/src/main/java/FetchAppDataFolder.java b/drive/snippets/drive_v3/src/main/java/FetchAppDataFolder.java index dd00bdf4..d80db884 100644 --- a/drive/snippets/drive_v3/src/main/java/FetchAppDataFolder.java +++ b/drive/snippets/drive_v3/src/main/java/FetchAppDataFolder.java @@ -22,47 +22,50 @@ import com.google.api.services.drive.model.File; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.Arrays; -/** Class to demonstrate use-case of list out application data folder and prints folder Id. */ +/** + * Class to demonstrate use-case of list out application data folder and prints folder Id. + */ public class FetchAppDataFolder { - /** - * Fetches appDataFolder and prints it's folder id. - * @return Application data folder's ID. - */ - public static String fetchAppDataFolder() throws IOException { + /** + * Fetches appDataFolder and prints it's folder id. + * + * @return Application data folder's ID. + */ + public static String fetchAppDataFolder() 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 = null; - try { - credentials = GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE_APPDATA)); - } catch (IOException e) { - e.printStackTrace(); - } - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = null; + try { + credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Arrays.asList(DriveScopes.DRIVE_APPDATA)); + } catch (IOException e) { + e.printStackTrace(); + } + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); - try { - File file = service.files().get("appDataFolder") - .setFields("id") - .execute(); - System.out.println("Folder ID: " + file.getId()); - return file.getId(); - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to fetch appdata folder: " + e.getDetails()); - throw e; - } + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); + try { + File file = service.files().get("appDataFolder") + .setFields("id") + .execute(); + System.out.println("Folder ID: " + file.getId()); + return file.getId(); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to fetch appdata folder: " + e.getDetails()); + throw e; } + } } // [END drive_fetch_appdata_folder] diff --git a/drive/snippets/drive_v3/src/main/java/FetchChanges.java b/drive/snippets/drive_v3/src/main/java/FetchChanges.java index aa921837..49a2319e 100644 --- a/drive/snippets/drive_v3/src/main/java/FetchChanges.java +++ b/drive/snippets/drive_v3/src/main/java/FetchChanges.java @@ -22,57 +22,58 @@ import com.google.api.services.drive.model.ChangeList; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.Arrays; /* Class to demonstrate use-case of Drive's fetch changes in file. */ public class FetchChanges { - /** - * Retrieve the list of changes for the currently authenticated user. - * @param savedStartPageToken Last saved start token for this user. - * @return Saved token after last page. - * @throws IOException if file is not found - */ - public static String fetchChanges(String savedStartPageToken) throws IOException { + /** + * Retrieve the list of changes for the currently authenticated user. + * + * @param savedStartPageToken Last saved start token for this user. + * @return Saved token after last page. + * @throws IOException if file is not found + */ + public static String fetchChanges(String savedStartPageToken) 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); - - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); - try { - // Begin with our last saved start token for this user or the - // current token from getStartPageToken() - String pageToken = savedStartPageToken; - while (pageToken != null) { - ChangeList changes = service.changes().list(pageToken) - .execute(); - for (com.google.api.services.drive.model.Change change : changes.getChanges()) { - // Process change - System.out.println("Change found for file: " + change.getFileId()); - } - if (changes.getNewStartPageToken() != null) { - // Last page, save this token for the next polling interval - savedStartPageToken = changes.getNewStartPageToken(); - } - pageToken = changes.getNextPageToken(); - } + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - return savedStartPageToken; - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to fetch changes: " + e.getDetails()); - throw e; + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); + try { + // Begin with our last saved start token for this user or the + // current token from getStartPageToken() + String pageToken = savedStartPageToken; + while (pageToken != null) { + ChangeList changes = service.changes().list(pageToken) + .execute(); + for (com.google.api.services.drive.model.Change change : changes.getChanges()) { + // Process change + System.out.println("Change found for file: " + change.getFileId()); } + if (changes.getNewStartPageToken() != null) { + // Last page, save this token for the next polling interval + savedStartPageToken = changes.getNewStartPageToken(); + } + pageToken = changes.getNextPageToken(); + } + + return savedStartPageToken; + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to fetch changes: " + e.getDetails()); + throw e; } + } } // [END drive_fetch_changes] diff --git a/drive/snippets/drive_v3/src/main/java/FetchStartPageToken.java b/drive/snippets/drive_v3/src/main/java/FetchStartPageToken.java index de8a2da3..a3445c7a 100644 --- a/drive/snippets/drive_v3/src/main/java/FetchStartPageToken.java +++ b/drive/snippets/drive_v3/src/main/java/FetchStartPageToken.java @@ -22,45 +22,46 @@ import com.google.api.services.drive.model.StartPageToken; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.Arrays; /* Class to demonstrate use-case of Drive's fetch start page token */ public class FetchStartPageToken { - /** - * Retrieve the start page token for the first time. - * @return Start page token as String. - * @throws IOException if file is not found - */ - public static String fetchStartPageToken() throws IOException { + /** + * Retrieve the start page token for the first time. + * + * @return Start page token as String. + * @throws IOException if file is not found + */ + public static String fetchStartPageToken() 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); - try { - StartPageToken response = service.changes() - .getStartPageToken().execute(); - System.out.println("Start token: " + response.getStartPageToken()); + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); + try { + StartPageToken response = service.changes() + .getStartPageToken().execute(); + System.out.println("Start token: " + response.getStartPageToken()); - return response.getStartPageToken(); - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to fetch start page token: " + e.getDetails()); - throw e; - } + return response.getStartPageToken(); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to fetch start page token: " + e.getDetails()); + throw e; } + } } // [END drive_fetch_start_page_token] diff --git a/drive/snippets/drive_v3/src/main/java/ListAppData.java b/drive/snippets/drive_v3/src/main/java/ListAppData.java index 1f611d3c..96192020 100644 --- a/drive/snippets/drive_v3/src/main/java/ListAppData.java +++ b/drive/snippets/drive_v3/src/main/java/ListAppData.java @@ -23,54 +23,57 @@ import com.google.api.services.drive.model.FileList; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.Arrays; -/** Class to demonstrate use-case of list 10 files in the application data folder. */ +/** + * Class to demonstrate use-case of list 10 files in the application data folder. + */ public class ListAppData { - /** - * list down files in the application data folder. - * @return list of 10 files. - */ - public static FileList listAppData() throws IOException { + /** + * list down files in the application data folder. + * + * @return list of 10 files. + */ + public static FileList listAppData() 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 = null; - try { - credentials = GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE_APPDATA)); - } catch (IOException e) { - e.printStackTrace(); - } - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = null; + try { + credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Arrays.asList(DriveScopes.DRIVE_APPDATA)); + } catch (IOException e) { + e.printStackTrace(); + } + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); - try { - FileList files = service.files().list() - .setSpaces("appDataFolder") - .setFields("nextPageToken, files(id, name)") - .setPageSize(10) - .execute(); - for (File file : files.getFiles()) { - System.out.printf("Found file: %s (%s)\n", - file.getName(), file.getId()); - } + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); + try { + FileList files = service.files().list() + .setSpaces("appDataFolder") + .setFields("nextPageToken, files(id, name)") + .setPageSize(10) + .execute(); + for (File file : files.getFiles()) { + System.out.printf("Found file: %s (%s)\n", + file.getName(), file.getId()); + } - return files; - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to list files: " + e.getDetails()); - throw e; - } + return files; + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to list files: " + e.getDetails()); + throw e; } + } } // [END drive_list_appdata] \ No newline at end of file diff --git a/drive/snippets/drive_v3/src/main/java/MoveFileToFolder.java b/drive/snippets/drive_v3/src/main/java/MoveFileToFolder.java index 4b5603e8..bba31a82 100644 --- a/drive/snippets/drive_v3/src/main/java/MoveFileToFolder.java +++ b/drive/snippets/drive_v3/src/main/java/MoveFileToFolder.java @@ -24,7 +24,6 @@ import com.google.api.services.drive.model.File; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.Arrays; import java.util.List; @@ -33,49 +32,50 @@ public class MoveFileToFolder { - /** - * @param fileId Id of file to be moved. - * @param folderId Id of folder where the fill will be moved. - * @return list of parent ids for the file. - * */ - public static List moveFileToFolder(String fileId, String folderId) - throws IOException { + /** + * @param fileId Id of file to be moved. + * @param folderId Id of folder where the fill will be moved. + * @return list of parent ids for the file. + */ + public static List moveFileToFolder(String fileId, String folderId) + 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); - // Retrieve the existing parents to remove - File file = service.files().get(fileId) - .setFields("parents") - .execute(); - StringBuilder previousParents = new StringBuilder(); - for (String parent : file.getParents()) { - previousParents.append(parent); - previousParents.append(','); - } - try{ - // Move the file to the new folder - file = service.files().update(fileId, null) - .setAddParents(folderId) - .setRemoveParents(previousParents.toString()) - .setFields("id, parents") - .execute(); + // Retrieve the existing parents to remove + File file = service.files().get(fileId) + .setFields("parents") + .execute(); + StringBuilder previousParents = new StringBuilder(); + for (String parent : file.getParents()) { + previousParents.append(parent); + previousParents.append(','); + } + try { + // Move the file to the new folder + file = service.files().update(fileId, null) + .setAddParents(folderId) + .setRemoveParents(previousParents.toString()) + .setFields("id, parents") + .execute(); - return file.getParents(); - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to move file: " + e.getDetails()); - throw e; - } + return file.getParents(); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to move file: " + e.getDetails()); + throw e; } + } } // [END drive_move_file_to_folder] diff --git a/drive/snippets/drive_v3/src/main/java/RecoverDrive.java b/drive/snippets/drive_v3/src/main/java/RecoverDrive.java index adf8162e..87fd32a8 100644 --- a/drive/snippets/drive_v3/src/main/java/RecoverDrive.java +++ b/drive/snippets/drive_v3/src/main/java/RecoverDrive.java @@ -23,7 +23,6 @@ import com.google.api.services.drive.model.Permission; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; @@ -32,74 +31,77 @@ /* class to demonstrate use-case of Drive's shared drive without an organizer. */ public class RecoverDrive { - /** - * Find all shared drives without an organizer and add one. - * @param realUser User's email id. - * @return All shared drives without an organizer. - * @throws IOException if shared drive not found. - */ - public static List recoverDrives(String realUser) - throws IOException { + /** + * Find all shared drives without an organizer and add one. + * + * @param realUser User's email id. + * @return All shared drives without an organizer. + * @throws IOException if shared drive not found. + */ + public static List recoverDrives(String realUser) + 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(Arrays.asList(DriveScopes.DRIVE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = + GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - com.google.api.services.drive.Drive service = new com.google.api.services.drive.Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); - List drives = new ArrayList(); + // Build a new authorized API client service. + com.google.api.services.drive.Drive service = + new com.google.api.services.drive.Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); + List drives = new ArrayList(); - // Find all shared drives without an organizer and add one. - // Note: This example does not capture all cases. Shared drives - // that have an empty group as the sole organizer, or an - // organizer outside the organization are not captured. A - // more exhaustive approach would evaluate each shared drive - // and the associated permissions and groups to ensure an active - // organizer is assigned. - String pageToken = null; - Permission newOrganizerPermission = new Permission() - .setType("user") - .setRole("organizer"); + // Find all shared drives without an organizer and add one. + // Note: This example does not capture all cases. Shared drives + // that have an empty group as the sole organizer, or an + // organizer outside the organization are not captured. A + // more exhaustive approach would evaluate each shared drive + // and the associated permissions and groups to ensure an active + // organizer is assigned. + String pageToken = null; + Permission newOrganizerPermission = new Permission() + .setType("user") + .setRole("organizer"); - newOrganizerPermission.setEmailAddress(realUser); + newOrganizerPermission.setEmailAddress(realUser); - do { - DriveList result = service.drives().list() - .setQ("organizerCount = 0") - .setFields("nextPageToken, drives(id, name)") - .setUseDomainAdminAccess(true) - .setPageToken(pageToken) - .execute(); - for (Drive drive : result.getDrives()) { - System.out.printf("Found drive without organizer: %s (%s)\n", - drive.getName(), drive.getId()); - // Note: For improved efficiency, consider batching - // permission insert requests - Permission permissionResult = service.permissions() - .create(drive.getId(), newOrganizerPermission) - .setUseDomainAdminAccess(true) - .setSupportsAllDrives(true) - .setFields("id") - .execute(); - System.out.printf("Added organizer permission: %s\n", - permissionResult.getId()); + do { + DriveList result = service.drives().list() + .setQ("organizerCount = 0") + .setFields("nextPageToken, drives(id, name)") + .setUseDomainAdminAccess(true) + .setPageToken(pageToken) + .execute(); + for (Drive drive : result.getDrives()) { + System.out.printf("Found drive without organizer: %s (%s)\n", + drive.getName(), drive.getId()); + // Note: For improved efficiency, consider batching + // permission insert requests + Permission permissionResult = service.permissions() + .create(drive.getId(), newOrganizerPermission) + .setUseDomainAdminAccess(true) + .setSupportsAllDrives(true) + .setFields("id") + .execute(); + System.out.printf("Added organizer permission: %s\n", + permissionResult.getId()); - } + } - drives.addAll(result.getDrives()); + drives.addAll(result.getDrives()); - pageToken = result.getNextPageToken(); - } while (pageToken != null); + pageToken = result.getNextPageToken(); + } while (pageToken != null); - return drives; - } + return drives; + } } // [END drive_recover_drives] diff --git a/drive/snippets/drive_v3/src/main/java/SearchFile.java b/drive/snippets/drive_v3/src/main/java/SearchFile.java index 632bf4ae..08f574b1 100644 --- a/drive/snippets/drive_v3/src/main/java/SearchFile.java +++ b/drive/snippets/drive_v3/src/main/java/SearchFile.java @@ -23,7 +23,6 @@ import com.google.api.services.drive.model.FileList; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; @@ -32,47 +31,49 @@ /* Class to demonstrate use-case of search files. */ public class SearchFile { - /** - * Search for specific set of files. - * @return search result list. - * @throws IOException if service account credentials file not found. - */ - public static List searchFile() throws IOException{ + /** + * Search for specific set of files. + * + * @return search result list. + * @throws IOException if service account credentials file not found. + */ + public static List searchFile() 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); - List files = new ArrayList(); + List files = new ArrayList(); - String pageToken = null; - do { - FileList result = service.files().list() - .setQ("mimeType='image/jpeg'") - .setSpaces("drive") - .setFields("nextPageToken, items(id, title)") - .setPageToken(pageToken) - .execute(); - for (File file : result.getFiles()) { - System.out.printf("Found file: %s (%s)\n", - file.getName(), file.getId()); - } + String pageToken = null; + do { + FileList result = service.files().list() + .setQ("mimeType='image/jpeg'") + .setSpaces("drive") + .setFields("nextPageToken, items(id, title)") + .setPageToken(pageToken) + .execute(); + for (File file : result.getFiles()) { + System.out.printf("Found file: %s (%s)\n", + file.getName(), file.getId()); + } - files.addAll(result.getFiles()); + files.addAll(result.getFiles()); - pageToken = result.getNextPageToken(); - } while (pageToken != null); + pageToken = result.getNextPageToken(); + } while (pageToken != null); - return files; - } + return files; + } } // [END drive_search_files] diff --git a/drive/snippets/drive_v3/src/main/java/ShareFile.java b/drive/snippets/drive_v3/src/main/java/ShareFile.java index 899edfef..438440df 100644 --- a/drive/snippets/drive_v3/src/main/java/ShareFile.java +++ b/drive/snippets/drive_v3/src/main/java/ShareFile.java @@ -27,7 +27,6 @@ import com.google.api.services.drive.model.Permission; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; @@ -36,80 +35,83 @@ /* Class to demonstrate use-case of modify permissions. */ public class ShareFile { - /** - * Batch permission modification. - * realFileId file Id. - * realUser User Id. - * realDomain Domain of the user ID. - * @return list of modified permissions if successful, {@code null} otherwise. - * @throws IOException if service account credentials file not found. - */ - public static List shareFile(String realFileId, String realUser, String realDomain) throws IOException{ + /** + * Batch permission modification. + * realFileId file Id. + * realUser User Id. + * realDomain Domain of the user ID. + * + * @return list of modified permissions if successful, {@code null} otherwise. + * @throws IOException if service account credentials file not found. + */ + public static List shareFile(String realFileId, String realUser, String realDomain) + 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.application*/ - GoogleCredentials credentials = GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); - - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); - - final List ids = new ArrayList(); - - - JsonBatchCallback callback = new JsonBatchCallback() { - @Override - public void onFailure(GoogleJsonError e, - HttpHeaders responseHeaders) - throws IOException { - // Handle error - System.err.println(e.getMessage()); - } - - @Override - public void onSuccess(Permission permission, - HttpHeaders responseHeaders) - throws IOException { - System.out.println("Permission ID: " + permission.getId()); - - ids.add(permission.getId()); - - } - }; - BatchRequest batch = service.batch(); - Permission userPermission = new Permission() - .setType("user") - .setRole("writer"); - - userPermission.setEmailAddress(realUser); - try { - service.permissions().create(realFileId, userPermission) - .setFields("id") - .queue(batch, callback); - - Permission domainPermission = new Permission() - .setType("domain") - .setRole("reader"); - - domainPermission.setDomain(realDomain); - - service.permissions().create(realFileId, domainPermission) - .setFields("id") - .queue(batch, callback); - - batch.execute(); - - return ids; - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to modify permission: " + e.getDetails()); - throw e; - } + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); + + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); + + final List ids = new ArrayList(); + + + JsonBatchCallback callback = new JsonBatchCallback() { + @Override + public void onFailure(GoogleJsonError e, + HttpHeaders responseHeaders) + throws IOException { + // Handle error + System.err.println(e.getMessage()); + } + + @Override + public void onSuccess(Permission permission, + HttpHeaders responseHeaders) + throws IOException { + System.out.println("Permission ID: " + permission.getId()); + + ids.add(permission.getId()); + + } + }; + BatchRequest batch = service.batch(); + Permission userPermission = new Permission() + .setType("user") + .setRole("writer"); + + userPermission.setEmailAddress(realUser); + try { + service.permissions().create(realFileId, userPermission) + .setFields("id") + .queue(batch, callback); + + Permission domainPermission = new Permission() + .setType("domain") + .setRole("reader"); + + domainPermission.setDomain(realDomain); + + service.permissions().create(realFileId, domainPermission) + .setFields("id") + .queue(batch, callback); + + batch.execute(); + + return ids; + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to modify permission: " + e.getDetails()); + throw e; } + } } // [END drive_share_file] diff --git a/drive/snippets/drive_v3/src/main/java/TouchFile.java b/drive/snippets/drive_v3/src/main/java/TouchFile.java index 2729133c..138a7e18 100644 --- a/drive/snippets/drive_v3/src/main/java/TouchFile.java +++ b/drive/snippets/drive_v3/src/main/java/TouchFile.java @@ -24,7 +24,6 @@ import com.google.api.services.drive.model.File; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.Arrays; @@ -32,46 +31,47 @@ public class TouchFile { - /** - * @param realFileId Id of file to be modified. - * @param realTimestamp Timestamp in miliseconds. - * @return long file's latest modification date value. - * @throws IOException if service account credentials file not found. - * */ - public static long touchFile(String realFileId, long realTimestamp) - throws IOException { + /** + * @param realFileId Id of file to be modified. + * @param realTimestamp Timestamp in miliseconds. + * @return long file's latest modification date value. + * @throws IOException if service account credentials file not found. + */ + public static long touchFile(String realFileId, long realTimestamp) + 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); - String fileId = "1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ"; - File fileMetadata = new File(); - fileMetadata.setModifiedTime(new DateTime(System.currentTimeMillis())); + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); + String fileId = "1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ"; + File fileMetadata = new File(); + fileMetadata.setModifiedTime(new DateTime(System.currentTimeMillis())); - fileId = realFileId; - fileMetadata.setModifiedTime(new DateTime(realTimestamp)); + fileId = realFileId; + fileMetadata.setModifiedTime(new DateTime(realTimestamp)); - try { - File file = service.files().update(fileId, fileMetadata) - .setFields("id, modifiedDate") - .execute(); - System.out.println("Modified time: " + file.getModifiedTime()); - return file.getModifiedTime().getValue(); - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to move file: " + e.getDetails()); - throw e; - } + try { + File file = service.files().update(fileId, fileMetadata) + .setFields("id, modifiedDate") + .execute(); + System.out.println("Modified time: " + file.getModifiedTime()); + return file.getModifiedTime().getValue(); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to move file: " + e.getDetails()); + throw e; } + } } // [END drive_touch_file] diff --git a/drive/snippets/drive_v3/src/main/java/UploadAppData.java b/drive/snippets/drive_v3/src/main/java/UploadAppData.java index 8192f009..4ed8e934 100644 --- a/drive/snippets/drive_v3/src/main/java/UploadAppData.java +++ b/drive/snippets/drive_v3/src/main/java/UploadAppData.java @@ -23,55 +23,58 @@ import com.google.api.services.drive.model.File; 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 use-case of create file in the application data folder. */ +/** + * Class to demonstrate use-case of create file in the application data folder. + */ public class UploadAppData { - /** - * Creates a file in the application data folder. - * @return Created file's Id. - */ - public static String uploadAppData() throws IOException { + /** + * Creates a file in the application data folder. + * + * @return Created file's Id. + */ + public static String uploadAppData() 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 = null; - try { - credentials = GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE_APPDATA)); - } catch (IOException e) { - e.printStackTrace(); - } - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = null; + try { + credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Arrays.asList(DriveScopes.DRIVE_APPDATA)); + } catch (IOException e) { + e.printStackTrace(); + } + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); - try { - // File's metadata. - File fileMetadata = new File(); - fileMetadata.setName("config.json"); - fileMetadata.setParents(Collections.singletonList("appDataFolder")); - java.io.File filePath = new java.io.File("files/config.json"); - FileContent mediaContent = new FileContent("application/json", filePath); - File file = service.files().create(fileMetadata, mediaContent) - .setFields("id") - .execute(); - System.out.println("File ID: " + file.getId()); - return file.getId(); - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to create file: " + e.getDetails()); - throw e; - } + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); + try { + // File's metadata. + File fileMetadata = new File(); + fileMetadata.setName("config.json"); + fileMetadata.setParents(Collections.singletonList("appDataFolder")); + java.io.File filePath = new java.io.File("files/config.json"); + FileContent mediaContent = new FileContent("application/json", filePath); + File file = service.files().create(fileMetadata, mediaContent) + .setFields("id") + .execute(); + System.out.println("File ID: " + file.getId()); + return file.getId(); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to create file: " + e.getDetails()); + throw e; } + } } // [END drive_upload_appdata] \ No newline at end of file diff --git a/drive/snippets/drive_v3/src/main/java/UploadBasic.java b/drive/snippets/drive_v3/src/main/java/UploadBasic.java index 65b30ad3..a39a696c 100644 --- a/drive/snippets/drive_v3/src/main/java/UploadBasic.java +++ b/drive/snippets/drive_v3/src/main/java/UploadBasic.java @@ -24,50 +24,51 @@ import com.google.api.services.drive.model.File; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.Arrays; /* Class to demonstrate use of Drive insert file API */ public class UploadBasic { - /** - * Upload new file. - * @return Inserted file metadata if successful, {@code null} otherwise. - * @throws IOException if service account credentials file not found. - */ - public static String uploadBasic() 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + /** + * Upload new file. + * + * @return Inserted file metadata if successful, {@code null} otherwise. + * @throws IOException if service account credentials file not found. + */ + public static String uploadBasic() 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(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); - // Upload file photo.jpg on drive. - File fileMetadata = new File(); - fileMetadata.setName("photo.jpg"); - // File's content. - java.io.File filePath = new java.io.File("files/photo.jpg"); - // Specify media type and file-path for file. - FileContent mediaContent = new FileContent("image/jpeg", filePath); - try { - File file = service.files().create(fileMetadata, mediaContent) - .setFields("id") - .execute(); - System.out.println("File ID: " + file.getId()); - return file.getId(); - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to upload file: " + e.getDetails()); - throw e; - } + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); + // Upload file photo.jpg on drive. + File fileMetadata = new File(); + fileMetadata.setName("photo.jpg"); + // File's content. + java.io.File filePath = new java.io.File("files/photo.jpg"); + // Specify media type and file-path for file. + FileContent mediaContent = new FileContent("image/jpeg", filePath); + try { + File file = service.files().create(fileMetadata, mediaContent) + .setFields("id") + .execute(); + System.out.println("File ID: " + file.getId()); + return file.getId(); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to upload file: " + e.getDetails()); + throw e; } + } } // [END drive_upload_basic] diff --git a/drive/snippets/drive_v3/src/main/java/UploadRevision.java b/drive/snippets/drive_v3/src/main/java/UploadRevision.java index 93e1c4f5..7ed2acac 100644 --- a/drive/snippets/drive_v3/src/main/java/UploadRevision.java +++ b/drive/snippets/drive_v3/src/main/java/UploadRevision.java @@ -24,49 +24,50 @@ import com.google.api.services.drive.model.File; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.Arrays; /* Class to demonstrate use-case of drive's upload revision */ public class UploadRevision { - /** - * Replace the old file with new one on same file ID. - * @param realFileId ID of the file to be replaced. - * @return Inserted file ID if successful, {@code null} otherwise. - * @throws IOException if service account credentials file not found. - */ - public static String uploadRevision(String realFileId) 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + /** + * Replace the old file with new one on same file ID. + * + * @param realFileId ID of the file to be replaced. + * @return Inserted file ID if successful, {@code null} otherwise. + * @throws IOException if service account credentials file not found. + */ + public static String uploadRevision(String realFileId) 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(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); - java.io.File filePath = new java.io.File("files/photo.jpg"); - FileContent mediaContent = new FileContent("image/jpeg", filePath); - try { - Drive.Files.Update request = service.files().update(realFileId, new File(), mediaContent) - .setFields("id"); - request.getMediaHttpUploader().setDirectUploadEnabled(true); - File file = request.execute(); - System.out.println("File ID: " + file.getId()); - return file.getId(); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to upload new file: " + e.getDetails()); - throw e; - } + java.io.File filePath = new java.io.File("files/photo.jpg"); + FileContent mediaContent = new FileContent("image/jpeg", filePath); + try { + Drive.Files.Update request = service.files().update(realFileId, new File(), mediaContent) + .setFields("id"); + request.getMediaHttpUploader().setDirectUploadEnabled(true); + File file = request.execute(); + System.out.println("File ID: " + file.getId()); + return file.getId(); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to upload new file: " + e.getDetails()); + throw e; } + } } // [END drive_upload_revision] diff --git a/drive/snippets/drive_v3/src/main/java/UploadToFolder.java b/drive/snippets/drive_v3/src/main/java/UploadToFolder.java index db2be62f..b6bd86ad 100644 --- a/drive/snippets/drive_v3/src/main/java/UploadToFolder.java +++ b/drive/snippets/drive_v3/src/main/java/UploadToFolder.java @@ -24,7 +24,6 @@ import com.google.api.services.drive.model.File; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.Arrays; import java.util.Collections; @@ -32,44 +31,46 @@ /* Class to demonstrate Drive's upload to folder use-case. */ public class UploadToFolder { - /** - * Upload a file to the specified folder. - * @param realFolderId Id of the folder. - * @return Inserted file metadata if successful, {@code null} otherwise. - * @throws IOException if service account credentials file not found. - */ - public static File uploadToFolder(String realFolderId) 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + /** + * Upload a file to the specified folder. + * + * @param realFolderId Id of the folder. + * @return Inserted file metadata if successful, {@code null} otherwise. + * @throws IOException if service account credentials file not found. + */ + public static File uploadToFolder(String realFolderId) 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(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); - // File's metadata. - File fileMetadata = new File(); - fileMetadata.setName("photo.jpg"); - fileMetadata.setParents(Collections.singletonList(realFolderId)); - java.io.File filePath = new java.io.File("files/photo.jpg"); - FileContent mediaContent = new FileContent("image/jpeg", filePath); - try { - File file = service.files().create(fileMetadata, mediaContent) - .setFields("id, parents") - .execute(); - System.out.println("File ID: " + file.getId()); - return file; - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to upload file: " + e.getDetails()); - throw e; - } + // File's metadata. + File fileMetadata = new File(); + fileMetadata.setName("photo.jpg"); + fileMetadata.setParents(Collections.singletonList(realFolderId)); + java.io.File filePath = new java.io.File("files/photo.jpg"); + FileContent mediaContent = new FileContent("image/jpeg", filePath); + try { + File file = service.files().create(fileMetadata, mediaContent) + .setFields("id, parents") + .execute(); + System.out.println("File ID: " + file.getId()); + return file; + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to upload file: " + e.getDetails()); + throw e; } + } } // [END drive_upload_to_folder] diff --git a/drive/snippets/drive_v3/src/main/java/UploadWithConversion.java b/drive/snippets/drive_v3/src/main/java/UploadWithConversion.java index 21d871b5..114e1b94 100644 --- a/drive/snippets/drive_v3/src/main/java/UploadWithConversion.java +++ b/drive/snippets/drive_v3/src/main/java/UploadWithConversion.java @@ -24,51 +24,52 @@ import com.google.api.services.drive.model.File; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.Arrays; /* Class to demonstrate Drive's upload with conversion use-case. */ public class UploadWithConversion { - /** - * Upload file with conversion. - * @return Inserted file id if successful, {@code null} otherwise. - * @throws IOException if service account credentials file not found. - */ - public static String uploadWithConversion() 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(Arrays.asList(DriveScopes.DRIVE_FILE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + /** + * Upload file with conversion. + * + * @return Inserted file id if successful, {@code null} otherwise. + * @throws IOException if service account credentials file not found. + */ + public static String uploadWithConversion() 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(Arrays.asList(DriveScopes.DRIVE_FILE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Build a new authorized API client service. - Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive samples") - .build(); + // Build a new authorized API client service. + Drive service = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive samples") + .build(); - // File's metadata. - File fileMetadata = new File(); - fileMetadata.setName("My Report"); - fileMetadata.setMimeType("application/vnd.google-apps.spreadsheet"); + // File's metadata. + File fileMetadata = new File(); + fileMetadata.setName("My Report"); + fileMetadata.setMimeType("application/vnd.google-apps.spreadsheet"); - java.io.File filePath = new java.io.File("files/report.csv"); - FileContent mediaContent = new FileContent("text/csv", filePath); - try { - File file = service.files().create(fileMetadata, mediaContent) - .setFields("id") - .execute(); - System.out.println("File ID: " + file.getId()); - return file.getId(); - }catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - System.err.println("Unable to move file: " + e.getDetails()); - throw e; - } + java.io.File filePath = new java.io.File("files/report.csv"); + FileContent mediaContent = new FileContent("text/csv", filePath); + try { + File file = service.files().create(fileMetadata, mediaContent) + .setFields("id") + .execute(); + System.out.println("File ID: " + file.getId()); + return file.getId(); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + System.err.println("Unable to move file: " + e.getDetails()); + throw e; } + } } // [END drive_upload_with_conversion] diff --git a/drive/snippets/drive_v3/src/test/java/AppDataSnippetsTest.java b/drive/snippets/drive_v3/src/test/java/AppDataSnippetsTest.java index cab4ed28..446af287 100644 --- a/drive/snippets/drive_v3/src/test/java/AppDataSnippetsTest.java +++ b/drive/snippets/drive_v3/src/test/java/AppDataSnippetsTest.java @@ -14,15 +14,14 @@ * limitations under the License. */ -import com.google.api.services.drive.model.File; -import com.google.api.services.drive.model.FileList; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import com.google.api.services.drive.model.FileList; import java.io.IOException; import java.security.GeneralSecurityException; - -import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; public class AppDataSnippetsTest extends BaseTest { diff --git a/drive/snippets/drive_v3/src/test/java/BaseTest.java b/drive/snippets/drive_v3/src/test/java/BaseTest.java index 75e636f3..7e4252fb 100644 --- a/drive/snippets/drive_v3/src/test/java/BaseTest.java +++ b/drive/snippets/drive_v3/src/test/java/BaseTest.java @@ -17,7 +17,6 @@ import com.google.api.client.http.FileContent; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; -import com.google.api.client.http.apache.ApacheHttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.drive.Drive; @@ -25,16 +24,17 @@ import com.google.api.services.drive.model.File; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; -import org.junit.After; -import org.junit.Before; - import java.io.IOException; import java.security.GeneralSecurityException; -import java.util.*; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; +import org.junit.After; +import org.junit.Before; public class BaseTest { static { @@ -70,7 +70,8 @@ public void publish(LogRecord record) { public GoogleCredentials getCredential() throws IOException { return GoogleCredentials.getApplicationDefault() - .createScoped(Arrays.asList(DriveScopes.DRIVE, DriveScopes.DRIVE_APPDATA,DriveScopes.DRIVE_FILE)); + .createScoped( + Arrays.asList(DriveScopes.DRIVE, DriveScopes.DRIVE_APPDATA, DriveScopes.DRIVE_FILE)); } /** @@ -85,14 +86,14 @@ protected Drive buildService() throws IOException { guides on implementing OAuth2 for your application. */ GoogleCredentials credentials = getCredential(); HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + credentials); // Create the classroom API client Drive service = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Drive Snippets") - .build(); + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Drive Snippets") + .build(); return service; } diff --git a/drive/snippets/drive_v3/src/test/java/ChangeSnippetsTest.java b/drive/snippets/drive_v3/src/test/java/ChangeSnippetsTest.java index 4323cc7d..7ad14676 100644 --- a/drive/snippets/drive_v3/src/test/java/ChangeSnippetsTest.java +++ b/drive/snippets/drive_v3/src/test/java/ChangeSnippetsTest.java @@ -14,14 +14,13 @@ * limitations under the License. */ -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; - import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; +import java.io.IOException; +import org.junit.Before; +import org.junit.Test; + public class ChangeSnippetsTest extends BaseTest { private ChangeSnippets snippets; diff --git a/drive/snippets/drive_v3/src/test/java/DriveSnippetsTest.java b/drive/snippets/drive_v3/src/test/java/DriveSnippetsTest.java index 71ec6b25..e32dc904 100644 --- a/drive/snippets/drive_v3/src/test/java/DriveSnippetsTest.java +++ b/drive/snippets/drive_v3/src/test/java/DriveSnippetsTest.java @@ -14,18 +14,17 @@ * limitations under the License. */ +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; + import com.google.api.services.drive.model.Drive; import com.google.api.services.drive.model.Permission; import com.google.api.services.drive.model.PermissionList; -import org.junit.Before; -import org.junit.Test; - import java.io.IOException; import java.security.GeneralSecurityException; import java.util.List; - -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; +import org.junit.Before; +import org.junit.Test; public class DriveSnippetsTest extends BaseTest { diff --git a/drive/snippets/drive_v3/src/test/java/FileSnippetsTest.java b/drive/snippets/drive_v3/src/test/java/FileSnippetsTest.java index a9641861..383a7935 100644 --- a/drive/snippets/drive_v3/src/test/java/FileSnippetsTest.java +++ b/drive/snippets/drive_v3/src/test/java/FileSnippetsTest.java @@ -14,17 +14,18 @@ * limitations under the License. */ -import com.google.api.services.drive.model.File; -import com.google.api.services.drive.model.FileList; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import com.google.api.services.drive.model.File; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.List; - -import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; public class FileSnippetsTest extends BaseTest { diff --git a/drive/snippets/drive_v3/src/test/java/TeamDriveSnippetsTest.java b/drive/snippets/drive_v3/src/test/java/TeamDriveSnippetsTest.java index 43447b4d..b59b235a 100644 --- a/drive/snippets/drive_v3/src/test/java/TeamDriveSnippetsTest.java +++ b/drive/snippets/drive_v3/src/test/java/TeamDriveSnippetsTest.java @@ -14,18 +14,17 @@ * limitations under the License. */ -import com.google.api.services.drive.model.TeamDrive; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; + import com.google.api.services.drive.model.Permission; import com.google.api.services.drive.model.PermissionList; -import org.junit.Before; -import org.junit.Test; - +import com.google.api.services.drive.model.TeamDrive; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.List; - -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; +import org.junit.Before; +import org.junit.Test; public class TeamDriveSnippetsTest extends BaseTest { diff --git a/drive/snippets/drive_v3/src/test/java/TestCreateDrive.java b/drive/snippets/drive_v3/src/test/java/TestCreateDrive.java index c8937fa4..37e3b23f 100644 --- a/drive/snippets/drive_v3/src/test/java/TestCreateDrive.java +++ b/drive/snippets/drive_v3/src/test/java/TestCreateDrive.java @@ -12,19 +12,18 @@ // See the License for the specific language governing permissions and // limitations under the License. -import org.junit.Test; +import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.security.GeneralSecurityException; - -import static org.junit.Assert.assertNotNull; +import org.junit.Test; // Unit test class for create-drive Drive snippet -public class TestCreateDrive extends BaseTest{ - @Test - public void createDrive() throws IOException, GeneralSecurityException { - String id = CreateDrive.createDrive(); - assertNotNull(id); - this.service.drives().delete(id); - } +public class TestCreateDrive extends BaseTest { + @Test + public void createDrive() throws IOException, GeneralSecurityException { + String id = CreateDrive.createDrive(); + assertNotNull(id); + this.service.drives().delete(id); + } } diff --git a/drive/snippets/drive_v3/src/test/java/TestCreateFolder.java b/drive/snippets/drive_v3/src/test/java/TestCreateFolder.java index 9c12f12f..d8492a08 100644 --- a/drive/snippets/drive_v3/src/test/java/TestCreateFolder.java +++ b/drive/snippets/drive_v3/src/test/java/TestCreateFolder.java @@ -14,18 +14,17 @@ * limitations under the License. */ -import org.junit.Test; +import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.security.GeneralSecurityException; +import org.junit.Test; -import static org.junit.Assert.assertNotNull; - -public class TestCreateFolder extends BaseTest{ - @Test - public void createFolder() throws IOException, GeneralSecurityException { - String id = CreateFolder.createFolder(); - assertNotNull(id); - deleteFileOnCleanup(id); - } +public class TestCreateFolder extends BaseTest { + @Test + public void createFolder() throws IOException, GeneralSecurityException { + String id = CreateFolder.createFolder(); + assertNotNull(id); + deleteFileOnCleanup(id); + } } diff --git a/drive/snippets/drive_v3/src/test/java/TestCreateShortcut.java b/drive/snippets/drive_v3/src/test/java/TestCreateShortcut.java index 1853773d..ab3e0f2f 100644 --- a/drive/snippets/drive_v3/src/test/java/TestCreateShortcut.java +++ b/drive/snippets/drive_v3/src/test/java/TestCreateShortcut.java @@ -14,18 +14,17 @@ * limitations under the License. */ -import org.junit.Test; +import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.security.GeneralSecurityException; +import org.junit.Test; -import static org.junit.Assert.assertNotNull; - -public class TestCreateShortcut extends BaseTest{ - @Test - public void createShortcut() throws IOException, GeneralSecurityException { - String id = CreateShortcut.createShortcut(); - assertNotNull(id); - deleteFileOnCleanup(id); - } +public class TestCreateShortcut extends BaseTest { + @Test + public void createShortcut() throws IOException, GeneralSecurityException { + String id = CreateShortcut.createShortcut(); + assertNotNull(id); + deleteFileOnCleanup(id); + } } diff --git a/drive/snippets/drive_v3/src/test/java/TestDownloadFile.java b/drive/snippets/drive_v3/src/test/java/TestDownloadFile.java index ce285417..526dea94 100644 --- a/drive/snippets/drive_v3/src/test/java/TestDownloadFile.java +++ b/drive/snippets/drive_v3/src/test/java/TestDownloadFile.java @@ -14,21 +14,20 @@ * limitations under the License. */ -import org.junit.Test; +import static org.junit.Assert.assertEquals; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.security.GeneralSecurityException; +import org.junit.Test; -import static org.junit.Assert.assertEquals; - -public class TestDownloadFile extends BaseTest{ - @Test - public void downloadFile() throws IOException, GeneralSecurityException { - String id = createTestBlob(); - ByteArrayOutputStream out = DownloadFile.downloadFile(id); - byte[] bytes = out.toByteArray(); - assertEquals((byte) 0xFF, bytes[0]); - assertEquals((byte) 0xD8, bytes[1]); - } +public class TestDownloadFile extends BaseTest { + @Test + public void downloadFile() throws IOException, GeneralSecurityException { + String id = createTestBlob(); + ByteArrayOutputStream out = DownloadFile.downloadFile(id); + byte[] bytes = out.toByteArray(); + assertEquals((byte) 0xFF, bytes[0]); + assertEquals((byte) 0xD8, bytes[1]); + } } diff --git a/drive/snippets/drive_v3/src/test/java/TestExportPdf.java b/drive/snippets/drive_v3/src/test/java/TestExportPdf.java index fc6deabb..16ede7b4 100644 --- a/drive/snippets/drive_v3/src/test/java/TestExportPdf.java +++ b/drive/snippets/drive_v3/src/test/java/TestExportPdf.java @@ -14,19 +14,18 @@ * limitations under the License. */ -import org.junit.Test; +import static org.junit.Assert.assertEquals; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.security.GeneralSecurityException; +import org.junit.Test; -import static org.junit.Assert.assertEquals; - -public class TestExportPdf extends BaseTest{ - @Test - public void exportPdf() throws IOException, GeneralSecurityException { - String id = createTestDocument(); - ByteArrayOutputStream out = ExportPdf.exportPdf(id); - assertEquals("%PDF", out.toString("UTF-8").substring(0, 4)); - } +public class TestExportPdf extends BaseTest { + @Test + public void exportPdf() throws IOException, GeneralSecurityException { + String id = createTestDocument(); + ByteArrayOutputStream out = ExportPdf.exportPdf(id); + assertEquals("%PDF", out.toString("UTF-8").substring(0, 4)); + } } diff --git a/drive/snippets/drive_v3/src/test/java/TestFetchAppDataFolder.java b/drive/snippets/drive_v3/src/test/java/TestFetchAppDataFolder.java index 95c69b6c..791e0480 100644 --- a/drive/snippets/drive_v3/src/test/java/TestFetchAppDataFolder.java +++ b/drive/snippets/drive_v3/src/test/java/TestFetchAppDataFolder.java @@ -14,17 +14,16 @@ * limitations under the License. */ -import org.junit.Test; +import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.security.GeneralSecurityException; - -import static org.junit.Assert.assertNotNull; +import org.junit.Test; public class TestFetchAppDataFolder { - @Test - public void fetchAppDataFolder() throws IOException, GeneralSecurityException { - String id = FetchAppDataFolder.fetchAppDataFolder(); - assertNotNull(id); - } + @Test + public void fetchAppDataFolder() throws IOException, GeneralSecurityException { + String id = FetchAppDataFolder.fetchAppDataFolder(); + assertNotNull(id); + } } diff --git a/drive/snippets/drive_v3/src/test/java/TestFetchChanges.java b/drive/snippets/drive_v3/src/test/java/TestFetchChanges.java index 7df7821a..aed15304 100644 --- a/drive/snippets/drive_v3/src/test/java/TestFetchChanges.java +++ b/drive/snippets/drive_v3/src/test/java/TestFetchChanges.java @@ -12,21 +12,20 @@ // See the License for the specific language governing permissions and // limitations under the License. -import org.junit.Test; - -import java.io.IOException; - import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; +import java.io.IOException; +import org.junit.Test; + // Unit test class for fetchChanges change snippet -public class TestFetchChanges extends BaseTest{ - @Test - public void fetchChanges() throws IOException { - String startPageToken = FetchStartPageToken.fetchStartPageToken(); - this.createTestBlob(); - String newStartPageToken = FetchChanges.fetchChanges(startPageToken); - assertNotNull(newStartPageToken); - assertNotEquals(startPageToken, newStartPageToken); - } +public class TestFetchChanges extends BaseTest { + @Test + public void fetchChanges() throws IOException { + String startPageToken = FetchStartPageToken.fetchStartPageToken(); + this.createTestBlob(); + String newStartPageToken = FetchChanges.fetchChanges(startPageToken); + assertNotNull(newStartPageToken); + assertNotEquals(startPageToken, newStartPageToken); + } } diff --git a/drive/snippets/drive_v3/src/test/java/TestFetchStartPageToken.java b/drive/snippets/drive_v3/src/test/java/TestFetchStartPageToken.java index fd4be2ad..1d334a1e 100644 --- a/drive/snippets/drive_v3/src/test/java/TestFetchStartPageToken.java +++ b/drive/snippets/drive_v3/src/test/java/TestFetchStartPageToken.java @@ -12,17 +12,16 @@ // See the License for the specific language governing permissions and // limitations under the License. -import org.junit.Test; +import static org.junit.Assert.assertNotNull; import java.io.IOException; - -import static org.junit.Assert.assertNotNull; +import org.junit.Test; // Unit test class for fetchStartPageToken change snippet -public class TestFetchStartPageToken extends BaseTest{ - @Test - public void fetchStartPageToken() throws IOException { - String token = FetchStartPageToken.fetchStartPageToken(); - assertNotNull(token); - } +public class TestFetchStartPageToken extends BaseTest { + @Test + public void fetchStartPageToken() throws IOException { + String token = FetchStartPageToken.fetchStartPageToken(); + assertNotNull(token); + } } diff --git a/drive/snippets/drive_v3/src/test/java/TestListAppData.java b/drive/snippets/drive_v3/src/test/java/TestListAppData.java index fe67a1f2..c747f7ee 100644 --- a/drive/snippets/drive_v3/src/test/java/TestListAppData.java +++ b/drive/snippets/drive_v3/src/test/java/TestListAppData.java @@ -14,20 +14,19 @@ * limitations under the License. */ -import com.google.api.services.drive.model.FileList; -import org.junit.Test; +import static org.junit.Assert.assertNotEquals; +import com.google.api.services.drive.model.FileList; import java.io.IOException; import java.security.GeneralSecurityException; +import org.junit.Test; -import static org.junit.Assert.assertNotEquals; - -public class TestListAppData extends BaseTest{ - @Test - public void listAppData() throws IOException, GeneralSecurityException { - String id = UploadAppData.uploadAppData(); - deleteFileOnCleanup(id); - FileList files = ListAppData.listAppData(); - assertNotEquals(0, files.getFiles().size()); - } +public class TestListAppData extends BaseTest { + @Test + public void listAppData() throws IOException, GeneralSecurityException { + String id = UploadAppData.uploadAppData(); + deleteFileOnCleanup(id); + FileList files = ListAppData.listAppData(); + assertNotEquals(0, files.getFiles().size()); + } } diff --git a/drive/snippets/drive_v3/src/test/java/TestMoveFileToFolder.java b/drive/snippets/drive_v3/src/test/java/TestMoveFileToFolder.java index 7e4b2b8d..2c5aa74c 100644 --- a/drive/snippets/drive_v3/src/test/java/TestMoveFileToFolder.java +++ b/drive/snippets/drive_v3/src/test/java/TestMoveFileToFolder.java @@ -14,25 +14,23 @@ * limitations under the License. */ -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; -import javax.annotation.CheckReturnValue; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.List; +import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class TestMoveFileToFolder extends BaseTest{ - @Test - public void moveFileToFolder() - throws IOException, GeneralSecurityException { - String folderId = CreateFolder.createFolder(); - deleteFileOnCleanup(folderId); - String fileId = this.createTestBlob(); - List parents = MoveFileToFolder.moveFileToFolder(fileId, folderId); - assertTrue(parents.contains(folderId)); - assertEquals(1, parents.size()); - } +public class TestMoveFileToFolder extends BaseTest { + @Test + public void moveFileToFolder() + throws IOException, GeneralSecurityException { + String folderId = CreateFolder.createFolder(); + deleteFileOnCleanup(folderId); + String fileId = this.createTestBlob(); + List parents = MoveFileToFolder.moveFileToFolder(fileId, folderId); + assertTrue(parents.contains(folderId)); + assertEquals(1, parents.size()); + } } diff --git a/drive/snippets/drive_v3/src/test/java/TestRecoverDrives.java b/drive/snippets/drive_v3/src/test/java/TestRecoverDrives.java index a638f0e6..28e92433 100644 --- a/drive/snippets/drive_v3/src/test/java/TestRecoverDrives.java +++ b/drive/snippets/drive_v3/src/test/java/TestRecoverDrives.java @@ -12,37 +12,36 @@ // See the License for the specific language governing permissions and // limitations under the License. +import static org.junit.Assert.assertNotEquals; + import com.google.api.services.drive.model.Drive; import com.google.api.services.drive.model.Permission; import com.google.api.services.drive.model.PermissionList; -import org.junit.Test; - import java.io.IOException; import java.util.List; - -import static org.junit.Assert.assertNotEquals; +import org.junit.Test; // Unit test class for recover-drives Drive snippet -public class TestRecoverDrives extends BaseTest{ - @Test - public void recoverDrives() throws IOException { - String id = this.createOrphanedDrive(); - List results = RecoverDrive.recoverDrives( - "sbazyl@test.appsdevtesting.com"); - assertNotEquals(0, results.size()); - this.service.drives().delete(id).execute(); - } +public class TestRecoverDrives extends BaseTest { + @Test + public void recoverDrives() throws IOException { + String id = this.createOrphanedDrive(); + List results = RecoverDrive.recoverDrives( + "sbazyl@test.appsdevtesting.com"); + assertNotEquals(0, results.size()); + this.service.drives().delete(id).execute(); + } - private String createOrphanedDrive() throws IOException { - String driveId = CreateDrive.createDrive(); - PermissionList response = this.service.permissions().list(driveId) - .setSupportsAllDrives(true) - .execute(); - for (Permission permission : response.getPermissions()) { - this.service.permissions().delete(driveId, permission.getId()) - .setSupportsAllDrives(true) - .execute(); - } - return driveId; + private String createOrphanedDrive() throws IOException { + String driveId = CreateDrive.createDrive(); + PermissionList response = this.service.permissions().list(driveId) + .setSupportsAllDrives(true) + .execute(); + for (Permission permission : response.getPermissions()) { + this.service.permissions().delete(driveId, permission.getId()) + .setSupportsAllDrives(true) + .execute(); } + return driveId; + } } diff --git a/drive/snippets/drive_v3/src/test/java/TestSearchFiles.java b/drive/snippets/drive_v3/src/test/java/TestSearchFiles.java index 6772cb40..280c6b9c 100644 --- a/drive/snippets/drive_v3/src/test/java/TestSearchFiles.java +++ b/drive/snippets/drive_v3/src/test/java/TestSearchFiles.java @@ -14,21 +14,20 @@ * limitations under the License. */ -import com.google.api.services.drive.model.File; -import org.junit.Test; +import static org.junit.Assert.assertNotEquals; +import com.google.api.services.drive.model.File; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.List; +import org.junit.Test; -import static org.junit.Assert.assertNotEquals; - -public class TestSearchFiles extends BaseTest{ - @Test - public void searchFiles() - throws IOException, GeneralSecurityException { - this.createTestBlob(); - List files = SearchFile.searchFile(); - assertNotEquals(0, files.size()); - } +public class TestSearchFiles extends BaseTest { + @Test + public void searchFiles() + throws IOException, GeneralSecurityException { + this.createTestBlob(); + List files = SearchFile.searchFile(); + assertNotEquals(0, files.size()); + } } diff --git a/drive/snippets/drive_v3/src/test/java/TestShareFile.java b/drive/snippets/drive_v3/src/test/java/TestShareFile.java index c47ec72c..167a7ec7 100644 --- a/drive/snippets/drive_v3/src/test/java/TestShareFile.java +++ b/drive/snippets/drive_v3/src/test/java/TestShareFile.java @@ -14,20 +14,19 @@ * limitations under the License. */ -import org.junit.Test; +import static org.junit.Assert.assertEquals; import java.io.IOException; import java.util.List; +import org.junit.Test; -import static org.junit.Assert.assertEquals; - -public class TestShareFile extends BaseTest{ - @Test - public void shareFile() throws IOException { - String fileId = this.createTestBlob(); - List ids = ShareFile.shareFile(fileId, - "user@test.appsdevtesting.com", - "test.appsdevtesting.com"); - assertEquals(2, ids.size()); - } +public class TestShareFile extends BaseTest { + @Test + public void shareFile() throws IOException { + String fileId = this.createTestBlob(); + List ids = ShareFile.shareFile(fileId, + "user@test.appsdevtesting.com", + "test.appsdevtesting.com"); + assertEquals(2, ids.size()); + } } diff --git a/drive/snippets/drive_v3/src/test/java/TestTouchFile.java b/drive/snippets/drive_v3/src/test/java/TestTouchFile.java index aecfabf4..9d7d80b8 100644 --- a/drive/snippets/drive_v3/src/test/java/TestTouchFile.java +++ b/drive/snippets/drive_v3/src/test/java/TestTouchFile.java @@ -14,19 +14,18 @@ * limitations under the License. */ -import org.junit.Test; +import static org.junit.Assert.assertEquals; import java.io.IOException; import java.security.GeneralSecurityException; +import org.junit.Test; -import static org.junit.Assert.assertEquals; - -public class TestTouchFile extends BaseTest{ - @Test - public void touchFile() throws IOException, GeneralSecurityException { - String id = this.createTestBlob(); - long now = System.currentTimeMillis(); - long modifiedTime = TouchFile.touchFile(id, now); - assertEquals(now, modifiedTime); - } +public class TestTouchFile extends BaseTest { + @Test + public void touchFile() throws IOException, GeneralSecurityException { + String id = this.createTestBlob(); + long now = System.currentTimeMillis(); + long modifiedTime = TouchFile.touchFile(id, now); + assertEquals(now, modifiedTime); + } } diff --git a/drive/snippets/drive_v3/src/test/java/TestUploadAppdata.java b/drive/snippets/drive_v3/src/test/java/TestUploadAppdata.java index a8dbd5be..69608a87 100644 --- a/drive/snippets/drive_v3/src/test/java/TestUploadAppdata.java +++ b/drive/snippets/drive_v3/src/test/java/TestUploadAppdata.java @@ -14,19 +14,18 @@ * limitations under the License. */ -import org.junit.Test; +import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.security.GeneralSecurityException; +import org.junit.Test; -import static org.junit.Assert.assertNotNull; - -public class TestUploadAppdata extends BaseTest{ - @Test - public void uploadAppData() - throws IOException, GeneralSecurityException { - String id = UploadAppData.uploadAppData(); - assertNotNull(id); - deleteFileOnCleanup(id); - } +public class TestUploadAppdata extends BaseTest { + @Test + public void uploadAppData() + throws IOException, GeneralSecurityException { + String id = UploadAppData.uploadAppData(); + assertNotNull(id); + deleteFileOnCleanup(id); + } } diff --git a/drive/snippets/drive_v3/src/test/java/TestUploadBasic.java b/drive/snippets/drive_v3/src/test/java/TestUploadBasic.java index b33b7866..fa53f4ff 100644 --- a/drive/snippets/drive_v3/src/test/java/TestUploadBasic.java +++ b/drive/snippets/drive_v3/src/test/java/TestUploadBasic.java @@ -14,18 +14,17 @@ * limitations under the License. */ -import org.junit.Test; +import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.security.GeneralSecurityException; +import org.junit.Test; -import static org.junit.Assert.assertNotNull; - -public class TestUploadBasic extends BaseTest{ - @Test - public void uploadBasic() throws IOException, GeneralSecurityException { - String id = UploadBasic.uploadBasic(); - assertNotNull(id); - deleteFileOnCleanup(id); - } +public class TestUploadBasic extends BaseTest { + @Test + public void uploadBasic() throws IOException, GeneralSecurityException { + String id = UploadBasic.uploadBasic(); + assertNotNull(id); + deleteFileOnCleanup(id); + } } diff --git a/drive/snippets/drive_v3/src/test/java/TestUploadRevision.java b/drive/snippets/drive_v3/src/test/java/TestUploadRevision.java index de932e4f..ea7e7eea 100644 --- a/drive/snippets/drive_v3/src/test/java/TestUploadRevision.java +++ b/drive/snippets/drive_v3/src/test/java/TestUploadRevision.java @@ -14,21 +14,20 @@ * limitations under the License. */ -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.security.GeneralSecurityException; +import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -public class TestUploadRevision extends BaseTest{ - @Test - public void uploadRevision() throws IOException, GeneralSecurityException { - String id = UploadBasic.uploadBasic(); - assertNotNull(id); - deleteFileOnCleanup(id); - String id2 = UploadRevision.uploadRevision(id); - assertEquals(id, id2); - } +public class TestUploadRevision extends BaseTest { + @Test + public void uploadRevision() throws IOException, GeneralSecurityException { + String id = UploadBasic.uploadBasic(); + assertNotNull(id); + deleteFileOnCleanup(id); + String id2 = UploadRevision.uploadRevision(id); + assertEquals(id, id2); + } } diff --git a/drive/snippets/drive_v3/src/test/java/TestUploadToFolder.java b/drive/snippets/drive_v3/src/test/java/TestUploadToFolder.java index c328994e..feee6a6a 100644 --- a/drive/snippets/drive_v3/src/test/java/TestUploadToFolder.java +++ b/drive/snippets/drive_v3/src/test/java/TestUploadToFolder.java @@ -14,21 +14,20 @@ * limitations under the License. */ -import com.google.api.services.drive.model.File; -import org.junit.Test; +import static org.junit.Assert.assertTrue; +import com.google.api.services.drive.model.File; import java.io.IOException; import java.security.GeneralSecurityException; +import org.junit.Test; -import static org.junit.Assert.assertTrue; - -public class TestUploadToFolder extends BaseTest{ - @Test - public void uploadToFolder() throws IOException, GeneralSecurityException { - String folderId = CreateFolder.createFolder(); - File file = UploadToFolder.uploadToFolder(folderId); - assertTrue(file.getParents().contains(folderId)); - deleteFileOnCleanup(file.getId()); - deleteFileOnCleanup(folderId); - } +public class TestUploadToFolder extends BaseTest { + @Test + public void uploadToFolder() throws IOException, GeneralSecurityException { + String folderId = CreateFolder.createFolder(); + File file = UploadToFolder.uploadToFolder(folderId); + assertTrue(file.getParents().contains(folderId)); + deleteFileOnCleanup(file.getId()); + deleteFileOnCleanup(folderId); + } } diff --git a/drive/snippets/drive_v3/src/test/java/TestUploadWithConversion.java b/drive/snippets/drive_v3/src/test/java/TestUploadWithConversion.java index ae3a889c..11b5f2f9 100644 --- a/drive/snippets/drive_v3/src/test/java/TestUploadWithConversion.java +++ b/drive/snippets/drive_v3/src/test/java/TestUploadWithConversion.java @@ -14,19 +14,18 @@ * limitations under the License. */ -import org.junit.Test; +import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.security.GeneralSecurityException; +import org.junit.Test; -import static org.junit.Assert.assertNotNull; - -public class TestUploadWithConversion extends BaseTest{ - @Test - public void uploadWithConversion() - throws IOException, GeneralSecurityException { - String id = UploadWithConversion.uploadWithConversion(); - assertNotNull(id); - deleteFileOnCleanup(id); - } +public class TestUploadWithConversion extends BaseTest { + @Test + public void uploadWithConversion() + throws IOException, GeneralSecurityException { + String id = UploadWithConversion.uploadWithConversion(); + assertNotNull(id); + deleteFileOnCleanup(id); + } } diff --git a/gmail/quickstart/src/main/java/GmailQuickstart.java b/gmail/quickstart/src/main/java/GmailQuickstart.java index 650ba0b7..56ebd1dd 100644 --- a/gmail/quickstart/src/main/java/GmailQuickstart.java +++ b/gmail/quickstart/src/main/java/GmailQuickstart.java @@ -13,6 +13,7 @@ // limitations under the License. // [START gmail_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; @@ -27,7 +28,6 @@ import com.google.api.services.gmail.GmailScopes; import com.google.api.services.gmail.model.Label; import com.google.api.services.gmail.model.ListLabelsResponse; - import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; @@ -38,65 +38,74 @@ /* class to demonstrate use of Gmail list labels API */ public class GmailQuickstart { - /** Application name. */ - private static final String APPLICATION_NAME = "Gmail API Java Quickstart"; - /** Global instance of the JSON factory. */ - private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); - /** Directory to store authorization tokens for this application. */ - private static final String TOKENS_DIRECTORY_PATH = "tokens"; + /** + * Application name. + */ + private static final String APPLICATION_NAME = "Gmail API Java Quickstart"; + /** + * Global instance of the JSON factory. + */ + private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); + /** + * 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(GmailScopes.GMAIL_LABELS); - private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; + /** + * 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(GmailScopes.GMAIL_LABELS); + private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; - /** - * Creates an authorized Credential object. - * @param HTTP_TRANSPORT The network HTTP Transport. - * @return An authorized Credential object. - * @throws IOException If the credentials.json file cannot be found. - */ - private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException { - // Load client secrets. - InputStream in = GmailQuickstart.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(); - Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user"); - //returns an authorized Credential object. - return credential; + /** + * Creates an authorized Credential object. + * + * @param HTTP_TRANSPORT The network HTTP Transport. + * @return An authorized Credential object. + * @throws IOException If the credentials.json file cannot be found. + */ + private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) + throws IOException { + // Load client secrets. + InputStream in = GmailQuickstart.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(); + Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user"); + //returns an authorized Credential object. + return credential; + } - public static void main(String... args) throws IOException, GeneralSecurityException { - // Build a new authorized API client service. - final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); - Gmail service = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) - .setApplicationName(APPLICATION_NAME) - .build(); + public static void main(String... args) throws IOException, GeneralSecurityException { + // Build a new authorized API client service. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Gmail service = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) + .setApplicationName(APPLICATION_NAME) + .build(); - // Print the labels in the user's account. - String user = "me"; - ListLabelsResponse listResponse = service.users().labels().list(user).execute(); - List

Each row of the CSV file should contain a user ID, path to the certificate, and the - * certificate password. - * - * @param csvFilename Name of the CSV file. - */ - public static void insertCertFromCsv(String csvFilename) { - try { - File csvFile = new File(csvFilename); - CSVParser parser = - CSVParser.parse(csvFile, java.nio.charset.StandardCharsets.UTF_8, CSVFormat.DEFAULT); - for (CSVRecord record : parser) { - String userId = record.get(0); - String certFilename = record.get(1); - String certPassword = record.get(2); - SmimeInfo smimeInfo = CreateSmimeInfo.createSmimeInfo(certFilename, - certPassword); - if (smimeInfo != null) { - InsertSmimeInfo.insertSmimeInfo(userId, - userId, - smimeInfo); - } else { - System.err.printf("Unable to read certificate file for userId: %s\n", userId); - } - } - } catch (Exception e) { - System.err.printf("An error occured while reading the CSV file: %s", e); + /** + * Upload S/MIME certificates based on the contents of a CSV file. + * + *

Each row of the CSV file should contain a user ID, path to the certificate, and the + * certificate password. + * + * @param csvFilename Name of the CSV file. + */ + public static void insertCertFromCsv(String csvFilename) { + try { + File csvFile = new File(csvFilename); + CSVParser parser = + CSVParser.parse(csvFile, java.nio.charset.StandardCharsets.UTF_8, CSVFormat.DEFAULT); + for (CSVRecord record : parser) { + String userId = record.get(0); + String certFilename = record.get(1); + String certPassword = record.get(2); + SmimeInfo smimeInfo = CreateSmimeInfo.createSmimeInfo(certFilename, + certPassword); + if (smimeInfo != null) { + InsertSmimeInfo.insertSmimeInfo(userId, + userId, + smimeInfo); + } else { + System.err.printf("Unable to read certificate file for userId: %s\n", userId); } + } + } catch (Exception e) { + System.err.printf("An error occured while reading the CSV file: %s", e); } + } } // [END gmail_insert_cert_from_csv] \ No newline at end of file diff --git a/gmail/snippets/src/main/java/InsertSmimeInfo.java b/gmail/snippets/src/main/java/InsertSmimeInfo.java index e686126d..25af7f83 100644 --- a/gmail/snippets/src/main/java/InsertSmimeInfo.java +++ b/gmail/snippets/src/main/java/InsertSmimeInfo.java @@ -14,8 +14,7 @@ // [START gmail_insert_smime_info] -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; @@ -24,54 +23,52 @@ import com.google.api.services.gmail.model.SmimeInfo; 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 Gmail Insert Smime Certificate API*/ public class InsertSmimeInfo { - /** - * Upload an S/MIME certificate for the user. - * - * @param userId User's email address. - * @param sendAsEmail The "send as" email address, or null if it should be the same as userId. - * @param smimeInfo The SmimeInfo object containing the user's S/MIME certificate. - * @return An SmimeInfo object with details about the uploaded certificate, {@code null} otherwise. - * @throws IOException - if service account credentials file not found. - */ - public static SmimeInfo insertSmimeInfo(String userId, - String sendAsEmail, - SmimeInfo smimeInfo) - throws IOException { + /** + * Upload an S/MIME certificate for the user. + * + * @param userId User's email address. + * @param sendAsEmail The "send as" email address, or null if it should be the same as userId. + * @param smimeInfo The SmimeInfo object containing the user's S/MIME certificate. + * @return An SmimeInfo object with details about the uploaded certificate, {@code null} otherwise. + * @throws IOException - if service account credentials file not found. + */ + public static SmimeInfo insertSmimeInfo(String userId, + String sendAsEmail, + SmimeInfo smimeInfo) + 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(GmailScopes.GMAIL_SETTINGS_SHARING); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(GmailScopes.GMAIL_SETTINGS_SHARING); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the gmail API client - Gmail service = new Gmail.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Gmail samples") - .build(); + // Create the gmail API client + Gmail service = new Gmail.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Gmail samples") + .build(); - if (sendAsEmail == null) { - sendAsEmail = userId; - } + if (sendAsEmail == null) { + sendAsEmail = userId; + } - try { - SmimeInfo results = service.users().settings().sendAs().smimeInfo() - .insert(userId, sendAsEmail, smimeInfo) - .execute(); - System.out.printf("Inserted certificate, id: %s\n", results.getId()); - return results; - } catch (IOException e) { - System.err.printf("An error occured: %s", e); - } - return null; + try { + SmimeInfo results = service.users().settings().sendAs().smimeInfo() + .insert(userId, sendAsEmail, smimeInfo) + .execute(); + System.out.printf("Inserted certificate, id: %s\n", results.getId()); + return results; + } catch (IOException e) { + System.err.printf("An error occured: %s", e); } + return null; + } } // [END gmail_insert_smime_info] \ No newline at end of file diff --git a/gmail/snippets/src/main/java/SendEmail.java b/gmail/snippets/src/main/java/SendEmail.java deleted file mode 100644 index 9b671f32..00000000 --- a/gmail/snippets/src/main/java/SendEmail.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * 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. - */ - -import com.google.api.services.gmail.Gmail; -import com.google.api.services.gmail.model.Draft; -import com.google.api.services.gmail.model.Message; -import org.apache.commons.codec.binary.Base64; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.util.Properties; - -import javax.activation.DataHandler; -import javax.activation.DataSource; -import javax.activation.FileDataSource; -import javax.mail.MessagingException; -import javax.mail.Multipart; -import javax.mail.Session; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeBodyPart; -import javax.mail.internet.MimeMessage; -import javax.mail.internet.MimeMultipart; - -// ... - -public class SendEmail { - - // ... - - // [START create_draft] - /** - * Create draft email. - * - * @param service an authorized Gmail API instance - * @param userId user's email address. The special value "me" - * can be used to indicate the authenticated user - * @param emailContent the MimeMessage used as email within the draft - * @return the created draft - * @throws MessagingException - * @throws IOException - */ - public static Draft createDraft(Gmail service, - String userId, - MimeMessage emailContent) - throws MessagingException, IOException { - Message message = createMessageWithEmail(emailContent); - Draft draft = new Draft(); - draft.setMessage(message); - draft = service.users().drafts().create(userId, draft).execute(); - - System.out.println("Draft id: " + draft.getId()); - System.out.println(draft.toPrettyString()); - return draft; - } - // [END create_draft] - - - // [START send_email] - /** - * Send an email from the user's mailbox to its recipient. - * - * @param service Authorized Gmail API instance. - * @param userId User's email address. The special value "me" - * can be used to indicate the authenticated user. - * @param emailContent Email to be sent. - * @return The sent message - * @throws MessagingException - * @throws IOException - */ - public static Message sendMessage(Gmail service, - String userId, - MimeMessage emailContent) - throws MessagingException, IOException { - Message message = createMessageWithEmail(emailContent); - message = service.users().messages().send(userId, message).execute(); - - System.out.println("Message id: " + message.getId()); - System.out.println(message.toPrettyString()); - return message; - } - // [END send_email] - - - // [START create_message] - /** - * Create a message from an email. - * - * @param emailContent Email to be set to raw of message - * @return a message containing a base64url encoded email - * @throws IOException - * @throws MessagingException - */ - public static Message createMessageWithEmail(MimeMessage emailContent) - throws MessagingException, IOException { - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - emailContent.writeTo(buffer); - byte[] bytes = buffer.toByteArray(); - String encodedEmail = Base64.encodeBase64URLSafeString(bytes); - Message message = new Message(); - message.setRaw(encodedEmail); - return message; - } - // [END create_message] - - // [START create_email] - /** - * Create a MimeMessage using the parameters provided. - * - * @param to email address of the receiver - * @param from email address of the sender, the mailbox account - * @param subject subject of the email - * @param bodyText body text of the email - * @return the MimeMessage to be used to send email - * @throws MessagingException - */ - public static MimeMessage createEmail(String to, - String from, - String subject, - String bodyText) - throws MessagingException { - Properties props = new Properties(); - Session session = Session.getDefaultInstance(props, null); - - MimeMessage email = new MimeMessage(session); - - email.setFrom(new InternetAddress(from)); - email.addRecipient(javax.mail.Message.RecipientType.TO, - new InternetAddress(to)); - email.setSubject(subject); - email.setText(bodyText); - return email; - } - // [END create_email] - - - // [START create_email_attachment] - /** - * Create a MimeMessage using the parameters provided. - * - * @param to Email address of the receiver. - * @param from Email address of the sender, the mailbox account. - * @param subject Subject of the email. - * @param bodyText Body text of the email. - * @param file Path to the file to be attached. - * @return MimeMessage to be used to send email. - * @throws MessagingException - */ - public static MimeMessage createEmailWithAttachment(String to, - String from, - String subject, - String bodyText, - File file) - throws MessagingException, IOException { - Properties props = new Properties(); - Session session = Session.getDefaultInstance(props, null); - - MimeMessage email = new MimeMessage(session); - - email.setFrom(new InternetAddress(from)); - email.addRecipient(javax.mail.Message.RecipientType.TO, - new InternetAddress(to)); - email.setSubject(subject); - - MimeBodyPart mimeBodyPart = new MimeBodyPart(); - mimeBodyPart.setContent(bodyText, "text/plain"); - - Multipart multipart = new MimeMultipart(); - multipart.addBodyPart(mimeBodyPart); - - mimeBodyPart = new MimeBodyPart(); - DataSource source = new FileDataSource(file); - - mimeBodyPart.setDataHandler(new DataHandler(source)); - mimeBodyPart.setFileName(file.getName()); - - multipart.addBodyPart(mimeBodyPart); - email.setContent(multipart); - - return email; - } - // [END create_email_attachment] - - // ... - -} diff --git a/gmail/snippets/src/main/java/SendMessage.java b/gmail/snippets/src/main/java/SendMessage.java index 9e0ec4b7..de989866 100644 --- a/gmail/snippets/src/main/java/SendMessage.java +++ b/gmail/snippets/src/main/java/SendMessage.java @@ -14,94 +14,92 @@ // [START gmail_send_message] + 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.gmail.Gmail; import com.google.api.services.gmail.GmailScopes; +import com.google.api.services.gmail.model.Message; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; -import org.apache.commons.codec.binary.Base64; -import com.google.api.services.gmail.Gmail; -import com.google.api.services.gmail.model.Message; - import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.util.Collections; import java.util.Properties; - import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; +import org.apache.commons.codec.binary.Base64; /* Class to demonstrate the use of Gmail Send Message API */ public class SendMessage { - /** - * Send an email from the user's mailbox to its recipient. - * - * @param fromEmailAddress - Email address to appear in the from: header - * @param toEmailAddress - Email address of the recipient - * @return the sent message, {@code null} otherwise. - * @throws MessagingException - if a wrongly formatted address is encountered. - * @throws IOException - if service account credentials file not found. - */ - public static Message sendEmail(String fromEmailAddress, - String toEmailAddress) - throws MessagingException, IOException { + /** + * Send an email from the user's mailbox to its recipient. + * + * @param fromEmailAddress - Email address to appear in the from: header + * @param toEmailAddress - Email address of the recipient + * @return the sent message, {@code null} otherwise. + * @throws MessagingException - if a wrongly formatted address is encountered. + * @throws IOException - if service account credentials file not found. + */ + public static Message sendEmail(String fromEmailAddress, + String toEmailAddress) + throws MessagingException, 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(GmailScopes.GMAIL_SEND); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(GmailScopes.GMAIL_SEND); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials); - // Create the gmail API client - Gmail service = new Gmail.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Gmail samples") - .build(); + // Create the gmail API client + Gmail service = new Gmail.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Gmail samples") + .build(); - // Create the email content - String messageSubject = "Test message"; - String bodyText = "lorem ipsum."; + // Create the email content + String messageSubject = "Test message"; + String bodyText = "lorem ipsum."; - // Encode as MIME message - Properties props = new Properties(); - Session session = Session.getDefaultInstance(props, null); - MimeMessage email = new MimeMessage(session); - email.setFrom(new InternetAddress(fromEmailAddress)); - email.addRecipient(javax.mail.Message.RecipientType.TO, - new InternetAddress(toEmailAddress)); - email.setSubject(messageSubject); - email.setText(bodyText); + // Encode as MIME message + Properties props = new Properties(); + Session session = Session.getDefaultInstance(props, null); + MimeMessage email = new MimeMessage(session); + email.setFrom(new InternetAddress(fromEmailAddress)); + email.addRecipient(javax.mail.Message.RecipientType.TO, + new InternetAddress(toEmailAddress)); + email.setSubject(messageSubject); + email.setText(bodyText); - // Encode and wrap the MIME message into a gmail message - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - email.writeTo(buffer); - byte[] rawMessageBytes = buffer.toByteArray(); - String encodedEmail = Base64.encodeBase64URLSafeString(rawMessageBytes); - Message message = new Message(); - message.setRaw(encodedEmail); + // Encode and wrap the MIME message into a gmail message + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + email.writeTo(buffer); + byte[] rawMessageBytes = buffer.toByteArray(); + String encodedEmail = Base64.encodeBase64URLSafeString(rawMessageBytes); + Message message = new Message(); + message.setRaw(encodedEmail); - try { - // Create send message - message = service.users().messages().send("me", message).execute(); - System.out.println("Message id: " + message.getId()); - System.out.println(message.toPrettyString()); - return message; - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 403) { - System.err.println("Unable to send message: " + e.getDetails()); - } else { - throw e; - } - } - return null; + try { + // Create send message + message = service.users().messages().send("me", message).execute(); + System.out.println("Message id: " + message.getId()); + System.out.println(message.toPrettyString()); + return message; + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 403) { + System.err.println("Unable to send message: " + e.getDetails()); + } else { + throw e; + } } + return null; + } } // [END gmail_send_message] \ No newline at end of file diff --git a/gmail/snippets/src/main/java/SendMessageWithAttachment.java b/gmail/snippets/src/main/java/SendMessageWithAttachment.java index 29c28ec4..2a9903f0 100644 --- a/gmail/snippets/src/main/java/SendMessageWithAttachment.java +++ b/gmail/snippets/src/main/java/SendMessageWithAttachment.java @@ -14,23 +14,21 @@ // [START gmail_send_message_with_attachment] + 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.gmail.Gmail; import com.google.api.services.gmail.GmailScopes; +import com.google.api.services.gmail.model.Message; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; -import org.apache.commons.codec.binary.Base64; -import com.google.api.services.gmail.Gmail; -import com.google.api.services.gmail.model.Message; - import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.Properties; - import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; @@ -41,85 +39,86 @@ import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; +import org.apache.commons.codec.binary.Base64; /* Class to demonstrate the use of Gmail Send Message with attachment API */ -public class SendMessageWithAttachment{ - /** - * Send an email with attachment from the user's mailbox to its recipient. - * - * @param fromEmailAddress - Email address to appear in the from: header. - * @param toEmailAddress - Email address of the recipient. - * @param file - Path to the file to be attached. - * @return the sent message, {@code null} otherwise. - * @throws MessagingException - if a wrongly formatted address is encountered. - * @throws IOException - if service account credentials file not found. - */ - public static Message sendEmailWithAttachment(String fromEmailAddress, - String toEmailAddress, - File file) - throws MessagingException, IOException { +public class SendMessageWithAttachment { + /** + * Send an email with attachment from the user's mailbox to its recipient. + * + * @param fromEmailAddress - Email address to appear in the from: header. + * @param toEmailAddress - Email address of the recipient. + * @param file - Path to the file to be attached. + * @return the sent message, {@code null} otherwise. + * @throws MessagingException - if a wrongly formatted address is encountered. + * @throws IOException - if service account credentials file not found. + */ + public static Message sendEmailWithAttachment(String fromEmailAddress, + String toEmailAddress, + File file) + throws MessagingException, 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(GmailScopes.GMAIL_SEND); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(GmailScopes.GMAIL_SEND); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials); - // Create the gmail API client - Gmail service = new Gmail.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Gmail samples") - .build(); + // Create the gmail API client + Gmail service = new Gmail.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Gmail samples") + .build(); - // Create the email content - String messageSubject = "Test message"; - String bodyText = "lorem ipsum."; + // Create the email content + String messageSubject = "Test message"; + String bodyText = "lorem ipsum."; - // Encode as MIME message - Properties props = new Properties(); - Session session = Session.getDefaultInstance(props, null); - MimeMessage email = new MimeMessage(session); - email.setFrom(new InternetAddress(fromEmailAddress)); - email.addRecipient(javax.mail.Message.RecipientType.TO, - new InternetAddress(toEmailAddress)); - email.setSubject(messageSubject); + // Encode as MIME message + Properties props = new Properties(); + Session session = Session.getDefaultInstance(props, null); + MimeMessage email = new MimeMessage(session); + email.setFrom(new InternetAddress(fromEmailAddress)); + email.addRecipient(javax.mail.Message.RecipientType.TO, + new InternetAddress(toEmailAddress)); + email.setSubject(messageSubject); - MimeBodyPart mimeBodyPart = new MimeBodyPart(); - mimeBodyPart.setContent(bodyText, "text/plain"); - Multipart multipart = new MimeMultipart(); - multipart.addBodyPart(mimeBodyPart); - mimeBodyPart = new MimeBodyPart(); - DataSource source = new FileDataSource(file); - mimeBodyPart.setDataHandler(new DataHandler(source)); - mimeBodyPart.setFileName(file.getName()); - multipart.addBodyPart(mimeBodyPart); - email.setContent(multipart); + MimeBodyPart mimeBodyPart = new MimeBodyPart(); + mimeBodyPart.setContent(bodyText, "text/plain"); + Multipart multipart = new MimeMultipart(); + multipart.addBodyPart(mimeBodyPart); + mimeBodyPart = new MimeBodyPart(); + DataSource source = new FileDataSource(file); + mimeBodyPart.setDataHandler(new DataHandler(source)); + mimeBodyPart.setFileName(file.getName()); + multipart.addBodyPart(mimeBodyPart); + email.setContent(multipart); - // Encode and wrap the MIME message into a gmail message - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - email.writeTo(buffer); - byte[] rawMessageBytes = buffer.toByteArray(); - String encodedEmail = Base64.encodeBase64URLSafeString(rawMessageBytes); - Message message = new Message(); - message.setRaw(encodedEmail); + // Encode and wrap the MIME message into a gmail message + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + email.writeTo(buffer); + byte[] rawMessageBytes = buffer.toByteArray(); + String encodedEmail = Base64.encodeBase64URLSafeString(rawMessageBytes); + Message message = new Message(); + message.setRaw(encodedEmail); - try { - // Create send message - message = service.users().messages().send("me", message).execute(); - System.out.println("Message id: " + message.getId()); - System.out.println(message.toPrettyString()); - return message; - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 403) { - System.err.println("Unable to send message: " + e.getDetails()); - } else { - throw e; - } - } - return null; + try { + // Create send message + message = service.users().messages().send("me", message).execute(); + System.out.println("Message id: " + message.getId()); + System.out.println(message.toPrettyString()); + return message; + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 403) { + System.err.println("Unable to send message: " + e.getDetails()); + } else { + throw e; + } } + return null; + } } // [END gmail_send_message_with_attachment] \ No newline at end of file diff --git a/gmail/snippets/src/main/java/UpdateSignature.java b/gmail/snippets/src/main/java/UpdateSignature.java index ca21e77e..3f5bf92e 100644 --- a/gmail/snippets/src/main/java/UpdateSignature.java +++ b/gmail/snippets/src/main/java/UpdateSignature.java @@ -14,6 +14,7 @@ // [START gmail_update_signature] + import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; @@ -21,64 +22,64 @@ import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.gmail.Gmail; import com.google.api.services.gmail.GmailScopes; -import com.google.api.services.gmail.model.SendAs; import com.google.api.services.gmail.model.ListSendAsResponse; +import com.google.api.services.gmail.model.SendAs; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; /* Class to demonstrate the use of Gmail Update Signature API */ public class UpdateSignature { - /** - * Update the gmail signature. - * - * @return the updated signature id , {@code null} otherwise. - * @throws IOException - if service account credentials file not found. - */ - public static String updateGmailSignature() throws IOException { + /** + * Update the gmail signature. + * + * @return the updated signature id , {@code null} otherwise. + * @throws IOException - if service account credentials file not found. + */ + public static String updateGmailSignature() 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(GmailScopes.GMAIL_SETTINGS_BASIC); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(GmailScopes.GMAIL_SETTINGS_BASIC); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials); - // Create the gmail API client - Gmail service = new Gmail.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Gmail samples") - .build(); + // Create the gmail API client + Gmail service = new Gmail.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Gmail samples") + .build(); - try { - SendAs primaryAlias = null; - ListSendAsResponse aliases = service.users().settings().sendAs().list("me").execute(); - for (SendAs alias : aliases.getSendAs()) { - if (alias.getIsPrimary()) { - primaryAlias = alias; - break; - } - } - // Updating a new signature - SendAs aliasSettings = new SendAs().setSignature("Automated Signature"); - SendAs result = service.users().settings().sendAs().patch( - "me", - primaryAlias.getSendAsEmail(), - aliasSettings) - .execute(); - //Prints the updated signature - System.out.println("Updated signature - " + result.getSignature()); - return result.getSignature(); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 403) { - System.err.println("Unable to update signature: " + e.getDetails()); - } else { - throw e; - } + try { + SendAs primaryAlias = null; + ListSendAsResponse aliases = service.users().settings().sendAs().list("me").execute(); + for (SendAs alias : aliases.getSendAs()) { + if (alias.getIsPrimary()) { + primaryAlias = alias; + break; } - return null; + } + // Updating a new signature + SendAs aliasSettings = new SendAs().setSignature("Automated Signature"); + SendAs result = service.users().settings().sendAs().patch( + "me", + primaryAlias.getSendAsEmail(), + aliasSettings) + .execute(); + //Prints the updated signature + System.out.println("Updated signature - " + result.getSignature()); + return result.getSignature(); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 403) { + System.err.println("Unable to update signature: " + e.getDetails()); + } else { + throw e; + } } + return null; + } } // [END gmail_update_signature] \ No newline at end of file diff --git a/gmail/snippets/src/main/java/UpdateSmimeCerts.java b/gmail/snippets/src/main/java/UpdateSmimeCerts.java index cd9ccb2c..0a92ce8a 100644 --- a/gmail/snippets/src/main/java/UpdateSmimeCerts.java +++ b/gmail/snippets/src/main/java/UpdateSmimeCerts.java @@ -14,6 +14,7 @@ // [START gmail_update_smime_certs] + import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; @@ -23,121 +24,121 @@ import com.google.api.services.gmail.model.SmimeInfo; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; -import java.util.Collections; /* Class to demonstrate the use of Gmail Update Smime Certificate API*/ public class UpdateSmimeCerts { - /** - * Update S/MIME certificates for the user. - * - *

First performs a lookup of all certificates for a user. If there are no certificates, or - * they all expire before the specified date/time, uploads the certificate in the specified file. - * If the default certificate is expired or there was no default set, chooses the certificate with - * the expiration furthest into the future and sets it as default. - * - * @param userId User's email address. - * @param sendAsEmail The "send as" email address, or None if it should be the same as user_id. - * @param certFilename Name of the file containing the S/MIME certificate. - * @param certPassword Password for the certificate file, or None if the file is not - * password-protected. - * @param expireTime DateTime object against which the certificate expiration is compared. If - * None, uses the current time. @ returns: The ID of the default certificate. - * @return The ID of the default certificate, {@code null} otherwise. - * @throws IOException - if service account credentials file not found. - */ - public static String updateSmimeCerts(String userId, - String sendAsEmail, - String certFilename, - String certPassword, - LocalDateTime expireTime) - throws IOException { + /** + * Update S/MIME certificates for the user. + * + *

First performs a lookup of all certificates for a user. If there are no certificates, or + * they all expire before the specified date/time, uploads the certificate in the specified file. + * If the default certificate is expired or there was no default set, chooses the certificate with + * the expiration furthest into the future and sets it as default. + * + * @param userId User's email address. + * @param sendAsEmail The "send as" email address, or None if it should be the same as user_id. + * @param certFilename Name of the file containing the S/MIME certificate. + * @param certPassword Password for the certificate file, or None if the file is not + * password-protected. + * @param expireTime DateTime object against which the certificate expiration is compared. If + * None, uses the current time. @ returns: The ID of the default certificate. + * @return The ID of the default certificate, {@code null} otherwise. + * @throws IOException - if service account credentials file not found. + */ + public static String updateSmimeCerts(String userId, + String sendAsEmail, + String certFilename, + String certPassword, + LocalDateTime expireTime) + 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(GmailScopes.GMAIL_SETTINGS_SHARING); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(GmailScopes.GMAIL_SETTINGS_SHARING); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the gmail API client - Gmail service = new Gmail.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Gmail samples") - .build(); + // Create the gmail API client + Gmail service = new Gmail.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Gmail samples") + .build(); - if (sendAsEmail == null) { - sendAsEmail = userId; - } + if (sendAsEmail == null) { + sendAsEmail = userId; + } - ListSmimeInfoResponse listResults; - try { - listResults = service.users().settings().sendAs().smimeInfo().list(userId, sendAsEmail).execute(); - } catch (IOException e) { - System.err.printf("An error occurred during list: %s\n", e); - return null; - } + ListSmimeInfoResponse listResults; + try { + listResults = + service.users().settings().sendAs().smimeInfo().list(userId, sendAsEmail).execute(); + } catch (IOException e) { + System.err.printf("An error occurred during list: %s\n", e); + return null; + } - String defaultCertId = null; - String bestCertId = null; - LocalDateTime bestCertExpire = LocalDateTime.MIN; + String defaultCertId = null; + String bestCertId = null; + LocalDateTime bestCertExpire = LocalDateTime.MIN; - if (expireTime == null) { - expireTime = LocalDateTime.now(); - } - if (listResults != null && listResults.getSmimeInfo() != null) { - for (SmimeInfo smimeInfo : listResults.getSmimeInfo()) { - String certId = smimeInfo.getId(); - boolean isDefaultCert = smimeInfo.getIsDefault(); - if (isDefaultCert) { - defaultCertId = certId; - } - LocalDateTime exp = - LocalDateTime.ofInstant( - Instant.ofEpochMilli(smimeInfo.getExpiration()), ZoneId.systemDefault()); - if (exp.isAfter(expireTime)) { - if (exp.isAfter(bestCertExpire)) { - bestCertId = certId; - bestCertExpire = exp; - } - } else { - if (isDefaultCert) { - defaultCertId = null; - } - } - } + if (expireTime == null) { + expireTime = LocalDateTime.now(); + } + if (listResults != null && listResults.getSmimeInfo() != null) { + for (SmimeInfo smimeInfo : listResults.getSmimeInfo()) { + String certId = smimeInfo.getId(); + boolean isDefaultCert = smimeInfo.getIsDefault(); + if (isDefaultCert) { + defaultCertId = certId; } - if (defaultCertId == null) { - String defaultId = bestCertId; - if (defaultId == null && certFilename != null) { - SmimeInfo smimeInfo = CreateSmimeInfo.createSmimeInfo(certFilename, - certPassword); - SmimeInfo insertResults = InsertSmimeInfo.insertSmimeInfo(userId, - sendAsEmail, - smimeInfo); - if (insertResults != null) { - defaultId = insertResults.getId(); - } - } - - if (defaultId != null) { - try { - service.users().settings().sendAs().smimeInfo().setDefault(userId, sendAsEmail, defaultId).execute(); - return defaultId; - } catch (IOException e) { - System.err.printf("An error occured during setDefault: %s", e); - } - } + LocalDateTime exp = + LocalDateTime.ofInstant( + Instant.ofEpochMilli(smimeInfo.getExpiration()), ZoneId.systemDefault()); + if (exp.isAfter(expireTime)) { + if (exp.isAfter(bestCertExpire)) { + bestCertId = certId; + bestCertExpire = exp; + } } else { - return defaultCertId; + if (isDefaultCert) { + defaultCertId = null; + } + } + } + } + if (defaultCertId == null) { + String defaultId = bestCertId; + if (defaultId == null && certFilename != null) { + SmimeInfo smimeInfo = CreateSmimeInfo.createSmimeInfo(certFilename, + certPassword); + SmimeInfo insertResults = InsertSmimeInfo.insertSmimeInfo(userId, + sendAsEmail, + smimeInfo); + if (insertResults != null) { + defaultId = insertResults.getId(); } + } - return null; + if (defaultId != null) { + try { + service.users().settings().sendAs().smimeInfo().setDefault(userId, sendAsEmail, defaultId) + .execute(); + return defaultId; + } catch (IOException e) { + System.err.printf("An error occured during setDefault: %s", e); + } + } + } else { + return defaultCertId; } + + return null; + } } // [END gmail_update_smime_certs] \ No newline at end of file diff --git a/gmail/snippets/src/main/java/UpdateSmimeFromCsv.java b/gmail/snippets/src/main/java/UpdateSmimeFromCsv.java index efe3052b..70932b7a 100644 --- a/gmail/snippets/src/main/java/UpdateSmimeFromCsv.java +++ b/gmail/snippets/src/main/java/UpdateSmimeFromCsv.java @@ -14,44 +14,44 @@ // [START gmail_update_smime_from_csv] -import org.apache.commons.csv.CSVFormat; -import org.apache.commons.csv.CSVParser; -import org.apache.commons.csv.CSVRecord; import java.io.File; import java.time.LocalDateTime; +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVParser; +import org.apache.commons.csv.CSVRecord; /* Class to demonstrate the use of Gmail Update Certificate from CSV File */ public class UpdateSmimeFromCsv { - /** - * Update S/MIME certificates based on the contents of a CSV file. - * - *

Each row of the CSV file should contain a user ID, path to the certificate, and the - * certificate password. - * - * @param csvFilename Name of the CSV file. - * @param expireTime DateTime object against which the certificate expiration is compared. If - * None, uses the current time. - */ - public static void updateSmimeFromCsv(String csvFilename, LocalDateTime expireTime) { - try { - File csvFile = new File(csvFilename); - CSVParser parser = CSVParser.parse( csvFile, - java.nio.charset.StandardCharsets.UTF_8, - CSVFormat.DEFAULT.withHeader().withSkipHeaderRecord()); - for (CSVRecord record : parser) { - String userId = record.get(0); - String certFilename = record.get(1); - String certPassword = record.get(2); - UpdateSmimeCerts.updateSmimeCerts(userId, - userId, - certFilename, - certPassword, - expireTime); - } - } catch (Exception e) { - System.err.printf("An error occured while reading the CSV file: %s", e); - } + /** + * Update S/MIME certificates based on the contents of a CSV file. + * + *

Each row of the CSV file should contain a user ID, path to the certificate, and the + * certificate password. + * + * @param csvFilename Name of the CSV file. + * @param expireTime DateTime object against which the certificate expiration is compared. If + * None, uses the current time. + */ + public static void updateSmimeFromCsv(String csvFilename, LocalDateTime expireTime) { + try { + File csvFile = new File(csvFilename); + CSVParser parser = CSVParser.parse(csvFile, + java.nio.charset.StandardCharsets.UTF_8, + CSVFormat.DEFAULT.withHeader().withSkipHeaderRecord()); + for (CSVRecord record : parser) { + String userId = record.get(0); + String certFilename = record.get(1); + String certPassword = record.get(2); + UpdateSmimeCerts.updateSmimeCerts(userId, + userId, + certFilename, + certPassword, + expireTime); + } + } catch (Exception e) { + System.err.printf("An error occured while reading the CSV file: %s", e); } + } } // [END gmail_update_smime_from_csv] \ No newline at end of file diff --git a/gmail/snippets/src/test/java/BaseTest.java b/gmail/snippets/src/test/java/BaseTest.java index 3fc90c8b..fbba7f1c 100644 --- a/gmail/snippets/src/test/java/BaseTest.java +++ b/gmail/snippets/src/test/java/BaseTest.java @@ -21,45 +21,45 @@ import com.google.api.services.gmail.GmailScopes; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; -import org.junit.Before; import java.io.IOException; +import org.junit.Before; public class BaseTest { - public static final String TEST_USER = "ci-test01@workspacesamples.dev"; - public static final String RECIPIENT = "gduser1@workspacesamples.dev"; - public static final String FORWARDING_ADDRESS = "gduser1@workspacesamples.dev"; + public static final String TEST_USER = "ci-test01@workspacesamples.dev"; + public static final String RECIPIENT = "gduser1@workspacesamples.dev"; + public static final String FORWARDING_ADDRESS = "gduser1@workspacesamples.dev"; - protected Gmail service; + protected Gmail service; - /** - * Create a default authorization Gmail client service. - * - * @return an authorized Gmail client service - * @throws IOException - if credentials file not found. - */ - public Gmail buildService() throws IOException { + /** + * Create a default authorization Gmail client service. + * + * @return an authorized Gmail client service + * @throws IOException - if credentials file not found. + */ + public Gmail 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(GmailScopes.GMAIL_SETTINGS_BASIC, - GmailScopes.GMAIL_COMPOSE, - GmailScopes.GMAIL_SETTINGS_SHARING, - GmailScopes.GMAIL_LABELS); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(GmailScopes.GMAIL_SETTINGS_BASIC, + GmailScopes.GMAIL_COMPOSE, + GmailScopes.GMAIL_SETTINGS_SHARING, + GmailScopes.GMAIL_LABELS); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials); - // Create the Gmail API client - Gmail service = new Gmail.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Gmail API Snippets") - .build(); - return service; - } + // Create the Gmail API client + Gmail service = new Gmail.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Gmail API Snippets") + .build(); + return service; + } - @Before - public void setupService() throws IOException { - this.service = buildService(); - } + @Before + public void setupService() throws IOException { + this.service = buildService(); + } } diff --git a/gmail/snippets/src/test/java/TestCreateDraft.java b/gmail/snippets/src/test/java/TestCreateDraft.java index e3eb2fb2..71e56eb9 100644 --- a/gmail/snippets/src/test/java/TestCreateDraft.java +++ b/gmail/snippets/src/test/java/TestCreateDraft.java @@ -13,19 +13,20 @@ // limitations under the License. +import static org.junit.Assert.assertNotNull; + import com.google.api.services.gmail.model.Draft; -import org.junit.Test; -import javax.mail.MessagingException; import java.io.IOException; -import static org.junit.Assert.assertNotNull; +import javax.mail.MessagingException; +import org.junit.Test; // Unit testcase for gmail create draft snippet -public class TestCreateDraft extends BaseTest{ +public class TestCreateDraft extends BaseTest { - @Test - public void testCreateDraft() throws MessagingException, IOException { - Draft draft = CreateDraft.createDraftMessage(RECIPIENT,TEST_USER); - assertNotNull(draft); - this.service.users().drafts().delete("me", draft.getId()).execute(); - } + @Test + public void testCreateDraft() throws MessagingException, IOException { + Draft draft = CreateDraft.createDraftMessage(RECIPIENT, TEST_USER); + assertNotNull(draft); + this.service.users().drafts().delete("me", draft.getId()).execute(); + } } diff --git a/gmail/snippets/src/test/java/TestCreateDraftWithAttachment.java b/gmail/snippets/src/test/java/TestCreateDraftWithAttachment.java index d0031682..065c64c6 100644 --- a/gmail/snippets/src/test/java/TestCreateDraftWithAttachment.java +++ b/gmail/snippets/src/test/java/TestCreateDraftWithAttachment.java @@ -13,21 +13,22 @@ // limitations under the License. +import static org.junit.Assert.assertNotNull; + import com.google.api.services.gmail.model.Draft; -import org.junit.Test; -import javax.mail.MessagingException; import java.io.IOException; -import static org.junit.Assert.assertNotNull; +import javax.mail.MessagingException; +import org.junit.Test; // Unit testcase for gmail create draft with attachment snippet -public class TestCreateDraftWithAttachment extends BaseTest{ +public class TestCreateDraftWithAttachment extends BaseTest { - @Test - public void testCreateDraftWithAttachment() throws MessagingException, IOException { - Draft draft = CreateDraftWithAttachment.createDraftMessageWithAttachment(RECIPIENT, - TEST_USER, - new java.io.File("files/photo.jpg")); - assertNotNull(draft); - this.service.users().drafts().delete(TEST_USER, draft.getId()).execute(); - } + @Test + public void testCreateDraftWithAttachment() throws MessagingException, IOException { + Draft draft = CreateDraftWithAttachment.createDraftMessageWithAttachment(RECIPIENT, + TEST_USER, + new java.io.File("files/photo.jpg")); + assertNotNull(draft); + this.service.users().drafts().delete(TEST_USER, draft.getId()).execute(); + } } diff --git a/gmail/snippets/src/test/java/TestCreateEmail.java b/gmail/snippets/src/test/java/TestCreateEmail.java index 1248aa35..043397a0 100644 --- a/gmail/snippets/src/test/java/TestCreateEmail.java +++ b/gmail/snippets/src/test/java/TestCreateEmail.java @@ -13,25 +13,26 @@ // limitations under the License. -import org.junit.Test; +import static org.junit.Assert.assertEquals; + +import java.io.IOException; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; -import java.io.IOException; -import static org.junit.Assert.assertEquals; +import org.junit.Test; // Unit testcase for gmail create email snippet -public class TestCreateEmail extends BaseTest{ +public class TestCreateEmail extends BaseTest { - @Test - public void createEmail() throws MessagingException, IOException { - MimeMessage mimeMessage = CreateEmail.createEmail(RECIPIENT, - TEST_USER, - "test", - "Hello!"); - assertEquals("test", mimeMessage.getSubject()); - assertEquals("Hello!", mimeMessage.getContent()); - assertEquals(RECIPIENT, mimeMessage.getRecipients(Message.RecipientType.TO)[0].toString()); - assertEquals(TEST_USER, mimeMessage.getFrom()[0].toString()); - } + @Test + public void createEmail() throws MessagingException, IOException { + MimeMessage mimeMessage = CreateEmail.createEmail(RECIPIENT, + TEST_USER, + "test", + "Hello!"); + assertEquals("test", mimeMessage.getSubject()); + assertEquals("Hello!", mimeMessage.getContent()); + assertEquals(RECIPIENT, mimeMessage.getRecipients(Message.RecipientType.TO)[0].toString()); + assertEquals(TEST_USER, mimeMessage.getFrom()[0].toString()); + } } diff --git a/gmail/snippets/src/test/java/TestCreateFilter.java b/gmail/snippets/src/test/java/TestCreateFilter.java index b345afa1..fbf72c2b 100644 --- a/gmail/snippets/src/test/java/TestCreateFilter.java +++ b/gmail/snippets/src/test/java/TestCreateFilter.java @@ -13,48 +13,49 @@ // limitations under the License. +import static org.junit.Assert.assertNotNull; + import com.google.api.services.gmail.model.Label; import com.google.api.services.gmail.model.ListLabelsResponse; +import java.io.IOException; import org.junit.After; import org.junit.Before; import org.junit.Test; -import java.io.IOException; -import static org.junit.Assert.assertNotNull; // Unit testcase for gmail create filter snippet public class TestCreateFilter extends BaseTest { - private Label testLabel = null; - - @Before - public void createLabel() throws IOException { - ListLabelsResponse response = this.service.users().labels().list("me").execute(); - for (Label l : response.getLabels()) { - if (l.getName().equals("testLabel")) { - testLabel = l; - } - } - if (testLabel == null) { - Label label = new Label() - .setName("testLabel") - .setLabelListVisibility("labelShow") - .setMessageListVisibility("show"); - testLabel = this.service.users().labels().create("me", label).execute(); - } - } + private Label testLabel = null; - @After - public void deleteLabel() throws IOException { - if (testLabel != null) { - this.service.users().labels().delete("me", testLabel.getId()).execute(); - testLabel = null; - } + @Before + public void createLabel() throws IOException { + ListLabelsResponse response = this.service.users().labels().list("me").execute(); + for (Label l : response.getLabels()) { + if (l.getName().equals("testLabel")) { + testLabel = l; + } } + if (testLabel == null) { + Label label = new Label() + .setName("testLabel") + .setLabelListVisibility("labelShow") + .setMessageListVisibility("show"); + testLabel = this.service.users().labels().create("me", label).execute(); + } + } - @Test - public void testCreateNewFilter() throws IOException { - String id = CreateFilter.createNewFilter(testLabel.getId()); - assertNotNull(id); - this.service.users().settings().filters().delete("me", id).execute(); + @After + public void deleteLabel() throws IOException { + if (testLabel != null) { + this.service.users().labels().delete("me", testLabel.getId()).execute(); + testLabel = null; } + } + + @Test + public void testCreateNewFilter() throws IOException { + String id = CreateFilter.createNewFilter(testLabel.getId()); + assertNotNull(id); + this.service.users().settings().filters().delete("me", id).execute(); + } } diff --git a/gmail/snippets/src/test/java/TestCreateMessage.java b/gmail/snippets/src/test/java/TestCreateMessage.java index 775e7c1f..d31bd75e 100644 --- a/gmail/snippets/src/test/java/TestCreateMessage.java +++ b/gmail/snippets/src/test/java/TestCreateMessage.java @@ -12,24 +12,26 @@ // See the License for the specific language governing permissions and // limitations under the License. -import org.junit.Test; +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; -import java.io.IOException; -import static org.junit.Assert.assertNotNull; +import org.junit.Test; // Unit testcase for gmail create message snippet -public class TestCreateMessage extends BaseTest{ +public class TestCreateMessage extends BaseTest { - @Test - public void testCreateMessageWithEmail() throws MessagingException, - IOException { - MimeMessage mimeMessage = CreateEmail.createEmail(RECIPIENT, - TEST_USER, - "test", - "Hello!"); + @Test + public void testCreateMessageWithEmail() throws MessagingException, + IOException { + MimeMessage mimeMessage = CreateEmail.createEmail(RECIPIENT, + TEST_USER, + "test", + "Hello!"); - com.google.api.services.gmail.model.Message message = CreateMessage.createMessageWithEmail(mimeMessage); - assertNotNull(message.getRaw()); // Weak assertion... - } + com.google.api.services.gmail.model.Message message = + CreateMessage.createMessageWithEmail(mimeMessage); + assertNotNull(message.getRaw()); // Weak assertion... + } } diff --git a/gmail/snippets/src/test/java/TestCreateSmimeInfo.java b/gmail/snippets/src/test/java/TestCreateSmimeInfo.java index 5357536e..6e304814 100644 --- a/gmail/snippets/src/test/java/TestCreateSmimeInfo.java +++ b/gmail/snippets/src/test/java/TestCreateSmimeInfo.java @@ -13,54 +13,54 @@ // limitations under the License. -import com.google.api.services.gmail.model.SmimeInfo; -import org.junit.Test; -import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import com.google.api.services.gmail.model.SmimeInfo; +import org.junit.Test; + // Unit testcase for gmail create smime info snippet public class TestCreateSmimeInfo { - @Test - public void testCreateSmimeInfo() { - SmimeInfo smimeInfo = CreateSmimeInfo.createSmimeInfo( - "files/cert.p12", - null /* password */); + @Test + public void testCreateSmimeInfo() { + SmimeInfo smimeInfo = CreateSmimeInfo.createSmimeInfo( + "files/cert.p12", + null /* password */); - assertNotNull(smimeInfo); - assertNull(smimeInfo.getEncryptedKeyPassword()); - assertNull(smimeInfo.getExpiration()); - assertNull(smimeInfo.getId()); - assertNull(smimeInfo.getIsDefault()); - assertNull(smimeInfo.getIssuerCn()); - assertNull(smimeInfo.getPem()); - assertThat(smimeInfo.getPkcs12().length(), greaterThan(0)); - } + assertNotNull(smimeInfo); + assertNull(smimeInfo.getEncryptedKeyPassword()); + assertNull(smimeInfo.getExpiration()); + assertNull(smimeInfo.getId()); + assertNull(smimeInfo.getIsDefault()); + assertNull(smimeInfo.getIssuerCn()); + assertNull(smimeInfo.getPem()); + assertThat(smimeInfo.getPkcs12().length(), greaterThan(0)); + } - @Test - public void testCreateSmimeInfoWithPassword() { - SmimeInfo smimeInfo = CreateSmimeInfo.createSmimeInfo( - "files/cert.p12", - "certpass"); + @Test + public void testCreateSmimeInfoWithPassword() { + SmimeInfo smimeInfo = CreateSmimeInfo.createSmimeInfo( + "files/cert.p12", + "certpass"); - assertNotNull(smimeInfo); - assertEquals(smimeInfo.getEncryptedKeyPassword(), "certpass"); - assertNull(smimeInfo.getExpiration()); - assertNull(smimeInfo.getId()); - assertNull(smimeInfo.getIsDefault()); - assertNull(smimeInfo.getIssuerCn()); - assertNull(smimeInfo.getPem()); - assertThat(smimeInfo.getPkcs12().length(), greaterThan(0)); - } + assertNotNull(smimeInfo); + assertEquals(smimeInfo.getEncryptedKeyPassword(), "certpass"); + assertNull(smimeInfo.getExpiration()); + assertNull(smimeInfo.getId()); + assertNull(smimeInfo.getIsDefault()); + assertNull(smimeInfo.getIssuerCn()); + assertNull(smimeInfo.getPem()); + assertThat(smimeInfo.getPkcs12().length(), greaterThan(0)); + } - @Test - public void testCreateSmimeInfoFileNotFound() { - SmimeInfo smimeInfo = CreateSmimeInfo.createSmimeInfo( - "files/notfound.p12", - null /* password */); - assertNull(smimeInfo); - } + @Test + public void testCreateSmimeInfoFileNotFound() { + SmimeInfo smimeInfo = CreateSmimeInfo.createSmimeInfo( + "files/notfound.p12", + null /* password */); + assertNull(smimeInfo); + } } diff --git a/gmail/snippets/src/test/java/TestEnableAutoReply.java b/gmail/snippets/src/test/java/TestEnableAutoReply.java index c961b734..829e4c6d 100644 --- a/gmail/snippets/src/test/java/TestEnableAutoReply.java +++ b/gmail/snippets/src/test/java/TestEnableAutoReply.java @@ -12,17 +12,18 @@ // See the License for the specific language governing permissions and // limitations under the License. +import static org.junit.Assert.assertNotNull; + import com.google.api.services.gmail.model.VacationSettings; -import org.junit.Test; import java.io.IOException; -import static org.junit.Assert.assertNotNull; +import org.junit.Test; // Unit testcase for gmail enable auto reply snippet public class TestEnableAutoReply extends BaseTest { - @Test - public void testAutoReply() throws IOException { - VacationSettings settings = EnableAutoReply.autoReply(); - assertNotNull(settings); - } + @Test + public void testAutoReply() throws IOException { + VacationSettings settings = EnableAutoReply.autoReply(); + assertNotNull(settings); + } } \ No newline at end of file diff --git a/gmail/snippets/src/test/java/TestEnableForwarding.java b/gmail/snippets/src/test/java/TestEnableForwarding.java index 6250c13c..b7719fc3 100644 --- a/gmail/snippets/src/test/java/TestEnableForwarding.java +++ b/gmail/snippets/src/test/java/TestEnableForwarding.java @@ -13,30 +13,32 @@ // limitations under the License. +import static org.junit.Assert.assertNotNull; + import com.google.api.services.gmail.model.AutoForwarding; +import java.io.IOException; import org.junit.Before; import org.junit.Test; -import java.io.IOException; -import static org.junit.Assert.assertNotNull; // Unit testcase for gmail enable forwarding snippet public class TestEnableForwarding extends BaseTest { - @Test - public void TestEnableAutoForwarding() throws IOException { - AutoForwarding forwarding = EnableForwarding.enableAutoForwarding(FORWARDING_ADDRESS); - assertNotNull(forwarding); - } + @Test + public void TestEnableAutoForwarding() throws IOException { + AutoForwarding forwarding = EnableForwarding.enableAutoForwarding(FORWARDING_ADDRESS); + assertNotNull(forwarding); + } - @Before - public void cleanup() { - try { - AutoForwarding forwarding = new AutoForwarding().setEnabled(false); - this.service.users().settings().updateAutoForwarding("me", forwarding).execute(); - this.service.users().settings().forwardingAddresses().delete("me", FORWARDING_ADDRESS).execute(); - } catch (Exception e) { - // Ignore -- resources might not exist - e.printStackTrace(); - } + @Before + public void cleanup() { + try { + AutoForwarding forwarding = new AutoForwarding().setEnabled(false); + this.service.users().settings().updateAutoForwarding("me", forwarding).execute(); + this.service.users().settings().forwardingAddresses().delete("me", FORWARDING_ADDRESS) + .execute(); + } catch (Exception e) { + // Ignore -- resources might not exist + e.printStackTrace(); } + } } diff --git a/gmail/snippets/src/test/java/TestInsertCertFromCsv.java b/gmail/snippets/src/test/java/TestInsertCertFromCsv.java index 2853cc2e..2a1ccc60 100644 --- a/gmail/snippets/src/test/java/TestInsertCertFromCsv.java +++ b/gmail/snippets/src/test/java/TestInsertCertFromCsv.java @@ -12,91 +12,100 @@ // See the License for the specific language governing permissions and // limitations under the License. +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import com.google.api.services.gmail.Gmail; import com.google.api.services.gmail.model.SmimeInfo; +import java.io.IOException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; -import java.io.IOException; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.*; // Unit testcase for gmail insert cert from csv snippet -public class TestInsertCertFromCsv extends BaseTest{ - - private static final long CURRENT_TIME_MS = 1234567890; - public static final String TEST_USER1 = "gduser1@workspacesamples.dev"; - public static final String TEST_USER2 = "gduser2@workspacesamples.dev"; - - @Mock - private Gmail mockService; - @Mock private Gmail.Users mockUsers; - @Mock private Gmail.Users.Settings mockSettings; - @Mock private Gmail.Users.Settings.SendAs mockSendAs; - @Mock private Gmail.Users.Settings.SendAs.SmimeInfo mockSmimeInfo; - @Mock private Gmail.Users.Settings.SendAs.SmimeInfo.Delete mockDelete; - @Mock private Gmail.Users.Settings.SendAs.SmimeInfo.Get mockGet; - @Mock private Gmail.Users.Settings.SendAs.SmimeInfo.Insert mockInsert; - @Mock private Gmail.Users.Settings.SendAs.SmimeInfo.List mockList; - @Mock private Gmail.Users.Settings.SendAs.SmimeInfo.SetDefault mockSetDefault; - - @Rule - public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Before - public void setup() throws IOException { - when(mockService.users()).thenReturn(mockUsers); - when(mockUsers.settings()).thenReturn(mockSettings); - when(mockSettings.sendAs()).thenReturn(mockSendAs); - when(mockSendAs.smimeInfo()).thenReturn(mockSmimeInfo); - - when(mockSmimeInfo.delete(any(), any(), any())).thenReturn(mockDelete); - when(mockSmimeInfo.get(any(), any(), any())).thenReturn(mockGet); - when(mockSmimeInfo.insert(any(), any(), any())).thenReturn(mockInsert); - when(mockSmimeInfo.list(any(), any())).thenReturn(mockList); - when(mockSmimeInfo.setDefault(any(), any(), any())).thenReturn(mockSetDefault); - } - - @Test - public void testInsertSmimeFromCsv() throws IOException { - when(mockInsert.execute()).thenReturn(makeFakeInsertResult()); - InsertCertFromCsv.insertCertFromCsv("files/certs.csv"); - - verifySmimeApiCalled(2); - verify(mockSmimeInfo).insert(eq(TEST_USER1), eq(TEST_USER1), any()); - verify(mockSmimeInfo).insert(eq(TEST_USER2), eq(TEST_USER2), any()); - verify(mockInsert, times(2)).execute(); - } - - @Test - public void testInsertSmimeFromCsvFails() throws IOException { - when(mockInsert.execute()).thenReturn(makeFakeInsertResult()); - - InsertCertFromCsv.insertCertFromCsv("files/notfound.csv"); - } - - private void verifySmimeApiCalled(int numCalls) { - verify(mockService, times(numCalls)).users(); - verify(mockUsers, times(numCalls)).settings(); - verify(mockSettings, times(numCalls)).sendAs(); - verify(mockSendAs, times(numCalls)).smimeInfo(); - } - - private SmimeInfo makeFakeInsertResult(String id, boolean isDefault, long expiration) { - SmimeInfo insertResult = new SmimeInfo(); - insertResult.setId(id); - insertResult.setIsDefault(isDefault); - insertResult.setExpiration(expiration); - - return insertResult; - } - - private SmimeInfo makeFakeInsertResult() { - return makeFakeInsertResult("new_certificate_id", false, CURRENT_TIME_MS + 1); - } +public class TestInsertCertFromCsv extends BaseTest { + + public static final String TEST_USER1 = "gduser1@workspacesamples.dev"; + public static final String TEST_USER2 = "gduser2@workspacesamples.dev"; + private static final long CURRENT_TIME_MS = 1234567890; + @Rule + public MockitoRule mockitoRule = MockitoJUnit.rule(); + @Mock + private Gmail mockService; + @Mock + private Gmail.Users mockUsers; + @Mock + private Gmail.Users.Settings mockSettings; + @Mock + private Gmail.Users.Settings.SendAs mockSendAs; + @Mock + private Gmail.Users.Settings.SendAs.SmimeInfo mockSmimeInfo; + @Mock + private Gmail.Users.Settings.SendAs.SmimeInfo.Delete mockDelete; + @Mock + private Gmail.Users.Settings.SendAs.SmimeInfo.Get mockGet; + @Mock + private Gmail.Users.Settings.SendAs.SmimeInfo.Insert mockInsert; + @Mock + private Gmail.Users.Settings.SendAs.SmimeInfo.List mockList; + @Mock + private Gmail.Users.Settings.SendAs.SmimeInfo.SetDefault mockSetDefault; + + @Before + public void setup() throws IOException { + when(mockService.users()).thenReturn(mockUsers); + when(mockUsers.settings()).thenReturn(mockSettings); + when(mockSettings.sendAs()).thenReturn(mockSendAs); + when(mockSendAs.smimeInfo()).thenReturn(mockSmimeInfo); + + when(mockSmimeInfo.delete(any(), any(), any())).thenReturn(mockDelete); + when(mockSmimeInfo.get(any(), any(), any())).thenReturn(mockGet); + when(mockSmimeInfo.insert(any(), any(), any())).thenReturn(mockInsert); + when(mockSmimeInfo.list(any(), any())).thenReturn(mockList); + when(mockSmimeInfo.setDefault(any(), any(), any())).thenReturn(mockSetDefault); + } + + @Test + public void testInsertSmimeFromCsv() throws IOException { + when(mockInsert.execute()).thenReturn(makeFakeInsertResult()); + InsertCertFromCsv.insertCertFromCsv("files/certs.csv"); + + verifySmimeApiCalled(2); + verify(mockSmimeInfo).insert(eq(TEST_USER1), eq(TEST_USER1), any()); + verify(mockSmimeInfo).insert(eq(TEST_USER2), eq(TEST_USER2), any()); + verify(mockInsert, times(2)).execute(); + } + + @Test + public void testInsertSmimeFromCsvFails() throws IOException { + when(mockInsert.execute()).thenReturn(makeFakeInsertResult()); + + InsertCertFromCsv.insertCertFromCsv("files/notfound.csv"); + } + + private void verifySmimeApiCalled(int numCalls) { + verify(mockService, times(numCalls)).users(); + verify(mockUsers, times(numCalls)).settings(); + verify(mockSettings, times(numCalls)).sendAs(); + verify(mockSendAs, times(numCalls)).smimeInfo(); + } + + private SmimeInfo makeFakeInsertResult(String id, boolean isDefault, long expiration) { + SmimeInfo insertResult = new SmimeInfo(); + insertResult.setId(id); + insertResult.setIsDefault(isDefault); + insertResult.setExpiration(expiration); + + return insertResult; + } + + private SmimeInfo makeFakeInsertResult() { + return makeFakeInsertResult("new_certificate_id", false, CURRENT_TIME_MS + 1); + } } diff --git a/gmail/snippets/src/test/java/TestInsertSmimeInfo.java b/gmail/snippets/src/test/java/TestInsertSmimeInfo.java index 3c70b89a..360174e7 100644 --- a/gmail/snippets/src/test/java/TestInsertSmimeInfo.java +++ b/gmail/snippets/src/test/java/TestInsertSmimeInfo.java @@ -12,106 +12,115 @@ // See the License for the specific language governing permissions and // limitations under the License. +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import com.google.api.services.gmail.Gmail; import com.google.api.services.gmail.model.SmimeInfo; +import java.io.IOException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; -import java.io.IOException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.*; -import static org.mockito.Mockito.times; // Unit testcase for gmail insert smime info snippet -public class TestInsertSmimeInfo extends BaseTest{ - - private static final long CURRENT_TIME_MS = 1234567890; - - @Mock private Gmail mockService; - @Mock private Gmail.Users mockUsers; - @Mock private Gmail.Users.Settings mockSettings; - @Mock private Gmail.Users.Settings.SendAs mockSendAs; - @Mock private Gmail.Users.Settings.SendAs.SmimeInfo mockSmimeInfo; - @Mock private Gmail.Users.Settings.SendAs.SmimeInfo.Delete mockDelete; - @Mock private Gmail.Users.Settings.SendAs.SmimeInfo.Get mockGet; - @Mock private Gmail.Users.Settings.SendAs.SmimeInfo.Insert mockInsert; - @Mock private Gmail.Users.Settings.SendAs.SmimeInfo.List mockList; - @Mock private Gmail.Users.Settings.SendAs.SmimeInfo.SetDefault mockSetDefault; - - @Rule - public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Before - public void setup() throws IOException { - when(mockService.users()).thenReturn(mockUsers); - when(mockUsers.settings()).thenReturn(mockSettings); - when(mockSettings.sendAs()).thenReturn(mockSendAs); - when(mockSendAs.smimeInfo()).thenReturn(mockSmimeInfo); - - when(mockSmimeInfo.delete(any(), any(), any())).thenReturn(mockDelete); - when(mockSmimeInfo.get(any(), any(), any())).thenReturn(mockGet); - when(mockSmimeInfo.insert(any(), any(), any())).thenReturn(mockInsert); - when(mockSmimeInfo.list(any(), any())).thenReturn(mockList); - when(mockSmimeInfo.setDefault(any(), any(), any())).thenReturn(mockSetDefault); - } - - @Test - public void testInsertSmimeInfo() throws IOException { - SmimeInfo insertResult = makeFakeInsertResult(); - when(mockInsert.execute()).thenReturn(insertResult); - - SmimeInfo smimeInfo = CreateSmimeInfo.createSmimeInfo("files/cert.p12", - null /* password */); - SmimeInfo result = InsertSmimeInfo.insertSmimeInfo(TEST_USER, - TEST_USER, - smimeInfo); - verifySmimeApiCalled(1); - verify(mockSmimeInfo).insert(eq(TEST_USER), eq(TEST_USER), eq(smimeInfo)); - verify(mockInsert).execute(); - - assertEquals(insertResult, result); - } - - @Test - public void testInsertSmimeInfoError() throws IOException { - when(mockInsert.execute()).thenThrow(IOException.class); - - SmimeInfo smimeInfo = CreateSmimeInfo.createSmimeInfo("files/cert.p12", - null /* password */); - SmimeInfo result = InsertSmimeInfo.insertSmimeInfo(TEST_USER, - TEST_USER, smimeInfo); - - verifySmimeApiCalled(1); - verify(mockSmimeInfo).insert(eq(TEST_USER), eq(TEST_USER), eq(smimeInfo)); - verify(mockInsert).execute(); - - assertNull(result); - } - - private void verifySmimeApiCalled(int numCalls) { - verify(mockService, times(numCalls)).users(); - verify(mockUsers, times(numCalls)).settings(); - verify(mockSettings, times(numCalls)).sendAs(); - verify(mockSendAs, times(numCalls)).smimeInfo(); - } - - private SmimeInfo makeFakeInsertResult(String id, boolean isDefault, long expiration) { - SmimeInfo insertResult = new SmimeInfo(); - insertResult.setId(id); - insertResult.setIsDefault(isDefault); - insertResult.setExpiration(expiration); - - return insertResult; - } - - private SmimeInfo makeFakeInsertResult() { - return makeFakeInsertResult("new_certificate_id", false, CURRENT_TIME_MS + 1); - } +public class TestInsertSmimeInfo extends BaseTest { + + private static final long CURRENT_TIME_MS = 1234567890; + @Rule + public MockitoRule mockitoRule = MockitoJUnit.rule(); + @Mock + private Gmail mockService; + @Mock + private Gmail.Users mockUsers; + @Mock + private Gmail.Users.Settings mockSettings; + @Mock + private Gmail.Users.Settings.SendAs mockSendAs; + @Mock + private Gmail.Users.Settings.SendAs.SmimeInfo mockSmimeInfo; + @Mock + private Gmail.Users.Settings.SendAs.SmimeInfo.Delete mockDelete; + @Mock + private Gmail.Users.Settings.SendAs.SmimeInfo.Get mockGet; + @Mock + private Gmail.Users.Settings.SendAs.SmimeInfo.Insert mockInsert; + @Mock + private Gmail.Users.Settings.SendAs.SmimeInfo.List mockList; + @Mock + private Gmail.Users.Settings.SendAs.SmimeInfo.SetDefault mockSetDefault; + + @Before + public void setup() throws IOException { + when(mockService.users()).thenReturn(mockUsers); + when(mockUsers.settings()).thenReturn(mockSettings); + when(mockSettings.sendAs()).thenReturn(mockSendAs); + when(mockSendAs.smimeInfo()).thenReturn(mockSmimeInfo); + + when(mockSmimeInfo.delete(any(), any(), any())).thenReturn(mockDelete); + when(mockSmimeInfo.get(any(), any(), any())).thenReturn(mockGet); + when(mockSmimeInfo.insert(any(), any(), any())).thenReturn(mockInsert); + when(mockSmimeInfo.list(any(), any())).thenReturn(mockList); + when(mockSmimeInfo.setDefault(any(), any(), any())).thenReturn(mockSetDefault); + } + + @Test + public void testInsertSmimeInfo() throws IOException { + SmimeInfo insertResult = makeFakeInsertResult(); + when(mockInsert.execute()).thenReturn(insertResult); + + SmimeInfo smimeInfo = CreateSmimeInfo.createSmimeInfo("files/cert.p12", + null /* password */); + SmimeInfo result = InsertSmimeInfo.insertSmimeInfo(TEST_USER, + TEST_USER, + smimeInfo); + verifySmimeApiCalled(1); + verify(mockSmimeInfo).insert(eq(TEST_USER), eq(TEST_USER), eq(smimeInfo)); + verify(mockInsert).execute(); + + assertEquals(insertResult, result); + } + + @Test + public void testInsertSmimeInfoError() throws IOException { + when(mockInsert.execute()).thenThrow(IOException.class); + + SmimeInfo smimeInfo = CreateSmimeInfo.createSmimeInfo("files/cert.p12", + null /* password */); + SmimeInfo result = InsertSmimeInfo.insertSmimeInfo(TEST_USER, + TEST_USER, smimeInfo); + + verifySmimeApiCalled(1); + verify(mockSmimeInfo).insert(eq(TEST_USER), eq(TEST_USER), eq(smimeInfo)); + verify(mockInsert).execute(); + + assertNull(result); + } + + private void verifySmimeApiCalled(int numCalls) { + verify(mockService, times(numCalls)).users(); + verify(mockUsers, times(numCalls)).settings(); + verify(mockSettings, times(numCalls)).sendAs(); + verify(mockSendAs, times(numCalls)).smimeInfo(); + } + + private SmimeInfo makeFakeInsertResult(String id, boolean isDefault, long expiration) { + SmimeInfo insertResult = new SmimeInfo(); + insertResult.setId(id); + insertResult.setIsDefault(isDefault); + insertResult.setExpiration(expiration); + + return insertResult; + } + + private SmimeInfo makeFakeInsertResult() { + return makeFakeInsertResult("new_certificate_id", false, CURRENT_TIME_MS + 1); + } } diff --git a/gmail/snippets/src/test/java/TestSendMessage.java b/gmail/snippets/src/test/java/TestSendMessage.java index 2bde312c..e915a244 100644 --- a/gmail/snippets/src/test/java/TestSendMessage.java +++ b/gmail/snippets/src/test/java/TestSendMessage.java @@ -12,19 +12,20 @@ // See the License for the specific language governing permissions and // limitations under the License. +import static org.junit.Assert.assertNotNull; + import com.google.api.services.gmail.model.Message; -import org.junit.Test; -import javax.mail.MessagingException; import java.io.IOException; -import static org.junit.Assert.assertNotNull; +import javax.mail.MessagingException; +import org.junit.Test; // Unit testcase for gmail send email snippet -public class TestSendMessage extends BaseTest{ +public class TestSendMessage extends BaseTest { - @Test - public void testSendEmail() throws MessagingException, IOException { - Message message = SendMessage.sendEmail(RECIPIENT, TEST_USER); - assertNotNull(message); - this.service.users().messages().delete("me", message.getId()).execute(); - } + @Test + public void testSendEmail() throws MessagingException, IOException { + Message message = SendMessage.sendEmail(RECIPIENT, TEST_USER); + assertNotNull(message); + this.service.users().messages().delete("me", message.getId()).execute(); + } } diff --git a/gmail/snippets/src/test/java/TestSendMessageWithAttachment.java b/gmail/snippets/src/test/java/TestSendMessageWithAttachment.java index 56161969..8c428982 100644 --- a/gmail/snippets/src/test/java/TestSendMessageWithAttachment.java +++ b/gmail/snippets/src/test/java/TestSendMessageWithAttachment.java @@ -12,23 +12,24 @@ // See the License for the specific language governing permissions and // limitations under the License. +import static org.junit.Assert.assertNotNull; + import com.google.api.services.gmail.model.Message; -import org.junit.Test; -import javax.mail.MessagingException; import java.io.File; import java.io.IOException; -import static org.junit.Assert.assertNotNull; +import javax.mail.MessagingException; +import org.junit.Test; // Unit testcase for gmail send email with attachment snippet -public class TestSendMessageWithAttachment extends BaseTest{ +public class TestSendMessageWithAttachment extends BaseTest { - @Test - public void testSendEmailWithAttachment() throws MessagingException, - IOException{ - Message message = SendMessageWithAttachment.sendEmailWithAttachment(RECIPIENT, - TEST_USER, - new File("files/photo.jpg")); - assertNotNull(message); - this.service.users().messages().delete("me", message.getId()).execute(); - } + @Test + public void testSendEmailWithAttachment() throws MessagingException, + IOException { + Message message = SendMessageWithAttachment.sendEmailWithAttachment(RECIPIENT, + TEST_USER, + new File("files/photo.jpg")); + assertNotNull(message); + this.service.users().messages().delete("me", message.getId()).execute(); + } } diff --git a/gmail/snippets/src/test/java/TestUpdateSignature.java b/gmail/snippets/src/test/java/TestUpdateSignature.java index 43f0559e..809da2a8 100644 --- a/gmail/snippets/src/test/java/TestUpdateSignature.java +++ b/gmail/snippets/src/test/java/TestUpdateSignature.java @@ -13,16 +13,17 @@ // limitations under the License. -import org.junit.Test; -import java.io.IOException; import static org.junit.Assert.assertEquals; +import java.io.IOException; +import org.junit.Test; + // Unit testcase for gmail update signature snippet public class TestUpdateSignature extends BaseTest { - @Test - public void testUpdateGmailSignature() throws IOException { - String signature = UpdateSignature.updateGmailSignature(); - assertEquals("Automated Signature", signature); - } + @Test + public void testUpdateGmailSignature() throws IOException { + String signature = UpdateSignature.updateGmailSignature(); + assertEquals("Automated Signature", signature); + } } \ No newline at end of file diff --git a/gmail/snippets/src/test/java/TestUpdateSmimeCerts.java b/gmail/snippets/src/test/java/TestUpdateSmimeCerts.java index c66ebb57..0808062b 100644 --- a/gmail/snippets/src/test/java/TestUpdateSmimeCerts.java +++ b/gmail/snippets/src/test/java/TestUpdateSmimeCerts.java @@ -12,16 +12,17 @@ // See the License for the specific language governing permissions and // limitations under the License. +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import com.google.api.services.gmail.Gmail; import com.google.api.services.gmail.model.ListSmimeInfoResponse; import com.google.api.services.gmail.model.SmimeInfo; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; - import java.io.IOException; import java.time.Instant; import java.time.LocalDateTime; @@ -29,242 +30,250 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.*; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; // Unit testcase for gmail update smime certs snippet -public class TestUpdateSmimeCerts extends BaseTest{ - - private static final long CURRENT_TIME_MS = 1234567890; - private static final LocalDateTime CURRENT_TIME = - LocalDateTime.ofInstant(Instant.ofEpochMilli(CURRENT_TIME_MS), ZoneId.systemDefault()); - @Mock - private Gmail mockService; - @Mock private Gmail.Users mockUsers; - @Mock private Gmail.Users.Settings mockSettings; - @Mock private Gmail.Users.Settings.SendAs mockSendAs; - @Mock private Gmail.Users.Settings.SendAs.SmimeInfo mockSmimeInfo; - @Mock private Gmail.Users.Settings.SendAs.SmimeInfo.Delete mockDelete; - @Mock private Gmail.Users.Settings.SendAs.SmimeInfo.Get mockGet; - @Mock private Gmail.Users.Settings.SendAs.SmimeInfo.Insert mockInsert; - @Mock private Gmail.Users.Settings.SendAs.SmimeInfo.List mockList; - @Mock private Gmail.Users.Settings.SendAs.SmimeInfo.SetDefault mockSetDefault; - - @Rule - public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Before - public void setup() throws IOException { - when(mockService.users()).thenReturn(mockUsers); - when(mockUsers.settings()).thenReturn(mockSettings); - when(mockSettings.sendAs()).thenReturn(mockSendAs); - when(mockSendAs.smimeInfo()).thenReturn(mockSmimeInfo); - - when(mockSmimeInfo.delete(any(), any(), any())).thenReturn(mockDelete); - when(mockSmimeInfo.get(any(), any(), any())).thenReturn(mockGet); - when(mockSmimeInfo.insert(any(), any(), any())).thenReturn(mockInsert); - when(mockSmimeInfo.list(any(), any())).thenReturn(mockList); - when(mockSmimeInfo.setDefault(any(), any(), any())).thenReturn(mockSetDefault); +public class TestUpdateSmimeCerts extends BaseTest { + + private static final long CURRENT_TIME_MS = 1234567890; + private static final LocalDateTime CURRENT_TIME = + LocalDateTime.ofInstant(Instant.ofEpochMilli(CURRENT_TIME_MS), ZoneId.systemDefault()); + @Rule + public MockitoRule mockitoRule = MockitoJUnit.rule(); + @Mock + private Gmail mockService; + @Mock + private Gmail.Users mockUsers; + @Mock + private Gmail.Users.Settings mockSettings; + @Mock + private Gmail.Users.Settings.SendAs mockSendAs; + @Mock + private Gmail.Users.Settings.SendAs.SmimeInfo mockSmimeInfo; + @Mock + private Gmail.Users.Settings.SendAs.SmimeInfo.Delete mockDelete; + @Mock + private Gmail.Users.Settings.SendAs.SmimeInfo.Get mockGet; + @Mock + private Gmail.Users.Settings.SendAs.SmimeInfo.Insert mockInsert; + @Mock + private Gmail.Users.Settings.SendAs.SmimeInfo.List mockList; + @Mock + private Gmail.Users.Settings.SendAs.SmimeInfo.SetDefault mockSetDefault; + + @Before + public void setup() throws IOException { + when(mockService.users()).thenReturn(mockUsers); + when(mockUsers.settings()).thenReturn(mockSettings); + when(mockSettings.sendAs()).thenReturn(mockSendAs); + when(mockSendAs.smimeInfo()).thenReturn(mockSmimeInfo); + + when(mockSmimeInfo.delete(any(), any(), any())).thenReturn(mockDelete); + when(mockSmimeInfo.get(any(), any(), any())).thenReturn(mockGet); + when(mockSmimeInfo.insert(any(), any(), any())).thenReturn(mockInsert); + when(mockSmimeInfo.list(any(), any())).thenReturn(mockList); + when(mockSmimeInfo.setDefault(any(), any(), any())).thenReturn(mockSetDefault); + } + + @Test + public void testUpdateSmimeCertsNoCerts() throws IOException { + when(mockList.execute()).thenReturn(makeFakeListResult()); + + String defaultCertId = UpdateSmimeCerts.updateSmimeCerts(TEST_USER, + TEST_USER, + null /* certFilename */, + null /* certPassword */, + CURRENT_TIME); + + verifySmimeApiCalled(1); + verify(mockSmimeInfo).list(eq(TEST_USER), eq(TEST_USER)); + verify(mockList).execute(); + + assertNull(defaultCertId); + } + + @Test + public void testUpdateSmimeCertsNoCertsUploadNewCert() throws IOException { + when(mockList.execute()).thenReturn(makeFakeListResult()); + when(mockInsert.execute()).thenReturn(makeFakeInsertResult()); + + String defaultCertId = UpdateSmimeCerts.updateSmimeCerts(TEST_USER, + TEST_USER, + "files/cert.p12", + null /* certPassword */, + CURRENT_TIME); + + verifySmimeApiCalled(3); + verify(mockSmimeInfo).list(eq(TEST_USER), eq(TEST_USER)); + verify(mockSmimeInfo).insert(eq(TEST_USER), eq(TEST_USER), any()); + verify(mockSmimeInfo).setDefault(eq(TEST_USER), eq(TEST_USER), eq("new_certificate_id")); + verify(mockList).execute(); + verify(mockInsert).execute(); + verify(mockSetDefault).execute(); + + assertEquals(defaultCertId, "new_certificate_id"); + } + + @Test + public void testUpdateSmimeCertsValidDefaultCertNoUpload() throws IOException { + ListSmimeInfoResponse listResponse = + makeFakeListResult(Arrays.asList(true), Arrays.asList(CURRENT_TIME_MS + 1)); + when(mockList.execute()).thenReturn(listResponse); + + String defaultCertId = UpdateSmimeCerts.updateSmimeCerts(TEST_USER, + TEST_USER, + "files/cert.p12", + null /* certPassword */, + CURRENT_TIME); + + verifySmimeApiCalled(1); + verify(mockSmimeInfo).list(eq(TEST_USER), eq(TEST_USER)); + verify(mockList).execute(); + + assertEquals(defaultCertId, "existing_certificate_id0"); + } + + @Test + public void testUpdateSmimeCertsExpiredDefaultCertUploadNewCert() throws IOException { + LocalDateTime expireTime = + LocalDateTime.ofInstant(Instant.ofEpochMilli(CURRENT_TIME_MS + 2), ZoneId.systemDefault()); + ListSmimeInfoResponse listResponse = + makeFakeListResult(Arrays.asList(true), Arrays.asList(CURRENT_TIME_MS + 1)); + when(mockList.execute()).thenReturn(listResponse); + + when(mockInsert.execute()).thenReturn(makeFakeInsertResult()); + + String defaultCertId = UpdateSmimeCerts.updateSmimeCerts(TEST_USER, + TEST_USER, + "files/cert.p12", + null /* certPassword */, + expireTime); + + verifySmimeApiCalled(3); + verify(mockSmimeInfo).list(eq(TEST_USER), eq(TEST_USER)); + verify(mockSmimeInfo).insert(eq(TEST_USER), eq(TEST_USER), any()); + verify(mockSmimeInfo).setDefault(eq(TEST_USER), eq(TEST_USER), eq("new_certificate_id")); + verify(mockList).execute(); + verify(mockInsert).execute(); + verify(mockSetDefault).execute(); + + assertEquals(defaultCertId, "new_certificate_id"); + } + + @Test + public void testUpdateSmimeCertsExpiredDefaultCertOtherCertNewDefault() throws IOException { + ListSmimeInfoResponse listResponse = + makeFakeListResult( + Arrays.asList(true, false), Arrays.asList(CURRENT_TIME_MS - 1, CURRENT_TIME_MS + 1)); + when(mockList.execute()).thenReturn(listResponse); + + String defaultCertId = UpdateSmimeCerts.updateSmimeCerts(TEST_USER, + TEST_USER, + "files/cert.p12", + null /* certPassword */, + CURRENT_TIME); + + verifySmimeApiCalled(2); + verify(mockSmimeInfo).list(eq(TEST_USER), eq(TEST_USER)); + verify(mockSmimeInfo).setDefault(eq(TEST_USER), eq(TEST_USER), eq("existing_certificate_id1")); + verify(mockList).execute(); + verify(mockSetDefault).execute(); + + assertEquals(defaultCertId, "existing_certificate_id1"); + } + + @Test + public void testUpdateSmimeCertsNoCertsNoDefaultsChooseBestCertAsNewDefault() throws IOException { + ListSmimeInfoResponse listResponse = + makeFakeListResult( + Arrays.asList(false, false, false, false), + Arrays.asList( + CURRENT_TIME_MS + 2, + CURRENT_TIME_MS + 1, + CURRENT_TIME_MS + 4, + CURRENT_TIME_MS + 3)); + when(mockList.execute()).thenReturn(listResponse); + + String defaultCertId = UpdateSmimeCerts.updateSmimeCerts(TEST_USER, + TEST_USER, + "files/cert.p12", + null /* certPassword */, + CURRENT_TIME); + + verifySmimeApiCalled(2); + verify(mockSmimeInfo).list(eq(TEST_USER), eq(TEST_USER)); + verify(mockSmimeInfo).setDefault(eq(TEST_USER), eq(TEST_USER), eq("existing_certificate_id2")); + verify(mockList).execute(); + verify(mockSetDefault).execute(); + + assertEquals(defaultCertId, "existing_certificate_id2"); + } + + @Test + public void testUpdateSmimeCertsError() throws IOException { + when(mockList.execute()).thenThrow(IOException.class); + + String defaultCertId = + UpdateSmimeCerts.updateSmimeCerts(TEST_USER, + TEST_USER, + "files/cert.p12", + null /* certPassword */, + CURRENT_TIME); + + verifySmimeApiCalled(1); + verify(mockSmimeInfo).list(eq(TEST_USER), eq(TEST_USER)); + verify(mockList).execute(); + + assertNull(defaultCertId); + } + + private void verifySmimeApiCalled(int numCalls) { + verify(mockService, times(numCalls)).users(); + verify(mockUsers, times(numCalls)).settings(); + verify(mockSettings, times(numCalls)).sendAs(); + verify(mockSendAs, times(numCalls)).smimeInfo(); + } + + private ListSmimeInfoResponse makeFakeListResult(List isDefault, List expiration) { + ListSmimeInfoResponse listResponse = new ListSmimeInfoResponse(); + if (isDefault == null || expiration == null) { + return listResponse; } - @Test - public void testUpdateSmimeCertsNoCerts() throws IOException { - when(mockList.execute()).thenReturn(makeFakeListResult()); - - String defaultCertId = UpdateSmimeCerts.updateSmimeCerts(TEST_USER, - TEST_USER, - null /* certFilename */, - null /* certPassword */, - CURRENT_TIME); - - verifySmimeApiCalled(1); - verify(mockSmimeInfo).list(eq(TEST_USER), eq(TEST_USER)); - verify(mockList).execute(); + assertEquals(isDefault.size(), expiration.size()); - assertNull(defaultCertId); + List smimeInfoList = new ArrayList(); + for (int i = 0; i < isDefault.size(); i++) { + SmimeInfo smimeInfo = new SmimeInfo(); + smimeInfo.setId(String.format("existing_certificate_id%d", i)); + smimeInfo.setIsDefault(isDefault.get(i)); + smimeInfo.setExpiration(expiration.get(i)); + smimeInfoList.add(smimeInfo); } + listResponse.setSmimeInfo(smimeInfoList); - @Test - public void testUpdateSmimeCertsNoCertsUploadNewCert() throws IOException { - when(mockList.execute()).thenReturn(makeFakeListResult()); - when(mockInsert.execute()).thenReturn(makeFakeInsertResult()); - - String defaultCertId = UpdateSmimeCerts.updateSmimeCerts(TEST_USER, - TEST_USER, - "files/cert.p12", - null /* certPassword */, - CURRENT_TIME); - - verifySmimeApiCalled(3); - verify(mockSmimeInfo).list(eq(TEST_USER), eq(TEST_USER)); - verify(mockSmimeInfo).insert(eq(TEST_USER), eq(TEST_USER), any()); - verify(mockSmimeInfo).setDefault(eq(TEST_USER), eq(TEST_USER), eq("new_certificate_id")); - verify(mockList).execute(); - verify(mockInsert).execute(); - verify(mockSetDefault).execute(); - - assertEquals(defaultCertId, "new_certificate_id"); - } - - @Test - public void testUpdateSmimeCertsValidDefaultCertNoUpload() throws IOException { - ListSmimeInfoResponse listResponse = - makeFakeListResult(Arrays.asList(true), Arrays.asList(CURRENT_TIME_MS + 1)); - when(mockList.execute()).thenReturn(listResponse); - - String defaultCertId = UpdateSmimeCerts.updateSmimeCerts(TEST_USER, - TEST_USER, - "files/cert.p12", - null /* certPassword */, - CURRENT_TIME); - - verifySmimeApiCalled(1); - verify(mockSmimeInfo).list(eq(TEST_USER), eq(TEST_USER)); - verify(mockList).execute(); - - assertEquals(defaultCertId, "existing_certificate_id0"); - } - - @Test - public void testUpdateSmimeCertsExpiredDefaultCertUploadNewCert() throws IOException { - LocalDateTime expireTime = - LocalDateTime.ofInstant(Instant.ofEpochMilli(CURRENT_TIME_MS + 2), ZoneId.systemDefault()); - ListSmimeInfoResponse listResponse = - makeFakeListResult(Arrays.asList(true), Arrays.asList(CURRENT_TIME_MS + 1)); - when(mockList.execute()).thenReturn(listResponse); - - when(mockInsert.execute()).thenReturn(makeFakeInsertResult()); - - String defaultCertId = UpdateSmimeCerts.updateSmimeCerts(TEST_USER, - TEST_USER, - "files/cert.p12", - null /* certPassword */, - expireTime); - - verifySmimeApiCalled(3); - verify(mockSmimeInfo).list(eq(TEST_USER), eq(TEST_USER)); - verify(mockSmimeInfo).insert(eq(TEST_USER), eq(TEST_USER), any()); - verify(mockSmimeInfo).setDefault(eq(TEST_USER), eq(TEST_USER), eq("new_certificate_id")); - verify(mockList).execute(); - verify(mockInsert).execute(); - verify(mockSetDefault).execute(); - - assertEquals(defaultCertId, "new_certificate_id"); - } - - @Test - public void testUpdateSmimeCertsExpiredDefaultCertOtherCertNewDefault() throws IOException { - ListSmimeInfoResponse listResponse = - makeFakeListResult( - Arrays.asList(true, false), Arrays.asList(CURRENT_TIME_MS - 1, CURRENT_TIME_MS + 1)); - when(mockList.execute()).thenReturn(listResponse); - - String defaultCertId = UpdateSmimeCerts.updateSmimeCerts(TEST_USER, - TEST_USER, - "files/cert.p12", - null /* certPassword */, - CURRENT_TIME); - - verifySmimeApiCalled(2); - verify(mockSmimeInfo).list(eq(TEST_USER), eq(TEST_USER)); - verify(mockSmimeInfo).setDefault(eq(TEST_USER), eq(TEST_USER), eq("existing_certificate_id1")); - verify(mockList).execute(); - verify(mockSetDefault).execute(); - - assertEquals(defaultCertId, "existing_certificate_id1"); - } - - @Test - public void testUpdateSmimeCertsNoCertsNoDefaultsChooseBestCertAsNewDefault() throws IOException { - ListSmimeInfoResponse listResponse = - makeFakeListResult( - Arrays.asList(false, false, false, false), - Arrays.asList( - CURRENT_TIME_MS + 2, - CURRENT_TIME_MS + 1, - CURRENT_TIME_MS + 4, - CURRENT_TIME_MS + 3)); - when(mockList.execute()).thenReturn(listResponse); - - String defaultCertId = UpdateSmimeCerts.updateSmimeCerts(TEST_USER, - TEST_USER, - "files/cert.p12", - null /* certPassword */, - CURRENT_TIME); - - verifySmimeApiCalled(2); - verify(mockSmimeInfo).list(eq(TEST_USER), eq(TEST_USER)); - verify(mockSmimeInfo).setDefault(eq(TEST_USER), eq(TEST_USER), eq("existing_certificate_id2")); - verify(mockList).execute(); - verify(mockSetDefault).execute(); - - assertEquals(defaultCertId, "existing_certificate_id2"); - } + return listResponse; + } - @Test - public void testUpdateSmimeCertsError() throws IOException { - when(mockList.execute()).thenThrow(IOException.class); + private ListSmimeInfoResponse makeFakeListResult() { + return makeFakeListResult(null /* isDefault */, null /* expiration */); + } - String defaultCertId = - UpdateSmimeCerts.updateSmimeCerts(TEST_USER, - TEST_USER, - "files/cert.p12", - null /* certPassword */, - CURRENT_TIME); + private SmimeInfo makeFakeInsertResult(String id, boolean isDefault, long expiration) { + SmimeInfo insertResult = new SmimeInfo(); + insertResult.setId(id); + insertResult.setIsDefault(isDefault); + insertResult.setExpiration(expiration); - verifySmimeApiCalled(1); - verify(mockSmimeInfo).list(eq(TEST_USER), eq(TEST_USER)); - verify(mockList).execute(); + return insertResult; + } - assertNull(defaultCertId); - } - - private void verifySmimeApiCalled(int numCalls) { - verify(mockService, times(numCalls)).users(); - verify(mockUsers, times(numCalls)).settings(); - verify(mockSettings, times(numCalls)).sendAs(); - verify(mockSendAs, times(numCalls)).smimeInfo(); - } - - private ListSmimeInfoResponse makeFakeListResult(List isDefault, List expiration) { - ListSmimeInfoResponse listResponse = new ListSmimeInfoResponse(); - if (isDefault == null || expiration == null) { - return listResponse; - } - - assertEquals(isDefault.size(), expiration.size()); - - List smimeInfoList = new ArrayList(); - for (int i = 0; i < isDefault.size(); i++) { - SmimeInfo smimeInfo = new SmimeInfo(); - smimeInfo.setId(String.format("existing_certificate_id%d", i)); - smimeInfo.setIsDefault(isDefault.get(i)); - smimeInfo.setExpiration(expiration.get(i)); - smimeInfoList.add(smimeInfo); - } - listResponse.setSmimeInfo(smimeInfoList); - - return listResponse; - } - - private ListSmimeInfoResponse makeFakeListResult() { - return makeFakeListResult(null /* isDefault */, null /* expiration */); - } - - private SmimeInfo makeFakeInsertResult(String id, boolean isDefault, long expiration) { - SmimeInfo insertResult = new SmimeInfo(); - insertResult.setId(id); - insertResult.setIsDefault(isDefault); - insertResult.setExpiration(expiration); - - return insertResult; - } - - private SmimeInfo makeFakeInsertResult() { - return makeFakeInsertResult("new_certificate_id", false, CURRENT_TIME_MS + 1); - } + private SmimeInfo makeFakeInsertResult() { + return makeFakeInsertResult("new_certificate_id", false, CURRENT_TIME_MS + 1); + } } diff --git a/gmail/snippets/src/test/java/TestUpdateSmimeFromCsv.java b/gmail/snippets/src/test/java/TestUpdateSmimeFromCsv.java index 35bcee1e..6b89e455 100644 --- a/gmail/snippets/src/test/java/TestUpdateSmimeFromCsv.java +++ b/gmail/snippets/src/test/java/TestUpdateSmimeFromCsv.java @@ -12,129 +12,137 @@ // See the License for the specific language governing permissions and // limitations under the License. +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import com.google.api.services.gmail.Gmail; import com.google.api.services.gmail.model.ListSmimeInfoResponse; import com.google.api.services.gmail.model.SmimeInfo; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; - import java.io.IOException; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.ArrayList; import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.*; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; // Unit testcase for gmail update smime from csv snippet -public class TestUpdateSmimeFromCsv extends BaseTest{ - - private static final long CURRENT_TIME_MS = 1234567890; - private static final LocalDateTime CURRENT_TIME = - LocalDateTime.ofInstant(Instant.ofEpochMilli(CURRENT_TIME_MS), ZoneId.systemDefault()); - - @Mock - private Gmail mockService; - @Mock private Gmail.Users mockUsers; - @Mock private Gmail.Users.Settings mockSettings; - @Mock private Gmail.Users.Settings.SendAs mockSendAs; - @Mock private Gmail.Users.Settings.SendAs.SmimeInfo mockSmimeInfo; - @Mock private Gmail.Users.Settings.SendAs.SmimeInfo.Delete mockDelete; - @Mock private Gmail.Users.Settings.SendAs.SmimeInfo.Get mockGet; - @Mock private Gmail.Users.Settings.SendAs.SmimeInfo.Insert mockInsert; - @Mock private Gmail.Users.Settings.SendAs.SmimeInfo.List mockList; - @Mock private Gmail.Users.Settings.SendAs.SmimeInfo.SetDefault mockSetDefault; - - @Rule - public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Before - public void setup() throws IOException { - when(mockService.users()).thenReturn(mockUsers); - when(mockUsers.settings()).thenReturn(mockSettings); - when(mockSettings.sendAs()).thenReturn(mockSendAs); - when(mockSendAs.smimeInfo()).thenReturn(mockSmimeInfo); - - when(mockSmimeInfo.delete(any(), any(), any())).thenReturn(mockDelete); - when(mockSmimeInfo.get(any(), any(), any())).thenReturn(mockGet); - when(mockSmimeInfo.insert(any(), any(), any())).thenReturn(mockInsert); - when(mockSmimeInfo.list(any(), any())).thenReturn(mockList); - when(mockSmimeInfo.setDefault(any(), any(), any())).thenReturn(mockSetDefault); +public class TestUpdateSmimeFromCsv extends BaseTest { + + private static final long CURRENT_TIME_MS = 1234567890; + private static final LocalDateTime CURRENT_TIME = + LocalDateTime.ofInstant(Instant.ofEpochMilli(CURRENT_TIME_MS), ZoneId.systemDefault()); + @Rule + public MockitoRule mockitoRule = MockitoJUnit.rule(); + @Mock + private Gmail mockService; + @Mock + private Gmail.Users mockUsers; + @Mock + private Gmail.Users.Settings mockSettings; + @Mock + private Gmail.Users.Settings.SendAs mockSendAs; + @Mock + private Gmail.Users.Settings.SendAs.SmimeInfo mockSmimeInfo; + @Mock + private Gmail.Users.Settings.SendAs.SmimeInfo.Delete mockDelete; + @Mock + private Gmail.Users.Settings.SendAs.SmimeInfo.Get mockGet; + @Mock + private Gmail.Users.Settings.SendAs.SmimeInfo.Insert mockInsert; + @Mock + private Gmail.Users.Settings.SendAs.SmimeInfo.List mockList; + @Mock + private Gmail.Users.Settings.SendAs.SmimeInfo.SetDefault mockSetDefault; + + @Before + public void setup() throws IOException { + when(mockService.users()).thenReturn(mockUsers); + when(mockUsers.settings()).thenReturn(mockSettings); + when(mockSettings.sendAs()).thenReturn(mockSendAs); + when(mockSendAs.smimeInfo()).thenReturn(mockSmimeInfo); + + when(mockSmimeInfo.delete(any(), any(), any())).thenReturn(mockDelete); + when(mockSmimeInfo.get(any(), any(), any())).thenReturn(mockGet); + when(mockSmimeInfo.insert(any(), any(), any())).thenReturn(mockInsert); + when(mockSmimeInfo.list(any(), any())).thenReturn(mockList); + when(mockSmimeInfo.setDefault(any(), any(), any())).thenReturn(mockSetDefault); + } + + @Test + public void testUpdateSmimeFromCsv() throws IOException { + when(mockList.execute()).thenReturn(makeFakeListResult()); + when(mockInsert.execute()).thenReturn(makeFakeInsertResult()); + + UpdateSmimeFromCsv.updateSmimeFromCsv("files/certs.csv", CURRENT_TIME); + + verifySmimeApiCalled(6); + verify(mockSmimeInfo).list(eq(TEST_USER), eq(TEST_USER)); + verify(mockSmimeInfo).insert(eq(TEST_USER), eq(TEST_USER), any()); + verify(mockSmimeInfo) + .setDefault(eq(TEST_USER), eq(TEST_USER), eq("new_certificate_id")); + verify(mockList, times(2)).execute(); + verify(mockInsert, times(2)).execute(); + verify(mockSetDefault, times(2)).execute(); + } + + @Test + public void testUpdateSmimeFromCsvFails() { + InsertCertFromCsv.insertCertFromCsv("files/notfound.csv"); + // tearDown() verifies that there were no interactions with the API. + } + + private void verifySmimeApiCalled(int numCalls) { + verify(mockService, times(numCalls)).users(); + verify(mockUsers, times(numCalls)).settings(); + verify(mockSettings, times(numCalls)).sendAs(); + verify(mockSendAs, times(numCalls)).smimeInfo(); + } + + private ListSmimeInfoResponse makeFakeListResult(List isDefault, List expiration) { + ListSmimeInfoResponse listResponse = new ListSmimeInfoResponse(); + if (isDefault == null || expiration == null) { + return listResponse; } - @Test - public void testUpdateSmimeFromCsv() throws IOException { - when(mockList.execute()).thenReturn(makeFakeListResult()); - when(mockInsert.execute()).thenReturn(makeFakeInsertResult()); - - UpdateSmimeFromCsv.updateSmimeFromCsv("files/certs.csv", CURRENT_TIME); - - verifySmimeApiCalled(6); - verify(mockSmimeInfo).list(eq(TEST_USER), eq(TEST_USER)); - verify(mockSmimeInfo).insert(eq(TEST_USER), eq(TEST_USER), any()); - verify(mockSmimeInfo) - .setDefault(eq(TEST_USER), eq(TEST_USER), eq("new_certificate_id")); - verify(mockList, times(2)).execute(); - verify(mockInsert, times(2)).execute(); - verify(mockSetDefault, times(2)).execute(); - } + assertEquals(isDefault.size(), expiration.size()); - @Test - public void testUpdateSmimeFromCsvFails() { - InsertCertFromCsv.insertCertFromCsv("files/notfound.csv"); - // tearDown() verifies that there were no interactions with the API. + List smimeInfoList = new ArrayList<>(); + for (int i = 0; i < isDefault.size(); i++) { + SmimeInfo smimeInfo = new SmimeInfo(); + smimeInfo.setId(String.format("existing_certificate_id%d", i)); + smimeInfo.setIsDefault(isDefault.get(i)); + smimeInfo.setExpiration(expiration.get(i)); + smimeInfoList.add(smimeInfo); } + listResponse.setSmimeInfo(smimeInfoList); - private void verifySmimeApiCalled(int numCalls) { - verify(mockService, times(numCalls)).users(); - verify(mockUsers, times(numCalls)).settings(); - verify(mockSettings, times(numCalls)).sendAs(); - verify(mockSendAs, times(numCalls)).smimeInfo(); - } + return listResponse; + } - private ListSmimeInfoResponse makeFakeListResult(List isDefault, List expiration) { - ListSmimeInfoResponse listResponse = new ListSmimeInfoResponse(); - if (isDefault == null || expiration == null) { - return listResponse; - } - - assertEquals(isDefault.size(), expiration.size()); - - List smimeInfoList = new ArrayList<>(); - for (int i = 0; i < isDefault.size(); i++) { - SmimeInfo smimeInfo = new SmimeInfo(); - smimeInfo.setId(String.format("existing_certificate_id%d", i)); - smimeInfo.setIsDefault(isDefault.get(i)); - smimeInfo.setExpiration(expiration.get(i)); - smimeInfoList.add(smimeInfo); - } - listResponse.setSmimeInfo(smimeInfoList); - - return listResponse; - } + private ListSmimeInfoResponse makeFakeListResult() { + return makeFakeListResult(null /* isDefault */, null /* expiration */); + } - private ListSmimeInfoResponse makeFakeListResult() { - return makeFakeListResult(null /* isDefault */, null /* expiration */); - } + private SmimeInfo makeFakeInsertResult(String id, boolean isDefault, long expiration) { + SmimeInfo insertResult = new SmimeInfo(); + insertResult.setId(id); + insertResult.setIsDefault(isDefault); + insertResult.setExpiration(expiration); - private SmimeInfo makeFakeInsertResult(String id, boolean isDefault, long expiration) { - SmimeInfo insertResult = new SmimeInfo(); - insertResult.setId(id); - insertResult.setIsDefault(isDefault); - insertResult.setExpiration(expiration); + return insertResult; + } - return insertResult; - } - - private SmimeInfo makeFakeInsertResult() { - return makeFakeInsertResult("new_certificate_id", false, CURRENT_TIME_MS + 1); - } + private SmimeInfo makeFakeInsertResult() { + return makeFakeInsertResult("new_certificate_id", false, CURRENT_TIME_MS + 1); + } } diff --git a/people/quickstart/src/main/java/PeopleQuickstart.java b/people/quickstart/src/main/java/PeopleQuickstart.java index a0301f2d..dcbc81f9 100644 --- a/people/quickstart/src/main/java/PeopleQuickstart.java +++ b/people/quickstart/src/main/java/PeopleQuickstart.java @@ -13,6 +13,7 @@ // limitations under the License. // [START people_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; @@ -38,70 +39,74 @@ import java.util.List; public class PeopleQuickstart { - private static final String APPLICATION_NAME = "Google People API Java Quickstart"; - private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); - 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 = Arrays.asList(PeopleServiceScopes.CONTACTS_READONLY); - private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; + private static final String APPLICATION_NAME = "Google People API Java Quickstart"; + private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); + private static final String TOKENS_DIRECTORY_PATH = "tokens"; - /** - * Creates an authorized Credential object. - * @param HTTP_TRANSPORT The network HTTP Transport. - * @return An authorized Credential object. - * @throws IOException If the credentials.json file cannot be found. - */ - private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException { - // Load client secrets. - InputStream in = PeopleQuickstart.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)); + /** + * Global instance of the scopes required by this quickstart. + * If modifying these scopes, delete your previously saved tokens/ folder. + */ + private static final List SCOPES = Arrays.asList(PeopleServiceScopes.CONTACTS_READONLY); + private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; - // 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"); + /** + * Creates an authorized Credential object. + * + * @param HTTP_TRANSPORT The network HTTP Transport. + * @return An authorized Credential object. + * @throws IOException If the credentials.json file cannot be found. + */ + private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) + throws IOException { + // Load client secrets. + InputStream in = PeopleQuickstart.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"); + } - public static void main(String... args) throws IOException, GeneralSecurityException { - // Build a new authorized API client service. - final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); - PeopleService service = new PeopleService.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) - .setApplicationName(APPLICATION_NAME) - .build(); + public static void main(String... args) throws IOException, GeneralSecurityException { + // Build a new authorized API client service. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + PeopleService service = + new PeopleService.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) + .setApplicationName(APPLICATION_NAME) + .build(); - // Request 10 connections. - ListConnectionsResponse response = service.people().connections() - .list("people/me") - .setPageSize(10) - .setPersonFields("names,emailAddresses") - .execute(); + // Request 10 connections. + ListConnectionsResponse response = service.people().connections() + .list("people/me") + .setPageSize(10) + .setPersonFields("names,emailAddresses") + .execute(); - // Print display name of connections if available. - List connections = response.getConnections(); - if (connections != null && connections.size() > 0) { - for (Person person : connections) { - List names = person.getNames(); - if (names != null && names.size() > 0) { - System.out.println("Name: " + person.getNames().get(0) - .getDisplayName()); - } else { - System.out.println("No names available for connection."); - } - } + // Print display name of connections if available. + List connections = response.getConnections(); + if (connections != null && connections.size() > 0) { + for (Person person : connections) { + List names = person.getNames(); + if (names != null && names.size() > 0) { + System.out.println("Name: " + person.getNames().get(0) + .getDisplayName()); } else { - System.out.println("No connections found."); + System.out.println("No names available for connection."); } + } + } else { + System.out.println("No connections found."); } + } } // [END people_quickstart] diff --git a/sheets/quickstart/src/main/java/SheetsQuickstart.java b/sheets/quickstart/src/main/java/SheetsQuickstart.java index e7d04d4c..10eef669 100644 --- a/sheets/quickstart/src/main/java/SheetsQuickstart.java +++ b/sheets/quickstart/src/main/java/SheetsQuickstart.java @@ -13,6 +13,7 @@ // limitations under the License. // [START sheets_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; @@ -26,7 +27,6 @@ import com.google.api.services.sheets.v4.Sheets; import com.google.api.services.sheets.v4.SheetsScopes; import com.google.api.services.sheets.v4.model.ValueRange; - import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; @@ -36,66 +36,71 @@ import java.util.List; public class SheetsQuickstart { - private static final String APPLICATION_NAME = "Google Sheets API Java Quickstart"; - private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); - private static final String TOKENS_DIRECTORY_PATH = "tokens"; + private static final String APPLICATION_NAME = "Google Sheets API Java Quickstart"; + private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); + 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(SheetsScopes.SPREADSHEETS_READONLY); - private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; + /** + * 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(SheetsScopes.SPREADSHEETS_READONLY); + private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; - /** - * Creates an authorized Credential object. - * @param HTTP_TRANSPORT The network HTTP Transport. - * @return An authorized Credential object. - * @throws IOException If the credentials.json file cannot be found. - */ - private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException { - // Load client secrets. - InputStream in = SheetsQuickstart.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"); + /** + * Creates an authorized Credential object. + * + * @param HTTP_TRANSPORT The network HTTP Transport. + * @return An authorized Credential object. + * @throws IOException If the credentials.json file cannot be found. + */ + private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) + throws IOException { + // Load client secrets. + InputStream in = SheetsQuickstart.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"); + } - /** - * Prints the names and majors of students in a sample spreadsheet: - * https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit - */ - public static void main(String... args) throws IOException, GeneralSecurityException { - // Build a new authorized API client service. - final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); - final String spreadsheetId = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms"; - final String range = "Class Data!A2:E"; - Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) - .setApplicationName(APPLICATION_NAME) - .build(); - ValueRange response = service.spreadsheets().values() - .get(spreadsheetId, range) - .execute(); - List> values = response.getValues(); - if (values == null || values.isEmpty()) { - System.out.println("No data found."); - } else { - System.out.println("Name, Major"); - for (List row : values) { - // Print columns A and E, which correspond to indices 0 and 4. - System.out.printf("%s, %s\n", row.get(0), row.get(4)); - } - } + /** + * Prints the names and majors of students in a sample spreadsheet: + * https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit + */ + public static void main(String... args) throws IOException, GeneralSecurityException { + // Build a new authorized API client service. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + final String spreadsheetId = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms"; + final String range = "Class Data!A2:E"; + Sheets service = + new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) + .setApplicationName(APPLICATION_NAME) + .build(); + ValueRange response = service.spreadsheets().values() + .get(spreadsheetId, range) + .execute(); + List> values = response.getValues(); + if (values == null || values.isEmpty()) { + System.out.println("No data found."); + } else { + System.out.println("Name, Major"); + for (List row : values) { + // Print columns A and E, which correspond to indices 0 and 4. + System.out.printf("%s, %s\n", row.get(0), row.get(4)); + } } + } } // [END sheets_quickstart] diff --git a/sheets/snippets/src/main/java/AppendValues.java b/sheets/snippets/src/main/java/AppendValues.java index c5d023a0..5da38dd1 100644 --- a/sheets/snippets/src/main/java/AppendValues.java +++ b/sheets/snippets/src/main/java/AppendValues.java @@ -14,6 +14,7 @@ // [START sheets_append_values] + import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; @@ -25,63 +26,62 @@ import com.google.api.services.sheets.v4.model.ValueRange; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.Collections; import java.util.List; /* Class to demonstrate the use of Spreadsheet Append Values API */ public class AppendValues { - /** - * Appends values to a spreadsheet. - * - * @param spreadsheetId - Id of the spreadsheet. - * @param range - Range of cells of the spreadsheet. - * @param valueInputOption - Determines how input data should be interpreted. - * @param values - list of rows of values to input. - * @return spreadsheet with appended values - * @throws IOException - if credentials file not found. - */ - public static AppendValuesResponse appendValues(String spreadsheetId, - String range, - String valueInputOption, - List> values) - throws IOException { + /** + * Appends values to a spreadsheet. + * + * @param spreadsheetId - Id of the spreadsheet. + * @param range - Range of cells of the spreadsheet. + * @param valueInputOption - Determines how input data should be interpreted. + * @param values - list of rows of values to input. + * @return spreadsheet with appended values + * @throws IOException - if credentials file not found. + */ + public static AppendValuesResponse appendValues(String spreadsheetId, + String range, + String valueInputOption, + List> values) + 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(SheetsScopes.SPREADSHEETS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(SheetsScopes.SPREADSHEETS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the sheets API client - Sheets service = new Sheets.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Sheets samples") - .build(); + // Create the sheets API client + Sheets service = new Sheets.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Sheets samples") + .build(); - AppendValuesResponse result = null; - try { - // Append values to the specified range. - ValueRange body = new ValueRange() - .setValues(values); - result = service.spreadsheets().values().append(spreadsheetId, range, body) - .setValueInputOption(valueInputOption) - .execute(); - // Prints the spreadsheet with appended values. - System.out.printf("%d cells appended.", result.getUpdates().getUpdatedCells()); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 404) { - System.out.printf("Spreadsheet not found with id '%s'.\n",spreadsheetId); - } else { - throw e; - } - } - return result; + AppendValuesResponse result = null; + try { + // Append values to the specified range. + ValueRange body = new ValueRange() + .setValues(values); + result = service.spreadsheets().values().append(spreadsheetId, range, body) + .setValueInputOption(valueInputOption) + .execute(); + // Prints the spreadsheet with appended values. + System.out.printf("%d cells appended.", result.getUpdates().getUpdatedCells()); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("Spreadsheet not found with id '%s'.\n", spreadsheetId); + } else { + throw e; + } } + return result; + } } // [END sheets_append_values] \ No newline at end of file diff --git a/sheets/snippets/src/main/java/BatchGetValues.java b/sheets/snippets/src/main/java/BatchGetValues.java index 21da22d9..1a79a213 100644 --- a/sheets/snippets/src/main/java/BatchGetValues.java +++ b/sheets/snippets/src/main/java/BatchGetValues.java @@ -14,6 +14,7 @@ // [START sheets_batch_get_values] + import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; @@ -24,55 +25,54 @@ import com.google.api.services.sheets.v4.model.BatchGetValuesResponse; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.Collections; import java.util.List; /* Class to demonstrate the use of Spreadsheet Batch Get Values API */ public class BatchGetValues { - /** - * Returns one or more ranges of values from a spreadsheet. - * - * @param spreadsheetId - Id of the spreadsheet. - * @param ranges - Range of cells of the spreadsheet. - * @return Values in the range - * @throws IOException - if credentials file not found. - */ - public static BatchGetValuesResponse batchGetValues(String spreadsheetId, - List ranges) - throws IOException { + /** + * Returns one or more ranges of values from a spreadsheet. + * + * @param spreadsheetId - Id of the spreadsheet. + * @param ranges - Range of cells of the spreadsheet. + * @return Values in the range + * @throws IOException - if credentials file not found. + */ + public static BatchGetValuesResponse batchGetValues(String spreadsheetId, + List ranges) + 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(SheetsScopes.SPREADSHEETS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(SheetsScopes.SPREADSHEETS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the sheets API client - Sheets service = new Sheets.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Sheets samples") - .build(); + // Create the sheets API client + Sheets service = new Sheets.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Sheets samples") + .build(); - BatchGetValuesResponse result = null; - try { - // Gets the values of the cells in the specified range. - result = service.spreadsheets().values().batchGet(spreadsheetId) - .setRanges(ranges).execute() ; - System.out.printf("%d ranges retrieved.", result.getValueRanges().size()); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 404) { - System.out.printf("Spreadsheet not found with id '%s'.\n",spreadsheetId); - } else { - throw e; - } - } - return result; + BatchGetValuesResponse result = null; + try { + // Gets the values of the cells in the specified range. + result = service.spreadsheets().values().batchGet(spreadsheetId) + .setRanges(ranges).execute(); + System.out.printf("%d ranges retrieved.", result.getValueRanges().size()); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("Spreadsheet not found with id '%s'.\n", spreadsheetId); + } else { + throw e; + } } + return result; + } } // [END sheets_batch_get_values] \ No newline at end of file diff --git a/sheets/snippets/src/main/java/BatchUpdate.java b/sheets/snippets/src/main/java/BatchUpdate.java index 6e8ac069..5c742500 100644 --- a/sheets/snippets/src/main/java/BatchUpdate.java +++ b/sheets/snippets/src/main/java/BatchUpdate.java @@ -14,6 +14,7 @@ // [START sheets_batch_update] + import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; @@ -21,8 +22,8 @@ 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.BatchUpdateSpreadsheetResponse; import com.google.api.services.sheets.v4.model.BatchUpdateSpreadsheetRequest; +import com.google.api.services.sheets.v4.model.BatchUpdateSpreadsheetResponse; import com.google.api.services.sheets.v4.model.FindReplaceRequest; import com.google.api.services.sheets.v4.model.FindReplaceResponse; import com.google.api.services.sheets.v4.model.Request; @@ -30,7 +31,6 @@ import com.google.api.services.sheets.v4.model.UpdateSpreadsheetPropertiesRequest; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.ArrayList; import java.util.Collections; @@ -38,68 +38,68 @@ /* Class to demonstrate the use of Spreadsheet Batch Update API */ public class BatchUpdate { - /** - * Updates spreadsheet's title and cell values. - * - * @param spreadsheetId - Id of the spreadsheet. - * @param title - New title of the spreadsheet. - * @param find - Find cell values - * @param replacement - Replaced cell values - * @return response metadata - * @throws IOException - if credentials file not found. - */ - public static BatchUpdateSpreadsheetResponse batchUpdate(String spreadsheetId, - String title, - String find, - String replacement) - throws IOException { + /** + * Updates spreadsheet's title and cell values. + * + * @param spreadsheetId - Id of the spreadsheet. + * @param title - New title of the spreadsheet. + * @param find - Find cell values + * @param replacement - Replaced cell values + * @return response metadata + * @throws IOException - if credentials file not found. + */ + public static BatchUpdateSpreadsheetResponse batchUpdate(String spreadsheetId, + String title, + String find, + String replacement) + 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(SheetsScopes.SPREADSHEETS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(SheetsScopes.SPREADSHEETS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the sheets API client - Sheets service = new Sheets.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Sheets samples") - .build(); + // Create the sheets API client + Sheets service = new Sheets.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Sheets samples") + .build(); - List requests = new ArrayList<>(); - BatchUpdateSpreadsheetResponse response = null; - try { - // Change the spreadsheet's title. - requests.add(new Request() - .setUpdateSpreadsheetProperties(new UpdateSpreadsheetPropertiesRequest() - .setProperties(new SpreadsheetProperties() - .setTitle(title)) - .setFields("title"))); - // Find and replace text. - requests.add(new Request() - .setFindReplace(new FindReplaceRequest() - .setFind(find) - .setReplacement(replacement) - .setAllSheets(true))); + List requests = new ArrayList<>(); + BatchUpdateSpreadsheetResponse response = null; + try { + // Change the spreadsheet's title. + requests.add(new Request() + .setUpdateSpreadsheetProperties(new UpdateSpreadsheetPropertiesRequest() + .setProperties(new SpreadsheetProperties() + .setTitle(title)) + .setFields("title"))); + // Find and replace text. + requests.add(new Request() + .setFindReplace(new FindReplaceRequest() + .setFind(find) + .setReplacement(replacement) + .setAllSheets(true))); - BatchUpdateSpreadsheetRequest body = - new BatchUpdateSpreadsheetRequest().setRequests(requests); - response = service.spreadsheets().batchUpdate(spreadsheetId, body).execute(); - FindReplaceResponse findReplaceResponse = response.getReplies().get(1).getFindReplace(); + BatchUpdateSpreadsheetRequest body = + new BatchUpdateSpreadsheetRequest().setRequests(requests); + response = service.spreadsheets().batchUpdate(spreadsheetId, body).execute(); + FindReplaceResponse findReplaceResponse = response.getReplies().get(1).getFindReplace(); - System.out.printf("%d replacements made.", findReplaceResponse.getOccurrencesChanged()); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 404) { - System.out.printf("Spreadsheet not found with id '%s'.\n",spreadsheetId); - } else { - throw e; - } - } - return response; + System.out.printf("%d replacements made.", findReplaceResponse.getOccurrencesChanged()); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("Spreadsheet not found with id '%s'.\n", spreadsheetId); + } else { + throw e; + } } + return response; + } } // [END sheets_batch_update] \ No newline at end of file diff --git a/sheets/snippets/src/main/java/BatchUpdateValues.java b/sheets/snippets/src/main/java/BatchUpdateValues.java index a2a1759c..7ce0306a 100644 --- a/sheets/snippets/src/main/java/BatchUpdateValues.java +++ b/sheets/snippets/src/main/java/BatchUpdateValues.java @@ -14,6 +14,7 @@ // [START sheets_batch_update_values] + import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; @@ -26,7 +27,6 @@ import com.google.api.services.sheets.v4.model.ValueRange; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.ArrayList; import java.util.Collections; @@ -34,59 +34,59 @@ /* Class to demonstrate the use of Spreadsheet Batch Update Values API */ public class BatchUpdateValues { - /** - * Set values in one or more ranges of spreadsheet. - * - * @param spreadsheetId - Id of the spreadsheet. - * @param range - Range of cells of the spreadsheet. - * @param valueInputOption - Determines how input data should be interpreted. - * @param values - list of rows of values to input. - * @return spreadsheet with updated values - * @throws IOException - if credentials file not found. - */ - public static BatchUpdateValuesResponse batchUpdateValues(String spreadsheetId, - String range, - String valueInputOption, - List> values) - throws IOException { + /** + * Set values in one or more ranges of spreadsheet. + * + * @param spreadsheetId - Id of the spreadsheet. + * @param range - Range of cells of the spreadsheet. + * @param valueInputOption - Determines how input data should be interpreted. + * @param values - list of rows of values to input. + * @return spreadsheet with updated values + * @throws IOException - if credentials file not found. + */ + public static BatchUpdateValuesResponse batchUpdateValues(String spreadsheetId, + String range, + String valueInputOption, + List> values) + 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(SheetsScopes.SPREADSHEETS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(SheetsScopes.SPREADSHEETS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the sheets API client - Sheets service = new Sheets.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Sheets samples") - .build(); + // Create the sheets API client + Sheets service = new Sheets.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Sheets samples") + .build(); - List data = new ArrayList<>(); - data.add(new ValueRange() - .setRange(range) - .setValues(values)); + List data = new ArrayList<>(); + data.add(new ValueRange() + .setRange(range) + .setValues(values)); - BatchUpdateValuesResponse result = null; - try { - // Updates the values in the specified range. - BatchUpdateValuesRequest body = new BatchUpdateValuesRequest() - .setValueInputOption(valueInputOption) - .setData(data); - result = service.spreadsheets().values().batchUpdate(spreadsheetId, body).execute(); - System.out.printf("%d cells updated.", result.getTotalUpdatedCells()); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 404) { - System.out.printf("Spreadsheet not found with id '%s'.\n",spreadsheetId); - } else { - throw e; - } - } - return result; + BatchUpdateValuesResponse result = null; + try { + // Updates the values in the specified range. + BatchUpdateValuesRequest body = new BatchUpdateValuesRequest() + .setValueInputOption(valueInputOption) + .setData(data); + result = service.spreadsheets().values().batchUpdate(spreadsheetId, body).execute(); + System.out.printf("%d cells updated.", result.getTotalUpdatedCells()); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("Spreadsheet not found with id '%s'.\n", spreadsheetId); + } else { + throw e; + } } + return result; + } } // [END sheets_batch_update_values] \ No newline at end of file diff --git a/sheets/snippets/src/main/java/ConditionalFormatting.java b/sheets/snippets/src/main/java/ConditionalFormatting.java index bae8ef3b..4cecfc76 100644 --- a/sheets/snippets/src/main/java/ConditionalFormatting.java +++ b/sheets/snippets/src/main/java/ConditionalFormatting.java @@ -14,6 +14,7 @@ // [START sheets_conditional_formatting] + import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; @@ -21,10 +22,20 @@ 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.api.services.sheets.v4.model.AddConditionalFormatRuleRequest; +import com.google.api.services.sheets.v4.model.BatchUpdateSpreadsheetRequest; +import com.google.api.services.sheets.v4.model.BatchUpdateSpreadsheetResponse; +import com.google.api.services.sheets.v4.model.BooleanCondition; +import com.google.api.services.sheets.v4.model.BooleanRule; +import com.google.api.services.sheets.v4.model.CellFormat; +import com.google.api.services.sheets.v4.model.Color; +import com.google.api.services.sheets.v4.model.ConditionValue; +import com.google.api.services.sheets.v4.model.ConditionalFormatRule; +import com.google.api.services.sheets.v4.model.GridRange; +import com.google.api.services.sheets.v4.model.Request; +import com.google.api.services.sheets.v4.model.TextFormat; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.Arrays; import java.util.Collections; @@ -32,97 +43,97 @@ /* Class to demonstrate the use of Spreadsheet Conditional Formatting API */ public class ConditionalFormatting { - /** - * Create conditional formatting. - * - * @param spreadsheetId - Id of the spreadsheet. - * @return updated changes count. - * @throws IOException - if credentials file not found. - */ - public static BatchUpdateSpreadsheetResponse conditionalFormat(String spreadsheetId) - throws IOException { + /** + * Create conditional formatting. + * + * @param spreadsheetId - Id of the spreadsheet. + * @return updated changes count. + * @throws IOException - if credentials file not found. + */ + public static BatchUpdateSpreadsheetResponse conditionalFormat(String spreadsheetId) + 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(SheetsScopes.SPREADSHEETS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(SheetsScopes.SPREADSHEETS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the sheets API client - Sheets service = new Sheets.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Sheets samples") - .build(); + // Create the sheets API client + Sheets service = new Sheets.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Sheets samples") + .build(); - List ranges = Collections.singletonList(new GridRange() - .setSheetId(0) - .setStartRowIndex(1) - .setEndRowIndex(11) - .setStartColumnIndex(0) - .setEndColumnIndex(4) - ); - List requests = Arrays.asList( - new Request().setAddConditionalFormatRule(new AddConditionalFormatRuleRequest() - .setRule(new ConditionalFormatRule() - .setRanges(ranges) - .setBooleanRule(new BooleanRule() - .setCondition(new BooleanCondition() - .setType("CUSTOM_FORMULA") - .setValues(Collections.singletonList( - new ConditionValue().setUserEnteredValue( - "=GT($D2,median($D$2:$D$11))") - )) - ) - .setFormat(new CellFormat().setTextFormat( - new TextFormat().setForegroundColor( - new Color().setRed(0.8f)) - )) - ) - ) - .setIndex(0) - ), - new Request().setAddConditionalFormatRule(new AddConditionalFormatRuleRequest() - .setRule(new ConditionalFormatRule() - .setRanges(ranges) - .setBooleanRule(new BooleanRule() - .setCondition(new BooleanCondition() - .setType("CUSTOM_FORMULA") - .setValues(Collections.singletonList( - new ConditionValue().setUserEnteredValue( - "=LT($D2,median($D$2:$D$11))") - )) - ) - .setFormat(new CellFormat().setBackgroundColor( - new Color().setRed(1f).setGreen(0.4f).setBlue(0.4f) - )) - ) - ) - .setIndex(0) + List ranges = Collections.singletonList(new GridRange() + .setSheetId(0) + .setStartRowIndex(1) + .setEndRowIndex(11) + .setStartColumnIndex(0) + .setEndColumnIndex(4) + ); + List requests = Arrays.asList( + new Request().setAddConditionalFormatRule(new AddConditionalFormatRuleRequest() + .setRule(new ConditionalFormatRule() + .setRanges(ranges) + .setBooleanRule(new BooleanRule() + .setCondition(new BooleanCondition() + .setType("CUSTOM_FORMULA") + .setValues(Collections.singletonList( + new ConditionValue().setUserEnteredValue( + "=GT($D2,median($D$2:$D$11))") + )) + ) + .setFormat(new CellFormat().setTextFormat( + new TextFormat().setForegroundColor( + new Color().setRed(0.8f)) + )) + ) + ) + .setIndex(0) + ), + new Request().setAddConditionalFormatRule(new AddConditionalFormatRuleRequest() + .setRule(new ConditionalFormatRule() + .setRanges(ranges) + .setBooleanRule(new BooleanRule() + .setCondition(new BooleanCondition() + .setType("CUSTOM_FORMULA") + .setValues(Collections.singletonList( + new ConditionValue().setUserEnteredValue( + "=LT($D2,median($D$2:$D$11))") + )) + ) + .setFormat(new CellFormat().setBackgroundColor( + new Color().setRed(1f).setGreen(0.4f).setBlue(0.4f) + )) ) - ); + ) + .setIndex(0) + ) + ); - BatchUpdateSpreadsheetResponse result = null; - try { - // Execute the requests. - BatchUpdateSpreadsheetRequest body = - new BatchUpdateSpreadsheetRequest() - .setRequests(requests); - result = service.spreadsheets() - .batchUpdate(spreadsheetId, body) - .execute(); - System.out.printf("%d cells updated.", result.getReplies().size()); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 404) { - System.out.printf("Spreadsheet not found with id '%s'.\n",spreadsheetId); - } else { - throw e; - } - } - return result; + BatchUpdateSpreadsheetResponse result = null; + try { + // Execute the requests. + BatchUpdateSpreadsheetRequest body = + new BatchUpdateSpreadsheetRequest() + .setRequests(requests); + result = service.spreadsheets() + .batchUpdate(spreadsheetId, body) + .execute(); + System.out.printf("%d cells updated.", result.getReplies().size()); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("Spreadsheet not found with id '%s'.\n", spreadsheetId); + } else { + throw e; + } } + return result; + } } // [END sheets_conditional_formatting] diff --git a/sheets/snippets/src/main/java/Create.java b/sheets/snippets/src/main/java/Create.java index bf4e0c6b..4d66e78c 100644 --- a/sheets/snippets/src/main/java/Create.java +++ b/sheets/snippets/src/main/java/Create.java @@ -14,6 +14,7 @@ // [START sheets_create] + import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; @@ -23,45 +24,44 @@ import com.google.api.services.sheets.v4.model.SpreadsheetProperties; 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 Spreadsheet Create API */ public class Create { - /** - * Create a new spreadsheet. - * - * @param title - the name of the sheet to be created. - * @return newly created spreadsheet id - * @throws IOException - if credentials file not found. - */ - public static String createSpreadsheet(String title) throws IOException { + /** + * Create a new spreadsheet. + * + * @param title - the name of the sheet to be created. + * @return newly created spreadsheet id + * @throws IOException - if credentials file not found. + */ + public static String createSpreadsheet(String title) 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(SheetsScopes.SPREADSHEETS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(SheetsScopes.SPREADSHEETS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the sheets API client - Sheets service = new Sheets.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Sheets samples") - .build(); + // Create the sheets API client + Sheets service = new Sheets.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Sheets samples") + .build(); - // Create new spreadsheet with a title - Spreadsheet spreadsheet = new Spreadsheet() - .setProperties(new SpreadsheetProperties() - .setTitle(title)); - spreadsheet = service.spreadsheets().create(spreadsheet) - .setFields("spreadsheetId") - .execute(); - // Prints the new spreadsheet id - System.out.println("Spreadsheet ID: " + spreadsheet.getSpreadsheetId()); - return spreadsheet.getSpreadsheetId(); - } + // Create new spreadsheet with a title + Spreadsheet spreadsheet = new Spreadsheet() + .setProperties(new SpreadsheetProperties() + .setTitle(title)); + spreadsheet = service.spreadsheets().create(spreadsheet) + .setFields("spreadsheetId") + .execute(); + // Prints the new spreadsheet id + System.out.println("Spreadsheet ID: " + spreadsheet.getSpreadsheetId()); + return spreadsheet.getSpreadsheetId(); + } } // [END sheets_create] \ No newline at end of file diff --git a/sheets/snippets/src/main/java/GetValues.java b/sheets/snippets/src/main/java/GetValues.java index 620e0577..157d6cdf 100644 --- a/sheets/snippets/src/main/java/GetValues.java +++ b/sheets/snippets/src/main/java/GetValues.java @@ -14,6 +14,7 @@ // [START sheets_get_values] + import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; @@ -24,52 +25,51 @@ import com.google.api.services.sheets.v4.model.ValueRange; 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 Spreadsheet Get Values API */ public class GetValues { - /** - * Returns a range of values from a spreadsheet. - * - * @param spreadsheetId - Id of the spreadsheet. - * @param range - Range of cells of the spreadsheet. - * @return Values in the range - * @throws IOException - if credentials file not found. - */ - public static ValueRange getValues(String spreadsheetId, String range) throws IOException { + /** + * Returns a range of values from a spreadsheet. + * + * @param spreadsheetId - Id of the spreadsheet. + * @param range - Range of cells of the spreadsheet. + * @return Values in the range + * @throws IOException - if credentials file not found. + */ + public static ValueRange getValues(String spreadsheetId, String range) 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(SheetsScopes.SPREADSHEETS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(SheetsScopes.SPREADSHEETS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the sheets API client - Sheets service = new Sheets.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Sheets samples") - .build(); + // Create the sheets API client + Sheets service = new Sheets.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Sheets samples") + .build(); - ValueRange result = null; - try { - // Gets the values of the cells in the specified range. - result = service.spreadsheets().values().get(spreadsheetId, range).execute(); - int numRows = result.getValues() != null ? result.getValues().size() : 0; - System.out.printf("%d rows retrieved.", numRows); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 404) { - System.out.printf("Spreadsheet not found with id '%s'.\n",spreadsheetId); - } else { - throw e; - } - } - return result; + ValueRange result = null; + try { + // Gets the values of the cells in the specified range. + result = service.spreadsheets().values().get(spreadsheetId, range).execute(); + int numRows = result.getValues() != null ? result.getValues().size() : 0; + System.out.printf("%d rows retrieved.", numRows); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("Spreadsheet not found with id '%s'.\n", spreadsheetId); + } else { + throw e; + } } + return result; + } } // [END sheets_get_values] diff --git a/sheets/snippets/src/main/java/PivotTables.java b/sheets/snippets/src/main/java/PivotTables.java index a6de919b..8b56a058 100644 --- a/sheets/snippets/src/main/java/PivotTables.java +++ b/sheets/snippets/src/main/java/PivotTables.java @@ -14,6 +14,7 @@ // [START sheets_pivot_tables] + import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; @@ -36,7 +37,6 @@ import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; import com.google.common.collect.Lists; - import java.io.IOException; import java.util.ArrayList; import java.util.Collections; @@ -44,101 +44,102 @@ /* Class to demonstrate the use of Spreadsheet Create Pivot Tables API */ public class PivotTables { - /** - * Create pivot table. - * - * @param spreadsheetId - Id of the spreadsheet. - * @return pivot table's spreadsheet - * @throws IOException - if credentials file not found. - */ - public static BatchUpdateSpreadsheetResponse pivotTables(String spreadsheetId) throws IOException { + /** + * Create pivot table. + * + * @param spreadsheetId - Id of the spreadsheet. + * @return pivot table's spreadsheet + * @throws IOException - if credentials file not found. + */ + public static BatchUpdateSpreadsheetResponse pivotTables(String spreadsheetId) + 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(SheetsScopes.SPREADSHEETS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(SheetsScopes.SPREADSHEETS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the sheets API client - Sheets service = new Sheets.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Sheets samples") - .build(); + // Create the sheets API client + Sheets service = new Sheets.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Sheets samples") + .build(); - // Create two sheets for our pivot table. - List sheetsRequests = new ArrayList<>(); - BatchUpdateSpreadsheetResponse result = null; - try { - sheetsRequests.add(new Request().setAddSheet(new AddSheetRequest())); - sheetsRequests.add(new Request().setAddSheet(new AddSheetRequest())); + // Create two sheets for our pivot table. + List sheetsRequests = new ArrayList<>(); + BatchUpdateSpreadsheetResponse result = null; + try { + sheetsRequests.add(new Request().setAddSheet(new AddSheetRequest())); + sheetsRequests.add(new Request().setAddSheet(new AddSheetRequest())); - BatchUpdateSpreadsheetRequest createSheetsBody = new BatchUpdateSpreadsheetRequest() - .setRequests(sheetsRequests); - BatchUpdateSpreadsheetResponse createSheetsResponse = service.spreadsheets() - .batchUpdate(spreadsheetId, createSheetsBody).execute(); - int sourceSheetId = createSheetsResponse.getReplies().get(0).getAddSheet().getProperties() - .getSheetId(); - int targetSheetId = createSheetsResponse.getReplies().get(1).getAddSheet().getProperties() - .getSheetId(); + BatchUpdateSpreadsheetRequest createSheetsBody = new BatchUpdateSpreadsheetRequest() + .setRequests(sheetsRequests); + BatchUpdateSpreadsheetResponse createSheetsResponse = service.spreadsheets() + .batchUpdate(spreadsheetId, createSheetsBody).execute(); + int sourceSheetId = createSheetsResponse.getReplies().get(0).getAddSheet().getProperties() + .getSheetId(); + int targetSheetId = createSheetsResponse.getReplies().get(1).getAddSheet().getProperties() + .getSheetId(); - PivotTable pivotTable = new PivotTable() - .setSource( - new GridRange() - .setSheetId(sourceSheetId) - .setStartRowIndex(0) - .setStartColumnIndex(0) - .setEndRowIndex(20) - .setEndColumnIndex(7) - ) - .setRows(Collections.singletonList( - new PivotGroup() - .setSourceColumnOffset(1) - .setShowTotals(true) - .setSortOrder("ASCENDING") - )) - .setColumns(Collections.singletonList( - new PivotGroup() - .setSourceColumnOffset(4) - .setShowTotals(true) - .setSortOrder("ASCENDING") - )) - .setValues(Collections.singletonList( - new PivotValue() - .setSummarizeFunction("COUNTA") - .setSourceColumnOffset(4) - )); - List requests = Lists.newArrayList(); - Request updateCellsRequest = new Request().setUpdateCells(new UpdateCellsRequest() - .setFields("*") - .setRows(Collections.singletonList( - new RowData().setValues( - Collections.singletonList( - new CellData().setPivotTable(pivotTable)) - ) - )) - .setStart(new GridCoordinate() - .setSheetId(targetSheetId) - .setRowIndex(0) - .setColumnIndex(0) + PivotTable pivotTable = new PivotTable() + .setSource( + new GridRange() + .setSheetId(sourceSheetId) + .setStartRowIndex(0) + .setStartColumnIndex(0) + .setEndRowIndex(20) + .setEndColumnIndex(7) + ) + .setRows(Collections.singletonList( + new PivotGroup() + .setSourceColumnOffset(1) + .setShowTotals(true) + .setSortOrder("ASCENDING") + )) + .setColumns(Collections.singletonList( + new PivotGroup() + .setSourceColumnOffset(4) + .setShowTotals(true) + .setSortOrder("ASCENDING") + )) + .setValues(Collections.singletonList( + new PivotValue() + .setSummarizeFunction("COUNTA") + .setSourceColumnOffset(4) + )); + List requests = Lists.newArrayList(); + Request updateCellsRequest = new Request().setUpdateCells(new UpdateCellsRequest() + .setFields("*") + .setRows(Collections.singletonList( + new RowData().setValues( + Collections.singletonList( + new CellData().setPivotTable(pivotTable)) + ) + )) + .setStart(new GridCoordinate() + .setSheetId(targetSheetId) + .setRowIndex(0) + .setColumnIndex(0) - )); + )); - requests.add(updateCellsRequest); - BatchUpdateSpreadsheetRequest updateCellsBody = new BatchUpdateSpreadsheetRequest() - .setRequests(requests); - result = service.spreadsheets().batchUpdate(spreadsheetId, updateCellsBody).execute(); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 404) { - System.out.printf("Spreadsheet not found with id '%s'.\n",spreadsheetId); - } else { - throw e; - } - } - return result; + requests.add(updateCellsRequest); + BatchUpdateSpreadsheetRequest updateCellsBody = new BatchUpdateSpreadsheetRequest() + .setRequests(requests); + result = service.spreadsheets().batchUpdate(spreadsheetId, updateCellsBody).execute(); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("Spreadsheet not found with id '%s'.\n", spreadsheetId); + } else { + throw e; + } } + return result; + } } // [END sheets_pivot_tables] \ No newline at end of file diff --git a/sheets/snippets/src/main/java/UpdateValues.java b/sheets/snippets/src/main/java/UpdateValues.java index 9183f752..21e23308 100644 --- a/sheets/snippets/src/main/java/UpdateValues.java +++ b/sheets/snippets/src/main/java/UpdateValues.java @@ -14,6 +14,7 @@ // [START sheets_update_values] + import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; @@ -25,62 +26,61 @@ import com.google.api.services.sheets.v4.model.ValueRange; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; - import java.io.IOException; import java.util.Collections; import java.util.List; /* Class to demonstrate the use of Spreadsheet Update Values API */ public class UpdateValues { - /** - * Sets values in a range of a spreadsheet. - * - * @param spreadsheetId - Id of the spreadsheet. - * @param range - Range of cells of the spreadsheet. - * @param valueInputOption - Determines how input data should be interpreted. - * @param values - List of rows of values to input. - * @return spreadsheet with updated values - * @throws IOException - if credentials file not found. - */ - public static UpdateValuesResponse updateValues(String spreadsheetId, - String range, - String valueInputOption, - List> values) - throws IOException { + /** + * Sets values in a range of a spreadsheet. + * + * @param spreadsheetId - Id of the spreadsheet. + * @param range - Range of cells of the spreadsheet. + * @param valueInputOption - Determines how input data should be interpreted. + * @param values - List of rows of values to input. + * @return spreadsheet with updated values + * @throws IOException - if credentials file not found. + */ + public static UpdateValuesResponse updateValues(String spreadsheetId, + String range, + String valueInputOption, + List> values) + 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(SheetsScopes.SPREADSHEETS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(SheetsScopes.SPREADSHEETS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the sheets API client - Sheets service = new Sheets.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Sheets samples") - .build(); + // Create the sheets API client + Sheets service = new Sheets.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Sheets samples") + .build(); - UpdateValuesResponse result =null; - try { - // Updates the values in the specified range. - ValueRange body = new ValueRange() - .setValues(values); - result = service.spreadsheets().values().update(spreadsheetId, range, body) - .setValueInputOption(valueInputOption) - .execute(); - System.out.printf("%d cells updated.", result.getUpdatedCells()); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 404) { - System.out.printf("Spreadsheet not found with id '%s'.\n",spreadsheetId); - } else { - throw e; - } - } - return result; + UpdateValuesResponse result = null; + try { + // Updates the values in the specified range. + ValueRange body = new ValueRange() + .setValues(values); + result = service.spreadsheets().values().update(spreadsheetId, range, body) + .setValueInputOption(valueInputOption) + .execute(); + System.out.printf("%d cells updated.", result.getUpdatedCells()); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("Spreadsheet not found with id '%s'.\n", spreadsheetId); + } else { + throw e; + } } + return result; + } } // [END sheets_update_values] \ No newline at end of file diff --git a/sheets/snippets/src/test/java/BaseTest.java b/sheets/snippets/src/test/java/BaseTest.java index b1f27a1a..6e815050 100644 --- a/sheets/snippets/src/test/java/BaseTest.java +++ b/sheets/snippets/src/test/java/BaseTest.java @@ -25,12 +25,11 @@ import com.google.api.services.sheets.v4.model.GridRange; import com.google.api.services.sheets.v4.model.RepeatCellRequest; import com.google.api.services.sheets.v4.model.Request; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; import java.util.ArrayList; import java.util.List; - -import com.google.auth.http.HttpCredentialsAdapter; -import com.google.auth.oauth2.GoogleCredentials; import org.junit.Before; public class BaseTest { @@ -42,11 +41,11 @@ public GoogleCredentials getCredential() throws IOException { TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for your application. */ GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() - .createScoped(SheetsScopes.SPREADSHEETS,SheetsScopes.DRIVE); + .createScoped(SheetsScopes.SPREADSHEETS, SheetsScopes.DRIVE); return credentials; } - public Sheets buildService(GoogleCredentials credentials){ + public Sheets buildService(GoogleCredentials credentials) { return new Sheets.Builder( new NetHttpTransport(), GsonFactory.getDefaultInstance(), diff --git a/sheets/snippets/src/test/java/TestAppendValues.java b/sheets/snippets/src/test/java/TestAppendValues.java index 489218f8..b0dd9551 100644 --- a/sheets/snippets/src/test/java/TestAppendValues.java +++ b/sheets/snippets/src/test/java/TestAppendValues.java @@ -12,31 +12,32 @@ // See the License for the specific language governing permissions and // limitations under the License. +import static org.junit.Assert.assertEquals; + import com.google.api.services.sheets.v4.model.AppendValuesResponse; import com.google.api.services.sheets.v4.model.UpdateValuesResponse; -import org.junit.Test; import java.io.IOException; import java.util.Arrays; import java.util.List; -import static org.junit.Assert.assertEquals; +import org.junit.Test; // Unit testcase for spreadsheet append values snippet -public class TestAppendValues extends BaseTest{ +public class TestAppendValues extends BaseTest { - @Test - public void testAppendValues() throws IOException { - String spreadsheetId = Create.createSpreadsheet("Test Spreadsheet"); - populateValuesWithStrings(spreadsheetId); - List> values = Arrays.asList( - Arrays.asList("A", "B"), - Arrays.asList("C", "D")); - AppendValuesResponse result = AppendValues.appendValues(spreadsheetId, "A1:B2", "USER_ENTERED", - values); - assertEquals("Sheet1!A1:J10", result.getTableRange()); - UpdateValuesResponse updates = result.getUpdates(); - assertEquals(2, updates.getUpdatedRows().intValue()); - assertEquals(2, updates.getUpdatedColumns().intValue()); - assertEquals(4, updates.getUpdatedCells().intValue()); - deleteFileOnCleanup(spreadsheetId); - } + @Test + public void testAppendValues() throws IOException { + String spreadsheetId = Create.createSpreadsheet("Test Spreadsheet"); + populateValuesWithStrings(spreadsheetId); + List> values = Arrays.asList( + Arrays.asList("A", "B"), + Arrays.asList("C", "D")); + AppendValuesResponse result = AppendValues.appendValues(spreadsheetId, "A1:B2", "USER_ENTERED", + values); + assertEquals("Sheet1!A1:J10", result.getTableRange()); + UpdateValuesResponse updates = result.getUpdates(); + assertEquals(2, updates.getUpdatedRows().intValue()); + assertEquals(2, updates.getUpdatedColumns().intValue()); + assertEquals(4, updates.getUpdatedCells().intValue()); + deleteFileOnCleanup(spreadsheetId); + } } diff --git a/sheets/snippets/src/test/java/TestBatchGetValues.java b/sheets/snippets/src/test/java/TestBatchGetValues.java index d23e5582..9833ddc4 100644 --- a/sheets/snippets/src/test/java/TestBatchGetValues.java +++ b/sheets/snippets/src/test/java/TestBatchGetValues.java @@ -12,28 +12,29 @@ // See the License for the specific language governing permissions and // limitations under the License. +import static org.junit.Assert.assertEquals; + import com.google.api.services.sheets.v4.model.BatchGetValuesResponse; import com.google.api.services.sheets.v4.model.ValueRange; -import org.junit.Test; import java.io.IOException; import java.util.Arrays; import java.util.List; -import static org.junit.Assert.assertEquals; +import org.junit.Test; // Unit testcase for spreadsheet batch get values snippet -public class TestBatchGetValues extends BaseTest{ +public class TestBatchGetValues extends BaseTest { - @Test - public void testBatchGetValues() throws IOException { - String spreadsheetId = Create.createSpreadsheet("Test Spreadsheet"); - populateValuesWithStrings(spreadsheetId); - List ranges = Arrays.asList("A1:A3", "B1:C1"); - BatchGetValuesResponse result = BatchGetValues.batchGetValues(spreadsheetId, - ranges); - List valueRanges = result.getValueRanges(); - assertEquals(2, valueRanges.size()); - List> values = valueRanges.get(0).getValues(); - assertEquals(3, values.size()); - deleteFileOnCleanup(spreadsheetId); - } + @Test + public void testBatchGetValues() throws IOException { + String spreadsheetId = Create.createSpreadsheet("Test Spreadsheet"); + populateValuesWithStrings(spreadsheetId); + List ranges = Arrays.asList("A1:A3", "B1:C1"); + BatchGetValuesResponse result = BatchGetValues.batchGetValues(spreadsheetId, + ranges); + List valueRanges = result.getValueRanges(); + assertEquals(2, valueRanges.size()); + List> values = valueRanges.get(0).getValues(); + assertEquals(3, values.size()); + deleteFileOnCleanup(spreadsheetId); + } } diff --git a/sheets/snippets/src/test/java/TestBatchUpdate.java b/sheets/snippets/src/test/java/TestBatchUpdate.java index 5dc5799f..24d78ca0 100644 --- a/sheets/snippets/src/test/java/TestBatchUpdate.java +++ b/sheets/snippets/src/test/java/TestBatchUpdate.java @@ -12,26 +12,28 @@ // See the License for the specific language governing permissions and // limitations under the License. +import static org.junit.Assert.assertEquals; + import com.google.api.services.sheets.v4.model.BatchUpdateSpreadsheetResponse; import com.google.api.services.sheets.v4.model.FindReplaceResponse; import com.google.api.services.sheets.v4.model.Response; -import org.junit.Test; import java.io.IOException; import java.util.List; -import static org.junit.Assert.assertEquals; +import org.junit.Test; // Unit testcase for spreadsheet batch update snippet -public class TestBatchUpdate extends BaseTest{ +public class TestBatchUpdate extends BaseTest { - @Test - public void testBatchUpdate() throws IOException { - String spreadsheetId = Create.createSpreadsheet("Test Spreadsheet"); - populateValuesWithStrings(spreadsheetId); - BatchUpdateSpreadsheetResponse response = BatchUpdate.batchUpdate(spreadsheetId, "New Title", "Hello", "Goodbye"); - List replies = response.getReplies(); - assertEquals(2, replies.size()); - FindReplaceResponse findReplaceResponse = replies.get(1).getFindReplace(); - assertEquals(100, findReplaceResponse.getOccurrencesChanged().intValue()); - deleteFileOnCleanup(spreadsheetId); - } + @Test + public void testBatchUpdate() throws IOException { + String spreadsheetId = Create.createSpreadsheet("Test Spreadsheet"); + populateValuesWithStrings(spreadsheetId); + BatchUpdateSpreadsheetResponse response = + BatchUpdate.batchUpdate(spreadsheetId, "New Title", "Hello", "Goodbye"); + List replies = response.getReplies(); + assertEquals(2, replies.size()); + FindReplaceResponse findReplaceResponse = replies.get(1).getFindReplace(); + assertEquals(100, findReplaceResponse.getOccurrencesChanged().intValue()); + deleteFileOnCleanup(spreadsheetId); + } } diff --git a/sheets/snippets/src/test/java/TestBatchUpdateValues.java b/sheets/snippets/src/test/java/TestBatchUpdateValues.java index e17646d2..21560d94 100644 --- a/sheets/snippets/src/test/java/TestBatchUpdateValues.java +++ b/sheets/snippets/src/test/java/TestBatchUpdateValues.java @@ -12,29 +12,30 @@ // See the License for the specific language governing permissions and // limitations under the License. +import static org.junit.Assert.assertEquals; + import com.google.api.services.sheets.v4.model.BatchUpdateValuesResponse; -import org.junit.Test; import java.io.IOException; import java.util.Arrays; import java.util.List; -import static org.junit.Assert.assertEquals; +import org.junit.Test; // Unit testcase for spreadsheet batch update values snippet public class TestBatchUpdateValues extends BaseTest { - @Test - public void testBatchUpdateValues() throws IOException { - String spreadsheetId = Create.createSpreadsheet("Test Spreadsheet"); - List> values = Arrays.asList( - Arrays.asList("A", "B"), - Arrays.asList("C", "D")); - BatchUpdateValuesResponse result = - BatchUpdateValues.batchUpdateValues(spreadsheetId, "A1:B2", "USER_ENTERED", - values); - assertEquals(1, result.getResponses().size()); - assertEquals(2, result.getTotalUpdatedRows().intValue()); - assertEquals(2, result.getTotalUpdatedColumns().intValue()); - assertEquals(4, result.getTotalUpdatedCells().intValue()); - deleteFileOnCleanup(spreadsheetId); - } + @Test + public void testBatchUpdateValues() throws IOException { + String spreadsheetId = Create.createSpreadsheet("Test Spreadsheet"); + List> values = Arrays.asList( + Arrays.asList("A", "B"), + Arrays.asList("C", "D")); + BatchUpdateValuesResponse result = + BatchUpdateValues.batchUpdateValues(spreadsheetId, "A1:B2", "USER_ENTERED", + values); + assertEquals(1, result.getResponses().size()); + assertEquals(2, result.getTotalUpdatedRows().intValue()); + assertEquals(2, result.getTotalUpdatedColumns().intValue()); + assertEquals(4, result.getTotalUpdatedCells().intValue()); + deleteFileOnCleanup(spreadsheetId); + } } diff --git a/sheets/snippets/src/test/java/TestConditionalFormatting.java b/sheets/snippets/src/test/java/TestConditionalFormatting.java index 5d094165..22173381 100644 --- a/sheets/snippets/src/test/java/TestConditionalFormatting.java +++ b/sheets/snippets/src/test/java/TestConditionalFormatting.java @@ -12,22 +12,23 @@ // See the License for the specific language governing permissions and // limitations under the License. +import static org.junit.Assert.assertEquals; + import com.google.api.services.sheets.v4.model.BatchUpdateSpreadsheetResponse; -import org.junit.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; +import org.junit.Test; // Unit testcase for spreadsheet conditional formatting snippet public class TestConditionalFormatting extends BaseTest { - @Test - public void testConditionalFormat() throws IOException { - String spreadsheetId = Create.createSpreadsheet("Test Spreadsheet"); - populateValuesWithNumbers(spreadsheetId); - BatchUpdateSpreadsheetResponse response = - ConditionalFormatting.conditionalFormat(spreadsheetId); - assertEquals(spreadsheetId, response.getSpreadsheetId()); - assertEquals(2, response.getReplies().size()); - deleteFileOnCleanup(spreadsheetId); - } + @Test + public void testConditionalFormat() throws IOException { + String spreadsheetId = Create.createSpreadsheet("Test Spreadsheet"); + populateValuesWithNumbers(spreadsheetId); + BatchUpdateSpreadsheetResponse response = + ConditionalFormatting.conditionalFormat(spreadsheetId); + assertEquals(spreadsheetId, response.getSpreadsheetId()); + assertEquals(2, response.getReplies().size()); + deleteFileOnCleanup(spreadsheetId); + } } diff --git a/sheets/snippets/src/test/java/TestCreate.java b/sheets/snippets/src/test/java/TestCreate.java index c75f0f4f..2fe55351 100644 --- a/sheets/snippets/src/test/java/TestCreate.java +++ b/sheets/snippets/src/test/java/TestCreate.java @@ -12,17 +12,18 @@ // See the License for the specific language governing permissions and // limitations under the License. -import org.junit.Test; -import java.io.IOException; import static org.junit.Assert.assertNotNull; +import java.io.IOException; +import org.junit.Test; + // Unit testcase for create spreadsheet snippet -public class TestCreate extends BaseTest{ +public class TestCreate extends BaseTest { - @Test - public void testCreate() throws IOException { - String id = Create.createSpreadsheet("Test Spreadsheet"); - assertNotNull(id); - deleteFileOnCleanup(id); - } + @Test + public void testCreate() throws IOException { + String id = Create.createSpreadsheet("Test Spreadsheet"); + assertNotNull(id); + deleteFileOnCleanup(id); + } } diff --git a/sheets/snippets/src/test/java/TestGetValues.java b/sheets/snippets/src/test/java/TestGetValues.java index ed640bfb..13bee226 100644 --- a/sheets/snippets/src/test/java/TestGetValues.java +++ b/sheets/snippets/src/test/java/TestGetValues.java @@ -12,23 +12,24 @@ // See the License for the specific language governing permissions and // limitations under the License. +import static org.junit.Assert.assertEquals; + import com.google.api.services.sheets.v4.model.ValueRange; -import org.junit.Test; import java.io.IOException; import java.util.List; -import static org.junit.Assert.assertEquals; +import org.junit.Test; // Unit testcase for spreadsheet get values snippet -public class TestGetValues extends BaseTest{ +public class TestGetValues extends BaseTest { - @Test - public void testGetValues() throws IOException { - String spreadsheetId = Create.createSpreadsheet("Test Spreadsheet"); - populateValuesWithStrings(spreadsheetId); - ValueRange result = GetValues.getValues(spreadsheetId, "A1:C2"); - List> values = result.getValues(); - assertEquals(2, values.size()); - assertEquals(3, values.get(0).size()); - deleteFileOnCleanup(spreadsheetId); - } + @Test + public void testGetValues() throws IOException { + String spreadsheetId = Create.createSpreadsheet("Test Spreadsheet"); + populateValuesWithStrings(spreadsheetId); + ValueRange result = GetValues.getValues(spreadsheetId, "A1:C2"); + List> values = result.getValues(); + assertEquals(2, values.size()); + assertEquals(3, values.get(0).size()); + deleteFileOnCleanup(spreadsheetId); + } } diff --git a/sheets/snippets/src/test/java/TestPivotTable.java b/sheets/snippets/src/test/java/TestPivotTable.java index 83d26883..91bd4f48 100644 --- a/sheets/snippets/src/test/java/TestPivotTable.java +++ b/sheets/snippets/src/test/java/TestPivotTable.java @@ -14,19 +14,20 @@ * limitations under the License. */ +import static org.junit.Assert.assertNotNull; + import com.google.api.services.sheets.v4.model.BatchUpdateSpreadsheetResponse; -import org.junit.Test; import java.io.IOException; -import static org.junit.Assert.assertNotNull; +import org.junit.Test; // Unit testcase for spreadsheet pivot table snippet -public class TestPivotTable extends BaseTest{ +public class TestPivotTable extends BaseTest { - @Test - public void testPivotTable() throws IOException { - String spreadsheetId = Create.createSpreadsheet("Test Spreadsheet"); - BatchUpdateSpreadsheetResponse result = PivotTables.pivotTables(spreadsheetId); - assertNotNull(result); - deleteFileOnCleanup(spreadsheetId); - } + @Test + public void testPivotTable() throws IOException { + String spreadsheetId = Create.createSpreadsheet("Test Spreadsheet"); + BatchUpdateSpreadsheetResponse result = PivotTables.pivotTables(spreadsheetId); + assertNotNull(result); + deleteFileOnCleanup(spreadsheetId); + } } diff --git a/sheets/snippets/src/test/java/TestUpdateValues.java b/sheets/snippets/src/test/java/TestUpdateValues.java index 133cb48d..8c8355a7 100644 --- a/sheets/snippets/src/test/java/TestUpdateValues.java +++ b/sheets/snippets/src/test/java/TestUpdateValues.java @@ -12,27 +12,28 @@ // See the License for the specific language governing permissions and // limitations under the License. +import static org.junit.Assert.assertEquals; + import com.google.api.services.sheets.v4.model.UpdateValuesResponse; -import org.junit.Test; import java.io.IOException; import java.util.Arrays; import java.util.List; -import static org.junit.Assert.assertEquals; +import org.junit.Test; // Unit testcase for spreadsheet update values snippet -public class TestUpdateValues extends BaseTest{ +public class TestUpdateValues extends BaseTest { - @Test - public void testUpdateValues() throws IOException { - String spreadsheetId = Create.createSpreadsheet("Test Spreadsheet"); - List> values = Arrays.asList( - Arrays.asList("A", "B"), - Arrays.asList("C", "D")); - UpdateValuesResponse result = UpdateValues.updateValues(spreadsheetId, - "A1:B2", "USER_ENTERED", values); - assertEquals(2, result.getUpdatedRows().intValue()); - assertEquals(2, result.getUpdatedColumns().intValue()); - assertEquals(4, result.getUpdatedCells().intValue()); - deleteFileOnCleanup(spreadsheetId); - } + @Test + public void testUpdateValues() throws IOException { + String spreadsheetId = Create.createSpreadsheet("Test Spreadsheet"); + List> values = Arrays.asList( + Arrays.asList("A", "B"), + Arrays.asList("C", "D")); + UpdateValuesResponse result = UpdateValues.updateValues(spreadsheetId, + "A1:B2", "USER_ENTERED", values); + assertEquals(2, result.getUpdatedRows().intValue()); + assertEquals(2, result.getUpdatedColumns().intValue()); + assertEquals(4, result.getUpdatedCells().intValue()); + deleteFileOnCleanup(spreadsheetId); + } } diff --git a/slides/quickstart/src/main/java/SlidesQuickstart.java b/slides/quickstart/src/main/java/SlidesQuickstart.java index dc776391..b404b3cb 100644 --- a/slides/quickstart/src/main/java/SlidesQuickstart.java +++ b/slides/quickstart/src/main/java/SlidesQuickstart.java @@ -13,6 +13,7 @@ // limitations under the License. // [START slides_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; @@ -27,7 +28,6 @@ import com.google.api.services.slides.v1.SlidesScopes; import com.google.api.services.slides.v1.model.Page; import com.google.api.services.slides.v1.model.Presentation; - import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; @@ -37,58 +37,64 @@ import java.util.List; public class SlidesQuickstart { - private static final String APPLICATION_NAME = "Google Slides API Java Quickstart"; - private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); - private static final String TOKENS_DIRECTORY_PATH = "tokens"; + private static final String APPLICATION_NAME = "Google Slides API Java Quickstart"; + private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); + 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(SlidesScopes.PRESENTATIONS_READONLY); - private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; + /** + * 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(SlidesScopes.PRESENTATIONS_READONLY); + private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; - /** - * Creates an authorized Credential object. - * @param HTTP_TRANSPORT The network HTTP Transport. - * @return An authorized Credential object. - * @throws IOException If the credentials.json file cannot be found. - */ - private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException { - // Load client secrets. - InputStream in = SlidesQuickstart.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"); + /** + * Creates an authorized Credential object. + * + * @param HTTP_TRANSPORT The network HTTP Transport. + * @return An authorized Credential object. + * @throws IOException If the credentials.json file cannot be found. + */ + private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) + throws IOException { + // Load client secrets. + InputStream in = SlidesQuickstart.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"); + } - public static void main(String... args) throws IOException, GeneralSecurityException { - // Build a new authorized API client service. - final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); - Slides service = new Slides.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) - .setApplicationName(APPLICATION_NAME) - .build(); + public static void main(String... args) throws IOException, GeneralSecurityException { + // Build a new authorized API client service. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Slides service = + new Slides.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) + .setApplicationName(APPLICATION_NAME) + .build(); - // Prints the number of slides and elements in a sample presentation: - // https://docs.google.com/presentation/d/1EAYk18WDjIG-zp_0vLm3CsfQh_i8eXc67Jo2O9C6Vuc/edit - String presentationId = "1EAYk18WDjIG-zp_0vLm3CsfQh_i8eXc67Jo2O9C6Vuc"; - Presentation response = service.presentations().get(presentationId).execute(); - List slides = response.getSlides(); + // Prints the number of slides and elements in a sample presentation: + // https://docs.google.com/presentation/d/1EAYk18WDjIG-zp_0vLm3CsfQh_i8eXc67Jo2O9C6Vuc/edit + String presentationId = "1EAYk18WDjIG-zp_0vLm3CsfQh_i8eXc67Jo2O9C6Vuc"; + Presentation response = service.presentations().get(presentationId).execute(); + List slides = response.getSlides(); - System.out.printf("The presentation contains %s slides:\n", slides.size()); - for (int i = 0; i < slides.size(); ++i) { - System.out.printf("- Slide #%s contains %s elements.\n", i + 1, slides.get(i).getPageElements().size()); - } + System.out.printf("The presentation contains %s slides:\n", slides.size()); + for (int i = 0; i < slides.size(); ++i) { + System.out.printf("- Slide #%s contains %s elements.\n", i + 1, + slides.get(i).getPageElements().size()); } + } } // [END slides_quickstart] diff --git a/slides/snippets/src/main/java/CopyPresentation.java b/slides/snippets/src/main/java/CopyPresentation.java index b6534cde..6b1def55 100644 --- a/slides/snippets/src/main/java/CopyPresentation.java +++ b/slides/snippets/src/main/java/CopyPresentation.java @@ -14,6 +14,7 @@ // [START slides_copy_presentation] + import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; @@ -30,49 +31,50 @@ /* Class to demonstrate the use of Slides Copy Presentation API */ public class CopyPresentation { - /** - * Copy an existing presentation. - * - * @param presentationId - id of the presentation. - * @param copyTitle - New title of the presentation. - * @return presentation id - * @throws IOException - if credentials file not found. - */ - public static String copyPresentation(String presentationId, String copyTitle) throws IOException { + /** + * Copy an existing presentation. + * + * @param presentationId - id of the presentation. + * @param copyTitle - New title of the presentation. + * @return presentation id + * @throws IOException - if credentials file not found. + */ + public static String copyPresentation(String presentationId, String copyTitle) + 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(SlidesScopes.DRIVE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(SlidesScopes.DRIVE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the drive API client - Drive driveService = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Slides samples") - .build(); + // Create the drive API client + Drive driveService = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Slides samples") + .build(); - String presentationCopyId = null; - try { - // Copies an existing presentation using specified presentation title. - File copyMetadata = new File().setName(copyTitle); - File presentationCopyFile = - driveService.files().copy(presentationId, copyMetadata).execute(); - presentationCopyId = presentationCopyFile.getId(); - // Prints the new copied presentation id. - System.out.println("New copied presentation id "+presentationCopyId); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 404) { - System.out.printf("Presentation not found with id '%s'.\n", presentationId); - } else { - throw e; - } - } - return presentationCopyId; + String presentationCopyId = null; + try { + // Copies an existing presentation using specified presentation title. + File copyMetadata = new File().setName(copyTitle); + File presentationCopyFile = + driveService.files().copy(presentationId, copyMetadata).execute(); + presentationCopyId = presentationCopyFile.getId(); + // Prints the new copied presentation id. + System.out.println("New copied presentation id " + presentationCopyId); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("Presentation not found with id '%s'.\n", presentationId); + } else { + throw e; + } } + return presentationCopyId; + } } // [END slides_copy_presentation] \ No newline at end of file diff --git a/slides/snippets/src/main/java/CreateBulletedText.java b/slides/snippets/src/main/java/CreateBulletedText.java index 412ed14b..89202f6a 100644 --- a/slides/snippets/src/main/java/CreateBulletedText.java +++ b/slides/snippets/src/main/java/CreateBulletedText.java @@ -14,6 +14,7 @@ // [START slides_create_bulleted_text] + import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; @@ -36,60 +37,60 @@ /* Class to demonstrate the use of Slide Create Bulleted Text API */ public class CreateBulletedText { - /** - * Add arrow-diamond-disc bullets to all text in the shape. - * - * @param presentationId - id of the presentation. - * @param shapeId - id of the shape. - * @return response - * @throws IOException - if credentials file not found. - */ - public static BatchUpdatePresentationResponse createBulletedText(String presentationId, - String shapeId) throws IOException { + /** + * Add arrow-diamond-disc bullets to all text in the shape. + * + * @param presentationId - id of the presentation. + * @param shapeId - id of the shape. + * @return response + * @throws IOException - if credentials file not found. + */ + public static BatchUpdatePresentationResponse createBulletedText(String presentationId, + String shapeId) + 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(SlidesScopes.PRESENTATIONS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(SlidesScopes.PRESENTATIONS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the slides API client - Slides service = new Slides.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Slides samples") - .build(); + // Create the slides API client + Slides service = new Slides.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Slides samples") + .build(); - // Add arrow-diamond-disc bullets to all text in the shape. - List requests = new ArrayList<>(); - requests.add(new Request() - .setCreateParagraphBullets(new CreateParagraphBulletsRequest() - .setObjectId(shapeId) - .setTextRange(new Range() - .setType("ALL")) - .setBulletPreset("BULLET_ARROW_DIAMOND_DISC"))); + // Add arrow-diamond-disc bullets to all text in the shape. + List requests = new ArrayList<>(); + requests.add(new Request() + .setCreateParagraphBullets(new CreateParagraphBulletsRequest() + .setObjectId(shapeId) + .setTextRange(new Range() + .setType("ALL")) + .setBulletPreset("BULLET_ARROW_DIAMOND_DISC"))); - BatchUpdatePresentationResponse response =null; - try { - // Execute the request. - BatchUpdatePresentationRequest body = - new BatchUpdatePresentationRequest().setRequests(requests); - response = service.presentations().batchUpdate(presentationId, body).execute(); - System.out.println("Added bullets to text in shape with ID: " + shapeId); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 400) { - System.out.printf("Shape not found with id '%s'.\n", shapeId); - } else if (error.getCode() == 404) { - System.out.printf("Presentation not found with id '%s'.\n", presentationId); - } - else { - throw e; - } - } - return response; + BatchUpdatePresentationResponse response = null; + try { + // Execute the request. + BatchUpdatePresentationRequest body = + new BatchUpdatePresentationRequest().setRequests(requests); + response = service.presentations().batchUpdate(presentationId, body).execute(); + System.out.println("Added bullets to text in shape with ID: " + shapeId); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 400) { + System.out.printf("Shape not found with id '%s'.\n", shapeId); + } else if (error.getCode() == 404) { + System.out.printf("Presentation not found with id '%s'.\n", presentationId); + } else { + throw e; + } } + return response; + } } // [END slides_create_bulleted_text] \ No newline at end of file diff --git a/slides/snippets/src/main/java/CreateImage.java b/slides/snippets/src/main/java/CreateImage.java index 132b3493..55ec3534 100644 --- a/slides/snippets/src/main/java/CreateImage.java +++ b/slides/snippets/src/main/java/CreateImage.java @@ -14,6 +14,7 @@ // [START slides_create_image] + import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; @@ -40,75 +41,74 @@ /* Class to demonstrate the use of Slides Create Image API */ public class CreateImage { - /** - * Create a new image, using the supplied object ID, with content - * downloaded from imageUrl. - * - * @param presentationId - id of the presentation. - * @param slideId - id of the shape. - * @param imageUrl - Url of the image. - * @return image id - * @throws IOException - if credentials file not found. - */ - public static BatchUpdatePresentationResponse createImage(String presentationId, - String slideId, - String imageUrl) - throws IOException { + /** + * Create a new image, using the supplied object ID, with content + * downloaded from imageUrl. + * + * @param presentationId - id of the presentation. + * @param slideId - id of the shape. + * @param imageUrl - Url of the image. + * @return image id + * @throws IOException - if credentials file not found. + */ + public static BatchUpdatePresentationResponse createImage(String presentationId, + String slideId, + String imageUrl) + 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(SlidesScopes.PRESENTATIONS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(SlidesScopes.PRESENTATIONS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the slides API client - Slides service = new Slides.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Slides samples") - .build(); + // Create the slides API client + Slides service = new Slides.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Slides samples") + .build(); - // Create a new image, using the supplied object ID, with content downloaded from imageUrl. - List requests = new ArrayList<>(); - String imageId = "MyImageId_01"; - Dimension emu4M = new Dimension().setMagnitude(4000000.0).setUnit("EMU"); - requests.add(new Request() - .setCreateImage(new CreateImageRequest() - .setObjectId(imageId) - .setUrl(imageUrl) - .setElementProperties(new PageElementProperties() - .setPageObjectId(slideId) - .setSize(new Size() - .setHeight(emu4M) - .setWidth(emu4M)) - .setTransform(new AffineTransform() - .setScaleX(1.0) - .setScaleY(1.0) - .setTranslateX(100000.0) - .setTranslateY(100000.0) - .setUnit("EMU"))))); + // Create a new image, using the supplied object ID, with content downloaded from imageUrl. + List requests = new ArrayList<>(); + String imageId = "MyImageId_01"; + Dimension emu4M = new Dimension().setMagnitude(4000000.0).setUnit("EMU"); + requests.add(new Request() + .setCreateImage(new CreateImageRequest() + .setObjectId(imageId) + .setUrl(imageUrl) + .setElementProperties(new PageElementProperties() + .setPageObjectId(slideId) + .setSize(new Size() + .setHeight(emu4M) + .setWidth(emu4M)) + .setTransform(new AffineTransform() + .setScaleX(1.0) + .setScaleY(1.0) + .setTranslateX(100000.0) + .setTranslateY(100000.0) + .setUnit("EMU"))))); - BatchUpdatePresentationResponse response = null; - try { - // Execute the request. - BatchUpdatePresentationRequest body = - new BatchUpdatePresentationRequest().setRequests(requests); - response = service.presentations().batchUpdate(presentationId, body).execute(); - CreateImageResponse createImageResponse = response.getReplies().get(0).getCreateImage(); - // Prints the created image id. - System.out.println("Created image with ID: " + createImageResponse.getObjectId()); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 404) { - System.out.printf("Presentation not found with id '%s'.\n", presentationId); - } - else { - throw e; - } - } - return response; + BatchUpdatePresentationResponse response = null; + try { + // Execute the request. + BatchUpdatePresentationRequest body = + new BatchUpdatePresentationRequest().setRequests(requests); + response = service.presentations().batchUpdate(presentationId, body).execute(); + CreateImageResponse createImageResponse = response.getReplies().get(0).getCreateImage(); + // Prints the created image id. + System.out.println("Created image with ID: " + createImageResponse.getObjectId()); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("Presentation not found with id '%s'.\n", presentationId); + } else { + throw e; + } } + return response; + } } // [END slides_create_image] \ No newline at end of file diff --git a/slides/snippets/src/main/java/CreatePresentation.java b/slides/snippets/src/main/java/CreatePresentation.java index 966362b2..f7d7d96b 100644 --- a/slides/snippets/src/main/java/CreatePresentation.java +++ b/slides/snippets/src/main/java/CreatePresentation.java @@ -14,6 +14,7 @@ // [START slides_create_presentation] + import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; @@ -28,38 +29,38 @@ /* Class to demonstrate the use of Slides Create Presentation API */ public class CreatePresentation { - /** - * Creates a new presentation. - * - * @param title - the name of the presentation to be created - * @return presentation id - * @throws IOException - if credentials file not found. - */ - public static String createPresentation(String title) throws IOException { + /** + * Creates a new presentation. + * + * @param title - the name of the presentation to be created + * @return presentation id + * @throws IOException - if credentials file not found. + */ + public static String createPresentation(String title) 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(SlidesScopes.PRESENTATIONS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(SlidesScopes.PRESENTATIONS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the slides API client - Slides service = new Slides.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Slides samples") - .build(); + // Create the slides API client + Slides service = new Slides.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Slides samples") + .build(); - // Creates a blank presentation with a specified title. - Presentation presentation = new Presentation() - .setTitle(title); - presentation = service.presentations().create(presentation) - .setFields("presentationId") - .execute(); - // Prints the newly created presentation id. - System.out.println("Created presentation with ID: " + presentation.getPresentationId()); - return presentation.getPresentationId(); - } + // Creates a blank presentation with a specified title. + Presentation presentation = new Presentation() + .setTitle(title); + presentation = service.presentations().create(presentation) + .setFields("presentationId") + .execute(); + // Prints the newly created presentation id. + System.out.println("Created presentation with ID: " + presentation.getPresentationId()); + return presentation.getPresentationId(); + } } // [END slides_create_presentation] \ No newline at end of file diff --git a/slides/snippets/src/main/java/CreateSheetsChart.java b/slides/snippets/src/main/java/CreateSheetsChart.java index d866007e..3f3d3e9b 100644 --- a/slides/snippets/src/main/java/CreateSheetsChart.java +++ b/slides/snippets/src/main/java/CreateSheetsChart.java @@ -14,6 +14,7 @@ // [START slides_create_sheets_chart] + import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; @@ -39,76 +40,75 @@ /* Class to demonstrate the use of Slides Create Chart API */ public class CreateSheetsChart { - /** - * Adds chart from spreadsheet to slides as linked. - * - * @param presentationId - id of the presentation. - * @param pageId - id of the page. - * @param spreadsheetId - id of the spreadsheet. - * @param sheetChartId - id of the chart in sheets. - * @return presentation chart id - * @throws IOException - if credentials file not found. - */ - public static BatchUpdatePresentationResponse createSheetsChart( - String presentationId, String pageId, String spreadsheetId, Integer sheetChartId) - throws IOException { + /** + * Adds chart from spreadsheet to slides as linked. + * + * @param presentationId - id of the presentation. + * @param pageId - id of the page. + * @param spreadsheetId - id of the spreadsheet. + * @param sheetChartId - id of the chart in sheets. + * @return presentation chart id + * @throws IOException - if credentials file not found. + */ + public static BatchUpdatePresentationResponse createSheetsChart( + String presentationId, String pageId, String spreadsheetId, Integer sheetChartId) + 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(SlidesScopes.PRESENTATIONS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(SlidesScopes.PRESENTATIONS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the slides API client - Slides service = new Slides.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Slides samples") - .build(); + // Create the slides API client + Slides service = new Slides.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Slides samples") + .build(); - // Embed a Sheets chart (indicated by the spreadsheetId and sheetChartId) onto - // a page in the presentation. Setting the linking mode as "LINKED" allows the - // chart to be refreshed if the Sheets version is updated. - List requests = new ArrayList<>(); - Dimension emu4M = new Dimension().setMagnitude(4000000.0).setUnit("EMU"); - String presentationChartId = "MyEmbeddedChart"; - requests.add(new Request() - .setCreateSheetsChart(new CreateSheetsChartRequest() - .setObjectId(presentationChartId) - .setSpreadsheetId(spreadsheetId) - .setChartId(sheetChartId) - .setLinkingMode("LINKED") - .setElementProperties(new PageElementProperties() - .setPageObjectId(pageId) - .setSize(new Size() - .setHeight(emu4M) - .setWidth(emu4M)) - .setTransform(new AffineTransform() - .setScaleX(1.0) - .setScaleY(1.0) - .setTranslateX(100000.0) - .setTranslateY(100000.0) - .setUnit("EMU"))))); + // Embed a Sheets chart (indicated by the spreadsheetId and sheetChartId) onto + // a page in the presentation. Setting the linking mode as "LINKED" allows the + // chart to be refreshed if the Sheets version is updated. + List requests = new ArrayList<>(); + Dimension emu4M = new Dimension().setMagnitude(4000000.0).setUnit("EMU"); + String presentationChartId = "MyEmbeddedChart"; + requests.add(new Request() + .setCreateSheetsChart(new CreateSheetsChartRequest() + .setObjectId(presentationChartId) + .setSpreadsheetId(spreadsheetId) + .setChartId(sheetChartId) + .setLinkingMode("LINKED") + .setElementProperties(new PageElementProperties() + .setPageObjectId(pageId) + .setSize(new Size() + .setHeight(emu4M) + .setWidth(emu4M)) + .setTransform(new AffineTransform() + .setScaleX(1.0) + .setScaleY(1.0) + .setTranslateX(100000.0) + .setTranslateY(100000.0) + .setUnit("EMU"))))); - BatchUpdatePresentationResponse response = null; - try { - // Execute the request. - BatchUpdatePresentationRequest body = - new BatchUpdatePresentationRequest().setRequests(requests); - response = service.presentations().batchUpdate(presentationId, body).execute(); - System.out.println("Added a linked Sheets chart with ID " + presentationChartId); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 404) { - System.out.printf("Presentation not found with id '%s'.\n", presentationId); - } - else { - throw e; - } - } - return response; + BatchUpdatePresentationResponse response = null; + try { + // Execute the request. + BatchUpdatePresentationRequest body = + new BatchUpdatePresentationRequest().setRequests(requests); + response = service.presentations().batchUpdate(presentationId, body).execute(); + System.out.println("Added a linked Sheets chart with ID " + presentationChartId); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("Presentation not found with id '%s'.\n", presentationId); + } else { + throw e; + } } + return response; + } } // [END slides_create_sheets_chart] \ No newline at end of file diff --git a/slides/snippets/src/main/java/CreateSlide.java b/slides/snippets/src/main/java/CreateSlide.java index 9a809264..1ef009ab 100644 --- a/slides/snippets/src/main/java/CreateSlide.java +++ b/slides/snippets/src/main/java/CreateSlide.java @@ -14,6 +14,7 @@ // [START slides_create_slide] + import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.http.HttpRequestInitializer; @@ -37,64 +38,65 @@ /* Class to demonstrate the use of Create Slides API */ public class CreateSlide { - /** - * Creates a new slide. - * - * @param presentationId - id of the presentation. - * @return slide id - * @throws IOException - if credentials file not found. - */ - public static BatchUpdatePresentationResponse createSlide(String presentationId) throws IOException { + /** + * Creates a new slide. + * + * @param presentationId - id of the presentation. + * @return slide id + * @throws IOException - if credentials file not found. + */ + public static BatchUpdatePresentationResponse createSlide(String presentationId) + 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(SlidesScopes.PRESENTATIONS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(SlidesScopes.PRESENTATIONS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the slides API client - Slides service = new Slides.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Slides samples") - .build(); + // Create the slides API client + Slides service = new Slides.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Slides samples") + .build(); - // Add a slide at index 1 using the predefined "TITLE_AND_TWO_COLUMNS" layout - List requests = new ArrayList<>(); - String slideId = "MyNewSlide_001"; - BatchUpdatePresentationResponse response = null; - try { - requests.add(new Request() - .setCreateSlide(new CreateSlideRequest() - .setObjectId(slideId) - .setInsertionIndex(1) - .setSlideLayoutReference(new LayoutReference() - .setPredefinedLayout("TITLE_AND_TWO_COLUMNS")))); + // Add a slide at index 1 using the predefined "TITLE_AND_TWO_COLUMNS" layout + List requests = new ArrayList<>(); + String slideId = "MyNewSlide_001"; + BatchUpdatePresentationResponse response = null; + try { + requests.add(new Request() + .setCreateSlide(new CreateSlideRequest() + .setObjectId(slideId) + .setInsertionIndex(1) + .setSlideLayoutReference(new LayoutReference() + .setPredefinedLayout("TITLE_AND_TWO_COLUMNS")))); - // If you wish to populate the slide with elements, add create requests here, - // using the slide ID specified above. + // If you wish to populate the slide with elements, add create requests here, + // using the slide ID specified above. - // Execute the request. - BatchUpdatePresentationRequest body = - new BatchUpdatePresentationRequest().setRequests(requests); - response = service.presentations().batchUpdate(presentationId, body).execute(); - CreateSlideResponse createSlideResponse = response.getReplies().get(0).getCreateSlide(); - // Prints the slide id. - System.out.println("Created slide with ID: " + createSlideResponse.getObjectId()); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 400) { - System.out.printf(" Id '%s' should be unique among all pages and page elements.\n", presentationId); - } else if (error.getCode() == 404) { - System.out.printf("Presentation not found with id '%s'.\n", presentationId); - } - else { - throw e; - } - } - return response; + // Execute the request. + BatchUpdatePresentationRequest body = + new BatchUpdatePresentationRequest().setRequests(requests); + response = service.presentations().batchUpdate(presentationId, body).execute(); + CreateSlideResponse createSlideResponse = response.getReplies().get(0).getCreateSlide(); + // Prints the slide id. + System.out.println("Created slide with ID: " + createSlideResponse.getObjectId()); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 400) { + System.out.printf(" Id '%s' should be unique among all pages and page elements.\n", + presentationId); + } else if (error.getCode() == 404) { + System.out.printf("Presentation not found with id '%s'.\n", presentationId); + } else { + throw e; + } } + return response; + } } // [END slides_create_slide] \ No newline at end of file diff --git a/slides/snippets/src/main/java/CreateTextboxWithText.java b/slides/snippets/src/main/java/CreateTextboxWithText.java index bb7df571..797be99e 100644 --- a/slides/snippets/src/main/java/CreateTextboxWithText.java +++ b/slides/snippets/src/main/java/CreateTextboxWithText.java @@ -14,6 +14,7 @@ // [START slides_create_textbox_with_text] + import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; @@ -41,76 +42,76 @@ /* Class to demonstrate the use of Slides Create Textbox API */ public class CreateTextboxWithText { - /** - * Create a new square textbox, using the specified id. - * - * @param presentationId - id of the presentation. - * @param slideId - id of the slide. - * @param textBoxId - id for the textbox. - * @return textbox id - * @throws IOException - if credentials file not found. - */ - public static BatchUpdatePresentationResponse createTextBoxWithText( - String presentationId, String slideId, String textBoxId) throws IOException { + /** + * Create a new square textbox, using the specified id. + * + * @param presentationId - id of the presentation. + * @param slideId - id of the slide. + * @param textBoxId - id for the textbox. + * @return textbox id + * @throws IOException - if credentials file not found. + */ + public static BatchUpdatePresentationResponse createTextBoxWithText( + String presentationId, String slideId, String textBoxId) 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(SlidesScopes.PRESENTATIONS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(SlidesScopes.PRESENTATIONS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the slides API client - Slides service = new Slides.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Slides samples") - .build(); + // Create the slides API client + Slides service = new Slides.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Slides samples") + .build(); - // Create a new square text box, using a supplied object ID. - List requests = new ArrayList<>(); - Dimension pt350 = new Dimension().setMagnitude(350.0).setUnit("PT"); - requests.add(new Request() - .setCreateShape(new CreateShapeRequest() - .setObjectId(textBoxId) - .setShapeType("TEXT_BOX") - .setElementProperties(new PageElementProperties() - .setPageObjectId(slideId) - .setSize(new Size() - .setHeight(pt350) - .setWidth(pt350)) - .setTransform(new AffineTransform() - .setScaleX(1.0) - .setScaleY(1.0) - .setTranslateX(350.0) - .setTranslateY(100.0) - .setUnit("PT"))))); + // Create a new square text box, using a supplied object ID. + List requests = new ArrayList<>(); + Dimension pt350 = new Dimension().setMagnitude(350.0).setUnit("PT"); + requests.add(new Request() + .setCreateShape(new CreateShapeRequest() + .setObjectId(textBoxId) + .setShapeType("TEXT_BOX") + .setElementProperties(new PageElementProperties() + .setPageObjectId(slideId) + .setSize(new Size() + .setHeight(pt350) + .setWidth(pt350)) + .setTransform(new AffineTransform() + .setScaleX(1.0) + .setScaleY(1.0) + .setTranslateX(350.0) + .setTranslateY(100.0) + .setUnit("PT"))))); - // Insert text into the box, using the object ID given to it. - requests.add(new Request() - .setInsertText(new InsertTextRequest() - .setObjectId(textBoxId) - .setInsertionIndex(0) - .setText("New Box Text Inserted"))); - BatchUpdatePresentationResponse response = null; + // Insert text into the box, using the object ID given to it. + requests.add(new Request() + .setInsertText(new InsertTextRequest() + .setObjectId(textBoxId) + .setInsertionIndex(0) + .setText("New Box Text Inserted"))); + BatchUpdatePresentationResponse response = null; - try { - // Execute the requests. - BatchUpdatePresentationRequest body = - new BatchUpdatePresentationRequest().setRequests(requests); - response = service.presentations().batchUpdate(presentationId, body).execute(); - CreateShapeResponse createShapeResponse = response.getReplies().get(0).getCreateShape(); - System.out.println("Created textbox with ID: " + createShapeResponse.getObjectId()); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 404) { - System.out.printf("Presentation not found with id '%s'.\n", presentationId); - } else { - throw e; - } - } - return response; + try { + // Execute the requests. + BatchUpdatePresentationRequest body = + new BatchUpdatePresentationRequest().setRequests(requests); + response = service.presentations().batchUpdate(presentationId, body).execute(); + CreateShapeResponse createShapeResponse = response.getReplies().get(0).getCreateShape(); + System.out.println("Created textbox with ID: " + createShapeResponse.getObjectId()); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("Presentation not found with id '%s'.\n", presentationId); + } else { + throw e; + } } + return response; + } } // [END slides_create_textbox_with_text] \ No newline at end of file diff --git a/slides/snippets/src/main/java/ImageMerging.java b/slides/snippets/src/main/java/ImageMerging.java index 3b616aee..a45b9ad8 100644 --- a/slides/snippets/src/main/java/ImageMerging.java +++ b/slides/snippets/src/main/java/ImageMerging.java @@ -14,6 +14,7 @@ // [START slides_image_merging] + import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; @@ -37,78 +38,79 @@ /* Class to demonstrate the use of Slides Image Merging API */ public class ImageMerging { - /** - * Changes specified texts into images. - * - * @param templatePresentationId - id of the presentation. - * @param imageUrl - Url of the image. - * @param customerName - Name of the customer. - * @return merged presentation id - * @throws IOException - if credentials file not found. - */ - public static BatchUpdatePresentationResponse imageMerging(String templatePresentationId, - String imageUrl, - String customerName) throws IOException { + /** + * Changes specified texts into images. + * + * @param templatePresentationId - id of the presentation. + * @param imageUrl - Url of the image. + * @param customerName - Name of the customer. + * @return merged presentation id + * @throws IOException - if credentials file not found. + */ + public static BatchUpdatePresentationResponse imageMerging(String templatePresentationId, + String imageUrl, + String customerName) + 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(Arrays.asList(SlidesScopes.PRESENTATIONS, - SlidesScopes.DRIVE)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Arrays.asList(SlidesScopes.PRESENTATIONS, + SlidesScopes.DRIVE)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the slides API client - Slides service = new Slides.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Slides samples") - .build(); + // Create the slides API client + Slides service = new Slides.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Slides samples") + .build(); - // Create the drive API client - Drive driveService = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Slides samples") - .build(); + // Create the drive API client + Drive driveService = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Slides samples") + .build(); - // Duplicate the template presentation using the Drive API. - String copyTitle = customerName + " presentation"; - File content = new File().setName(copyTitle); - File presentationFile = - driveService.files().copy(templatePresentationId, content).execute(); - String presentationId = presentationFile.getId(); + // Duplicate the template presentation using the Drive API. + String copyTitle = customerName + " presentation"; + File content = new File().setName(copyTitle); + File presentationFile = + driveService.files().copy(templatePresentationId, content).execute(); + String presentationId = presentationFile.getId(); - // Create the image merge (replaceAllShapesWithImage) requests. - List requests = new ArrayList<>(); - requests.add(new Request() - .setReplaceAllShapesWithImage(new ReplaceAllShapesWithImageRequest() - .setImageUrl(imageUrl) - .setImageReplaceMethod("CENTER_INSIDE") - .setContainsText(new SubstringMatchCriteria() - .setText("{{company-logo}}") - .setMatchCase(true)))); + // Create the image merge (replaceAllShapesWithImage) requests. + List requests = new ArrayList<>(); + requests.add(new Request() + .setReplaceAllShapesWithImage(new ReplaceAllShapesWithImageRequest() + .setImageUrl(imageUrl) + .setImageReplaceMethod("CENTER_INSIDE") + .setContainsText(new SubstringMatchCriteria() + .setText("{{company-logo}}") + .setMatchCase(true)))); - // Execute the requests. - BatchUpdatePresentationRequest body = - new BatchUpdatePresentationRequest().setRequests(requests); - BatchUpdatePresentationResponse response = - service.presentations().batchUpdate(presentationId, body).execute(); + // Execute the requests. + BatchUpdatePresentationRequest body = + new BatchUpdatePresentationRequest().setRequests(requests); + BatchUpdatePresentationResponse response = + service.presentations().batchUpdate(presentationId, body).execute(); - int numReplacements = 0; - try { - // Count total number of replacements made. - for (Response resp : response.getReplies()) { - numReplacements += resp.getReplaceAllShapesWithImage().getOccurrencesChanged(); - } + int numReplacements = 0; + try { + // Count total number of replacements made. + for (Response resp : response.getReplies()) { + numReplacements += resp.getReplaceAllShapesWithImage().getOccurrencesChanged(); + } - // Prints the merged presentation id and count of replacements. - System.out.println("Created merged presentation with ID: " + presentationId); - System.out.println("Replaced " + numReplacements + " shapes instances with images."); - } catch (NullPointerException ne) { - System.out.println("Text not found to replace with image."); - } - return response; + // Prints the merged presentation id and count of replacements. + System.out.println("Created merged presentation with ID: " + presentationId); + System.out.println("Replaced " + numReplacements + " shapes instances with images."); + } catch (NullPointerException ne) { + System.out.println("Text not found to replace with image."); } + return response; + } } // [END slides_image_merging] \ No newline at end of file diff --git a/slides/snippets/src/main/java/RefreshSheetsChart.java b/slides/snippets/src/main/java/RefreshSheetsChart.java index 30230a5a..7ff9df97 100644 --- a/slides/snippets/src/main/java/RefreshSheetsChart.java +++ b/slides/snippets/src/main/java/RefreshSheetsChart.java @@ -14,6 +14,7 @@ // [START slides_refresh_sheets_chart] + import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; @@ -35,58 +36,57 @@ /* Class to demonstrate the use of Slides Refresh Chart API */ public class RefreshSheetsChart { - /** - * Refresh the sheets charts. - * - * @param presentationId - id of the presentation. - * @param presentationChartId - id of the presentation chart. - * @return presentation chart id - * @throws IOException - if credentials file not found. - */ - public static BatchUpdatePresentationResponse refreshSheetsChart( - String presentationId, String presentationChartId) throws IOException { + /** + * Refresh the sheets charts. + * + * @param presentationId - id of the presentation. + * @param presentationChartId - id of the presentation chart. + * @return presentation chart id + * @throws IOException - if credentials file not found. + */ + public static BatchUpdatePresentationResponse refreshSheetsChart( + String presentationId, String presentationChartId) 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(SlidesScopes.PRESENTATIONS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(SlidesScopes.PRESENTATIONS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the slides API client - Slides service = new Slides.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Slides samples") - .build(); + // Create the slides API client + Slides service = new Slides.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Slides samples") + .build(); - List requests = new ArrayList<>(); + List requests = new ArrayList<>(); - // Refresh an existing linked Sheets chart embedded a presentation. - requests.add(new Request() - .setRefreshSheetsChart(new RefreshSheetsChartRequest() - .setObjectId(presentationChartId))); + // Refresh an existing linked Sheets chart embedded a presentation. + requests.add(new Request() + .setRefreshSheetsChart(new RefreshSheetsChartRequest() + .setObjectId(presentationChartId))); - BatchUpdatePresentationResponse response = null; - try { - // Execute the request. - BatchUpdatePresentationRequest body = - new BatchUpdatePresentationRequest().setRequests(requests); - response = service.presentations().batchUpdate(presentationId, body).execute(); - System.out.println("Refreshed a linked Sheets chart with ID " + presentationChartId); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 400) { - System.out.printf("Presentation chart not found with id '%s'.\n", presentationChartId); - } else if (error.getCode() == 404) { - System.out.printf("Presentation not found with id '%s'.\n", presentationId); - } - else { - throw e; - } - } - return response; + BatchUpdatePresentationResponse response = null; + try { + // Execute the request. + BatchUpdatePresentationRequest body = + new BatchUpdatePresentationRequest().setRequests(requests); + response = service.presentations().batchUpdate(presentationId, body).execute(); + System.out.println("Refreshed a linked Sheets chart with ID " + presentationChartId); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 400) { + System.out.printf("Presentation chart not found with id '%s'.\n", presentationChartId); + } else if (error.getCode() == 404) { + System.out.printf("Presentation not found with id '%s'.\n", presentationId); + } else { + throw e; + } } + return response; + } } // [END slides_refresh_sheets_chart] \ No newline at end of file diff --git a/slides/snippets/src/main/java/SimpleTextReplace.java b/slides/snippets/src/main/java/SimpleTextReplace.java index 060215c1..0e23a303 100644 --- a/slides/snippets/src/main/java/SimpleTextReplace.java +++ b/slides/snippets/src/main/java/SimpleTextReplace.java @@ -14,6 +14,7 @@ // [START slides_simple_text_replace] + import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; @@ -37,65 +38,64 @@ /* Class to demonstrate the use of Slides Replace Text API */ public class SimpleTextReplace { - /** - * Remove existing text in the shape, then insert new text. - * - * @param presentationId - id of the presentation. - * @param shapeId - id of the shape. - * @param replacementText - New replacement text. - * @return response - * @throws IOException - if credentials file not found. - */ - public static BatchUpdatePresentationResponse simpleTextReplace( - String presentationId, String shapeId, String replacementText) throws IOException { + /** + * Remove existing text in the shape, then insert new text. + * + * @param presentationId - id of the presentation. + * @param shapeId - id of the shape. + * @param replacementText - New replacement text. + * @return response + * @throws IOException - if credentials file not found. + */ + public static BatchUpdatePresentationResponse simpleTextReplace( + String presentationId, String shapeId, String replacementText) 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(SlidesScopes.PRESENTATIONS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(SlidesScopes.PRESENTATIONS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the slides API client - Slides service = new Slides.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Slides samples") - .build(); + // Create the slides API client + Slides service = new Slides.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Slides samples") + .build(); - // Remove existing text in the shape, then insert the new text. - List requests = new ArrayList<>(); - requests.add(new Request() - .setDeleteText(new DeleteTextRequest() - .setObjectId(shapeId) - .setTextRange(new Range() - .setType("ALL")))); - requests.add(new Request() - .setInsertText(new InsertTextRequest() - .setObjectId(shapeId) - .setInsertionIndex(0) - .setText(replacementText))); + // Remove existing text in the shape, then insert the new text. + List requests = new ArrayList<>(); + requests.add(new Request() + .setDeleteText(new DeleteTextRequest() + .setObjectId(shapeId) + .setTextRange(new Range() + .setType("ALL")))); + requests.add(new Request() + .setInsertText(new InsertTextRequest() + .setObjectId(shapeId) + .setInsertionIndex(0) + .setText(replacementText))); - BatchUpdatePresentationResponse response = null; - try { - // Execute the requests. - BatchUpdatePresentationRequest body = - new BatchUpdatePresentationRequest().setRequests(requests); - response = service.presentations().batchUpdate(presentationId, body).execute(); - System.out.println("Replaced text in shape with ID: " + shapeId); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 400) { - System.out.printf("Shape not found with id '%s'.\n", shapeId); - } else if (error.getCode() == 404) { - System.out.printf("Presentation not found with id '%s'.\n", presentationId); - } - else { - throw e; - } - } - return response; + BatchUpdatePresentationResponse response = null; + try { + // Execute the requests. + BatchUpdatePresentationRequest body = + new BatchUpdatePresentationRequest().setRequests(requests); + response = service.presentations().batchUpdate(presentationId, body).execute(); + System.out.println("Replaced text in shape with ID: " + shapeId); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 400) { + System.out.printf("Shape not found with id '%s'.\n", shapeId); + } else if (error.getCode() == 404) { + System.out.printf("Presentation not found with id '%s'.\n", presentationId); + } else { + throw e; + } } + return response; + } } // [END slides_simple_text_replace] \ No newline at end of file diff --git a/slides/snippets/src/main/java/TextMerging.java b/slides/snippets/src/main/java/TextMerging.java index c58b8658..67f96955 100644 --- a/slides/snippets/src/main/java/TextMerging.java +++ b/slides/snippets/src/main/java/TextMerging.java @@ -14,6 +14,7 @@ // [START slides_text_merging] + import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; @@ -41,115 +42,116 @@ /* Class to demonstrate the use of Slides Text Merging API */ public class TextMerging { - /** - * Changes specified texts with data from spreadsheet. - * - * @param templatePresentationId - id of the presentation. - * @param dataSpreadsheetId - id of the spreadsheet containing data. - * @return merged presentation id - * @throws IOException - if credentials file not found. - */ - public static List textMerging( - String templatePresentationId, String dataSpreadsheetId) throws IOException { + /** + * Changes specified texts with data from spreadsheet. + * + * @param templatePresentationId - id of the presentation. + * @param dataSpreadsheetId - id of the spreadsheet containing data. + * @return merged presentation id + * @throws IOException - if credentials file not found. + */ + public static List textMerging( + String templatePresentationId, String dataSpreadsheetId) 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(Arrays.asList(SlidesScopes.PRESENTATIONS, - SlidesScopes.DRIVE,SlidesScopes.SPREADSHEETS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Arrays.asList(SlidesScopes.PRESENTATIONS, + SlidesScopes.DRIVE, SlidesScopes.SPREADSHEETS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the slides API client - Slides service = new Slides.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Slides samples") - .build(); + // Create the slides API client + Slides service = new Slides.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Slides samples") + .build(); - // Create the drive API client - Drive driveService = new Drive.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Slides samples") - .build(); + // Create the drive API client + Drive driveService = new Drive.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Slides samples") + .build(); - // Create the sheets API client - Sheets sheetsService = new Sheets.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Slides samples") - .build(); + // Create the sheets API client + Sheets sheetsService = new Sheets.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Slides samples") + .build(); - List responses = new ArrayList<>(5); - // Use the Sheets API to load data, one record per row. - String dataRangeNotation = "Customers!A2:M6"; - ValueRange sheetsResponse = sheetsService.spreadsheets().values() - .get(dataSpreadsheetId, dataRangeNotation).execute(); - List> values = sheetsResponse.getValues(); + List responses = new ArrayList<>(5); + // Use the Sheets API to load data, one record per row. + String dataRangeNotation = "Customers!A2:M6"; + ValueRange sheetsResponse = sheetsService.spreadsheets().values() + .get(dataSpreadsheetId, dataRangeNotation).execute(); + List> values = sheetsResponse.getValues(); - try { - // For each record, create a new merged presentation. - for (List row : values) { - String customerName = row.get(2).toString(); // name in column 3 - String caseDescription = row.get(5).toString(); // case description in column 6 - String totalPortfolio = row.get(11).toString(); // total portfolio in column 12 + try { + // For each record, create a new merged presentation. + for (List row : values) { + String customerName = row.get(2).toString(); // name in column 3 + String caseDescription = row.get(5).toString(); // case description in column 6 + String totalPortfolio = row.get(11).toString(); // total portfolio in column 12 - // Duplicate the template presentation using the Drive API. - String copyTitle = customerName + " presentation"; - File content = new File().setName(copyTitle); - File presentationFile = - driveService.files().copy(templatePresentationId, content).execute(); - String presentationId = presentationFile.getId(); + // Duplicate the template presentation using the Drive API. + String copyTitle = customerName + " presentation"; + File content = new File().setName(copyTitle); + File presentationFile = + driveService.files().copy(templatePresentationId, content).execute(); + String presentationId = presentationFile.getId(); - // Create the text merge (replaceAllText) requests for this presentation. - List requests = new ArrayList<>(); - requests.add(new Request() - .setReplaceAllText(new ReplaceAllTextRequest() - .setContainsText(new SubstringMatchCriteria() - .setText("{{customer-name}}") - .setMatchCase(true)) - .setReplaceText(customerName))); - requests.add(new Request() - .setReplaceAllText(new ReplaceAllTextRequest() - .setContainsText(new SubstringMatchCriteria() - .setText("{{case-description}}") - .setMatchCase(true)) - .setReplaceText(caseDescription))); - requests.add(new Request() - .setReplaceAllText(new ReplaceAllTextRequest() - .setContainsText(new SubstringMatchCriteria() - .setText("{{total-portfolio}}") - .setMatchCase(true)) - .setReplaceText(totalPortfolio))); + // Create the text merge (replaceAllText) requests for this presentation. + List requests = new ArrayList<>(); + requests.add(new Request() + .setReplaceAllText(new ReplaceAllTextRequest() + .setContainsText(new SubstringMatchCriteria() + .setText("{{customer-name}}") + .setMatchCase(true)) + .setReplaceText(customerName))); + requests.add(new Request() + .setReplaceAllText(new ReplaceAllTextRequest() + .setContainsText(new SubstringMatchCriteria() + .setText("{{case-description}}") + .setMatchCase(true)) + .setReplaceText(caseDescription))); + requests.add(new Request() + .setReplaceAllText(new ReplaceAllTextRequest() + .setContainsText(new SubstringMatchCriteria() + .setText("{{total-portfolio}}") + .setMatchCase(true)) + .setReplaceText(totalPortfolio))); - // Execute the requests for this presentation. - BatchUpdatePresentationRequest body = - new BatchUpdatePresentationRequest().setRequests(requests); - BatchUpdatePresentationResponse response = service.presentations().batchUpdate(presentationId, body).execute(); + // Execute the requests for this presentation. + BatchUpdatePresentationRequest body = + new BatchUpdatePresentationRequest().setRequests(requests); + BatchUpdatePresentationResponse response = + service.presentations().batchUpdate(presentationId, body).execute(); - // Count total number of replacements made. - int numReplacements = 0; - for (Response resp : response.getReplies()) { - numReplacements += resp.getReplaceAllText().getOccurrencesChanged(); - } - // Prints the merged presentation id and count of replacements. - System.out.println("Created merged presentation for " + - customerName + " with ID: " + presentationId); - System.out.println("Replaced " + numReplacements + " text instances."); - } - }catch (NullPointerException ne) { - System.out.println("Text not found to replace with image."); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 404) { - System.out.printf("Presentation not found with id '%s'.\n", templatePresentationId); - } else { - throw e; - } + // Count total number of replacements made. + int numReplacements = 0; + for (Response resp : response.getReplies()) { + numReplacements += resp.getReplaceAllText().getOccurrencesChanged(); } - return responses; + // Prints the merged presentation id and count of replacements. + System.out.println("Created merged presentation for " + + customerName + " with ID: " + presentationId); + System.out.println("Replaced " + numReplacements + " text instances."); + } + } catch (NullPointerException ne) { + System.out.println("Text not found to replace with image."); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 404) { + System.out.printf("Presentation not found with id '%s'.\n", templatePresentationId); + } else { + throw e; + } } + return responses; + } } // [END slides_text_merging] \ No newline at end of file diff --git a/slides/snippets/src/main/java/TextStyleUpdate.java b/slides/snippets/src/main/java/TextStyleUpdate.java index 6b59a81c..86b694d0 100644 --- a/slides/snippets/src/main/java/TextStyleUpdate.java +++ b/slides/snippets/src/main/java/TextStyleUpdate.java @@ -14,6 +14,7 @@ // [START slides_text_style_update] + import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; @@ -42,97 +43,97 @@ /* Class to demonstrate the use of Slide Text Structure and Styling API */ public class TextStyleUpdate { - /** - * Styles text in the shape. - * - * @param presentationId - id of the presentation. - * @param shapeId - id of the shape. - * @return shape id - * @throws IOException - if credentials file not found. - */ - public static BatchUpdatePresentationResponse textStyleUpdate(String presentationId, String shapeId) - throws IOException { + /** + * Styles text in the shape. + * + * @param presentationId - id of the presentation. + * @param shapeId - id of the shape. + * @return shape id + * @throws IOException - if credentials file not found. + */ + public static BatchUpdatePresentationResponse textStyleUpdate(String presentationId, + String shapeId) + 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(SlidesScopes.PRESENTATIONS)); - HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( - credentials); + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(Collections.singleton(SlidesScopes.PRESENTATIONS)); + HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( + credentials); - // Create the slides API client - Slides service = new Slides.Builder(new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - requestInitializer) - .setApplicationName("Slides samples") - .build(); + // Create the slides API client + Slides service = new Slides.Builder(new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + requestInitializer) + .setApplicationName("Slides samples") + .build(); - // Update the text style so that the first 5 characters are bolded - // and italicized, and the next 5 are displayed in blue 14 pt Times - // New Roman font, and the next five are hyperlinked. - List requests = new ArrayList<>(); - requests.add(new Request() - .setUpdateTextStyle(new UpdateTextStyleRequest() - .setObjectId(shapeId) - .setTextRange(new Range() - .setType("FIXED_RANGE") - .setStartIndex(0) - .setEndIndex(5)) - .setStyle(new TextStyle() - .setBold(true) - .setItalic(true)) - .setFields("bold,italic"))); - requests.add(new Request() - .setUpdateTextStyle(new UpdateTextStyleRequest() - .setObjectId(shapeId) - .setTextRange(new Range() - .setType("FIXED_RANGE") - .setStartIndex(5) - .setEndIndex(10)) - .setStyle(new TextStyle() - .setFontFamily("Times New Roman") - .setFontSize(new Dimension() - .setMagnitude(14.0) - .setUnit("PT")) - .setForegroundColor(new OptionalColor() - .setOpaqueColor(new OpaqueColor() - .setRgbColor(new RgbColor() - .setBlue(1.0F) - .setGreen(0.0F) - .setRed(0.0F))))) - .setFields("foregroundColor,fontFamily,fontSize"))); - requests.add(new Request() - .setUpdateTextStyle(new UpdateTextStyleRequest() - .setObjectId(shapeId) - .setTextRange(new Range() - .setType("FIXED_RANGE") - .setStartIndex(10) - .setEndIndex(15)) - .setStyle(new TextStyle() - .setLink(new Link() - .setUrl("www.example.com"))) - .setFields("link"))); + // Update the text style so that the first 5 characters are bolded + // and italicized, and the next 5 are displayed in blue 14 pt Times + // New Roman font, and the next five are hyperlinked. + List requests = new ArrayList<>(); + requests.add(new Request() + .setUpdateTextStyle(new UpdateTextStyleRequest() + .setObjectId(shapeId) + .setTextRange(new Range() + .setType("FIXED_RANGE") + .setStartIndex(0) + .setEndIndex(5)) + .setStyle(new TextStyle() + .setBold(true) + .setItalic(true)) + .setFields("bold,italic"))); + requests.add(new Request() + .setUpdateTextStyle(new UpdateTextStyleRequest() + .setObjectId(shapeId) + .setTextRange(new Range() + .setType("FIXED_RANGE") + .setStartIndex(5) + .setEndIndex(10)) + .setStyle(new TextStyle() + .setFontFamily("Times New Roman") + .setFontSize(new Dimension() + .setMagnitude(14.0) + .setUnit("PT")) + .setForegroundColor(new OptionalColor() + .setOpaqueColor(new OpaqueColor() + .setRgbColor(new RgbColor() + .setBlue(1.0F) + .setGreen(0.0F) + .setRed(0.0F))))) + .setFields("foregroundColor,fontFamily,fontSize"))); + requests.add(new Request() + .setUpdateTextStyle(new UpdateTextStyleRequest() + .setObjectId(shapeId) + .setTextRange(new Range() + .setType("FIXED_RANGE") + .setStartIndex(10) + .setEndIndex(15)) + .setStyle(new TextStyle() + .setLink(new Link() + .setUrl("www.example.com"))) + .setFields("link"))); - BatchUpdatePresentationResponse response = null; - try { - // Execute the requests. - BatchUpdatePresentationRequest body = - new BatchUpdatePresentationRequest().setRequests(requests); - response = service.presentations().batchUpdate(presentationId, body).execute(); - System.out.println("Updated text style for shape with ID: " + shapeId); - } catch (GoogleJsonResponseException e) { - // TODO(developer) - handle error appropriately - GoogleJsonError error = e.getDetails(); - if (error.getCode() == 400) { - System.out.printf("Shape not found with id '%s'.\n", shapeId); - } else if (error.getCode() == 404) { - System.out.printf("Presentation not found with id '%s'.\n", presentationId); - } - else { - throw e; - } - } - return response; + BatchUpdatePresentationResponse response = null; + try { + // Execute the requests. + BatchUpdatePresentationRequest body = + new BatchUpdatePresentationRequest().setRequests(requests); + response = service.presentations().batchUpdate(presentationId, body).execute(); + System.out.println("Updated text style for shape with ID: " + shapeId); + } catch (GoogleJsonResponseException e) { + // TODO(developer) - handle error appropriately + GoogleJsonError error = e.getDetails(); + if (error.getCode() == 400) { + System.out.printf("Shape not found with id '%s'.\n", shapeId); + } else if (error.getCode() == 404) { + System.out.printf("Presentation not found with id '%s'.\n", presentationId); + } else { + throw e; + } } + return response; + } } // [END slides_text_style_update] \ No newline at end of file diff --git a/slides/snippets/src/test/java/BaseTest.java b/slides/snippets/src/test/java/BaseTest.java index f28c5117..d6f52d6b 100644 --- a/slides/snippets/src/test/java/BaseTest.java +++ b/slides/snippets/src/test/java/BaseTest.java @@ -32,145 +32,145 @@ import org.junit.After; public class BaseTest { - protected Slides service; - protected Drive driveService; - protected Sheets sheetsService; + protected Slides service; + protected Drive driveService; + protected Sheets sheetsService; - public GoogleCredentials getCredential() throws IOException { + public GoogleCredentials getCredential() 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(SlidesScopes.PRESENTATIONS, SlidesScopes.DRIVE); - return credentials; - } - - public Slides buildService(GoogleCredentials credential) { - return new Slides.Builder( - new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - new HttpCredentialsAdapter(credential)) - .setApplicationName("Slides API Snippets") - .build(); - } - - public Drive buildDriveService(GoogleCredentials credential) { - return new Drive.Builder( - new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - new HttpCredentialsAdapter(credential)) - .setApplicationName("Slides API Snippets") - .build(); - } - - public Sheets buildSheetsService(GoogleCredentials credential) { - return new Sheets.Builder( - new NetHttpTransport(), - GsonFactory.getDefaultInstance(), - new HttpCredentialsAdapter(credential)) - .setApplicationName("Slides API Snippets") - .build(); - } - - @Before - public void setup() throws IOException { - GoogleCredentials credential = getCredential(); - this.service = buildService(credential); - this.driveService = buildDriveService(credential); - this.sheetsService = buildSheetsService(credential); - } - - protected void deleteFileOnCleanup(String id) throws IOException { - this.driveService.files().delete(id).execute(); - } - - protected String createTestPresentation() throws IOException { - Presentation presentation = new Presentation() - .setTitle("Test Presentation"); - presentation = service.presentations().create(presentation) - .setFields("presentationId") - .execute(); - return presentation.getPresentationId(); - } - - protected String createTestSlide(String presentationId) throws IOException { - List requests = new ArrayList<>(); - requests.add(new Request() - .setCreateSlide(new CreateSlideRequest() - .setObjectId("TestSlide") - .setInsertionIndex(0) - .setSlideLayoutReference(new LayoutReference() - .setPredefinedLayout("BLANK")))); - BatchUpdatePresentationRequest body = - new BatchUpdatePresentationRequest().setRequests(requests); - BatchUpdatePresentationResponse response = - service.presentations().batchUpdate(presentationId, body).execute(); - return response.getReplies().get(0).getCreateSlide().getObjectId(); - } - - protected String createTestTextBox(String presentationId, String pageId) throws IOException { - String textBoxId = "MyTextBox_01"; - Dimension pt350 = new Dimension().setMagnitude(350.0).setUnit("PT"); - List requests = new ArrayList<>(); - requests.add(new Request() - .setCreateShape(new CreateShapeRequest() - .setObjectId(textBoxId) - .setShapeType("TEXT_BOX") - .setElementProperties(new PageElementProperties() - .setPageObjectId(pageId) - .setSize(new Size() - .setHeight(pt350) - .setWidth(pt350)) - .setTransform(new AffineTransform() - .setScaleX(1.0) - .setScaleY(1.0) - .setTranslateX(350.0) - .setTranslateY(100.0) - .setUnit("PT"))))); - - requests.add(new Request() - .setInsertText(new InsertTextRequest() - .setObjectId(textBoxId) - .setInsertionIndex(0) - .setText("New Box Text Inserted"))); - - BatchUpdatePresentationRequest body = - new BatchUpdatePresentationRequest().setRequests(requests); - BatchUpdatePresentationResponse response = - service.presentations().batchUpdate(presentationId, body).execute(); - return response.getReplies().get(0).getCreateShape().getObjectId(); - } - - protected String createTestSheetsChart(String presentationId, - String pageId, - String spreadsheetId, - Integer sheetChartId) throws IOException { - String presentationChartId = "MyChartId_01"; - Dimension emu4M = new Dimension().setMagnitude(4000000.0).setUnit("EMU"); - List requests = new ArrayList<>(); - requests.add(new Request() - .setCreateSheetsChart(new CreateSheetsChartRequest() - .setObjectId(presentationChartId) - .setSpreadsheetId(spreadsheetId) - .setChartId(sheetChartId) - .setLinkingMode("LINKED") - .setElementProperties(new PageElementProperties() - .setPageObjectId(pageId) - .setSize(new Size() - .setHeight(emu4M) - .setWidth(emu4M)) - .setTransform(new AffineTransform() - .setScaleX(1.0) - .setScaleY(1.0) - .setTranslateX(100000.0) - .setTranslateY(100000.0) - .setUnit("EMU"))))); - - BatchUpdatePresentationRequest body = - new BatchUpdatePresentationRequest().setRequests(requests); - BatchUpdatePresentationResponse response = - service.presentations().batchUpdate(presentationId, body).execute(); - return response.getReplies().get(0).getCreateSheetsChart().getObjectId(); - } + GoogleCredentials credentials = GoogleCredentials.getApplicationDefault() + .createScoped(SlidesScopes.PRESENTATIONS, SlidesScopes.DRIVE); + return credentials; + } + + public Slides buildService(GoogleCredentials credential) { + return new Slides.Builder( + new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + new HttpCredentialsAdapter(credential)) + .setApplicationName("Slides API Snippets") + .build(); + } + + public Drive buildDriveService(GoogleCredentials credential) { + return new Drive.Builder( + new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + new HttpCredentialsAdapter(credential)) + .setApplicationName("Slides API Snippets") + .build(); + } + + public Sheets buildSheetsService(GoogleCredentials credential) { + return new Sheets.Builder( + new NetHttpTransport(), + GsonFactory.getDefaultInstance(), + new HttpCredentialsAdapter(credential)) + .setApplicationName("Slides API Snippets") + .build(); + } + + @Before + public void setup() throws IOException { + GoogleCredentials credential = getCredential(); + this.service = buildService(credential); + this.driveService = buildDriveService(credential); + this.sheetsService = buildSheetsService(credential); + } + + protected void deleteFileOnCleanup(String id) throws IOException { + this.driveService.files().delete(id).execute(); + } + + protected String createTestPresentation() throws IOException { + Presentation presentation = new Presentation() + .setTitle("Test Presentation"); + presentation = service.presentations().create(presentation) + .setFields("presentationId") + .execute(); + return presentation.getPresentationId(); + } + + protected String createTestSlide(String presentationId) throws IOException { + List requests = new ArrayList<>(); + requests.add(new Request() + .setCreateSlide(new CreateSlideRequest() + .setObjectId("TestSlide") + .setInsertionIndex(0) + .setSlideLayoutReference(new LayoutReference() + .setPredefinedLayout("BLANK")))); + BatchUpdatePresentationRequest body = + new BatchUpdatePresentationRequest().setRequests(requests); + BatchUpdatePresentationResponse response = + service.presentations().batchUpdate(presentationId, body).execute(); + return response.getReplies().get(0).getCreateSlide().getObjectId(); + } + + protected String createTestTextBox(String presentationId, String pageId) throws IOException { + String textBoxId = "MyTextBox_01"; + Dimension pt350 = new Dimension().setMagnitude(350.0).setUnit("PT"); + List requests = new ArrayList<>(); + requests.add(new Request() + .setCreateShape(new CreateShapeRequest() + .setObjectId(textBoxId) + .setShapeType("TEXT_BOX") + .setElementProperties(new PageElementProperties() + .setPageObjectId(pageId) + .setSize(new Size() + .setHeight(pt350) + .setWidth(pt350)) + .setTransform(new AffineTransform() + .setScaleX(1.0) + .setScaleY(1.0) + .setTranslateX(350.0) + .setTranslateY(100.0) + .setUnit("PT"))))); + + requests.add(new Request() + .setInsertText(new InsertTextRequest() + .setObjectId(textBoxId) + .setInsertionIndex(0) + .setText("New Box Text Inserted"))); + + BatchUpdatePresentationRequest body = + new BatchUpdatePresentationRequest().setRequests(requests); + BatchUpdatePresentationResponse response = + service.presentations().batchUpdate(presentationId, body).execute(); + return response.getReplies().get(0).getCreateShape().getObjectId(); + } + + protected String createTestSheetsChart(String presentationId, + String pageId, + String spreadsheetId, + Integer sheetChartId) throws IOException { + String presentationChartId = "MyChartId_01"; + Dimension emu4M = new Dimension().setMagnitude(4000000.0).setUnit("EMU"); + List requests = new ArrayList<>(); + requests.add(new Request() + .setCreateSheetsChart(new CreateSheetsChartRequest() + .setObjectId(presentationChartId) + .setSpreadsheetId(spreadsheetId) + .setChartId(sheetChartId) + .setLinkingMode("LINKED") + .setElementProperties(new PageElementProperties() + .setPageObjectId(pageId) + .setSize(new Size() + .setHeight(emu4M) + .setWidth(emu4M)) + .setTransform(new AffineTransform() + .setScaleX(1.0) + .setScaleY(1.0) + .setTranslateX(100000.0) + .setTranslateY(100000.0) + .setUnit("EMU"))))); + + BatchUpdatePresentationRequest body = + new BatchUpdatePresentationRequest().setRequests(requests); + BatchUpdatePresentationResponse response = + service.presentations().batchUpdate(presentationId, body).execute(); + return response.getReplies().get(0).getCreateSheetsChart().getObjectId(); + } } diff --git a/slides/snippets/src/test/java/TestCopyPresentation.java b/slides/snippets/src/test/java/TestCopyPresentation.java index a4772d09..ddbf8d3e 100644 --- a/slides/snippets/src/test/java/TestCopyPresentation.java +++ b/slides/snippets/src/test/java/TestCopyPresentation.java @@ -19,13 +19,13 @@ import static org.junit.Assert.assertNotNull; // Unit testcase for copy presentation snippet -public class TestCopyPresentation extends BaseTest{ +public class TestCopyPresentation extends BaseTest { - @Test - public void testCopyPresentation() throws IOException { - String presentationId = createTestPresentation(); - String copyId = CopyPresentation.copyPresentation(presentationId, "My Duplicate Presentation"); - assertNotNull(copyId); - deleteFileOnCleanup(copyId); - } + @Test + public void testCopyPresentation() throws IOException { + String presentationId = createTestPresentation(); + String copyId = CopyPresentation.copyPresentation(presentationId, "My Duplicate Presentation"); + assertNotNull(copyId); + deleteFileOnCleanup(copyId); + } } diff --git a/slides/snippets/src/test/java/TestCreateBulletedText.java b/slides/snippets/src/test/java/TestCreateBulletedText.java index c6c00cf9..8d707000 100644 --- a/slides/snippets/src/test/java/TestCreateBulletedText.java +++ b/slides/snippets/src/test/java/TestCreateBulletedText.java @@ -20,16 +20,16 @@ import static org.junit.Assert.assertEquals; // Unit testcase for createBulletedText snippet -public class TestCreateBulletedText extends BaseTest{ +public class TestCreateBulletedText extends BaseTest { - @Test - public void testCreateBulletText() throws IOException { - String presentationId = createTestPresentation(); - String pageId = createTestSlide(presentationId); - String boxId = createTestTextBox(presentationId, pageId); - BatchUpdatePresentationResponse response = - CreateBulletedText.createBulletedText(presentationId, boxId); - assertEquals(1, response.getReplies().size()); - deleteFileOnCleanup(presentationId); - } + @Test + public void testCreateBulletText() throws IOException { + String presentationId = createTestPresentation(); + String pageId = createTestSlide(presentationId); + String boxId = createTestTextBox(presentationId, pageId); + BatchUpdatePresentationResponse response = + CreateBulletedText.createBulletedText(presentationId, boxId); + assertEquals(1, response.getReplies().size()); + deleteFileOnCleanup(presentationId); + } } diff --git a/slides/snippets/src/test/java/TestCreateImage.java b/slides/snippets/src/test/java/TestCreateImage.java index f2493670..d4d51840 100644 --- a/slides/snippets/src/test/java/TestCreateImage.java +++ b/slides/snippets/src/test/java/TestCreateImage.java @@ -23,17 +23,17 @@ // Unit testcase for createImage snippet public class TestCreateImage extends BaseTest { - private final String IMAGE_URL = - "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"; + private final String IMAGE_URL = + "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"; - @Test - public void testCreateImage() throws IOException { - String presentationId = createTestPresentation(); - String slideId = createTestSlide(presentationId); - BatchUpdatePresentationResponse response = CreateImage.createImage( - presentationId, slideId, IMAGE_URL); - assertEquals(1, response.getReplies().size()); - String imageId = response.getReplies().get(0).getCreateImage().getObjectId(); - assertNotNull(imageId); - } + @Test + public void testCreateImage() throws IOException { + String presentationId = createTestPresentation(); + String slideId = createTestSlide(presentationId); + BatchUpdatePresentationResponse response = CreateImage.createImage( + presentationId, slideId, IMAGE_URL); + assertEquals(1, response.getReplies().size()); + String imageId = response.getReplies().get(0).getCreateImage().getObjectId(); + assertNotNull(imageId); + } } diff --git a/slides/snippets/src/test/java/TestCreatePresentation.java b/slides/snippets/src/test/java/TestCreatePresentation.java index 8a44c76c..06bdd053 100644 --- a/slides/snippets/src/test/java/TestCreatePresentation.java +++ b/slides/snippets/src/test/java/TestCreatePresentation.java @@ -19,12 +19,12 @@ import static org.junit.Assert.assertNotNull; // Unit testcase for createPresentation snippet -public class TestCreatePresentation extends BaseTest{ +public class TestCreatePresentation extends BaseTest { - @Test - public void testCreatePresentation() throws IOException { - String presentationId = CreatePresentation.createPresentation("Title"); - assertNotNull(presentationId); - deleteFileOnCleanup(presentationId); - } + @Test + public void testCreatePresentation() throws IOException { + String presentationId = CreatePresentation.createPresentation("Title"); + assertNotNull(presentationId); + deleteFileOnCleanup(presentationId); + } } diff --git a/slides/snippets/src/test/java/TestCreateSheetsChart.java b/slides/snippets/src/test/java/TestCreateSheetsChart.java index c4905b83..7e7fa2c8 100644 --- a/slides/snippets/src/test/java/TestCreateSheetsChart.java +++ b/slides/snippets/src/test/java/TestCreateSheetsChart.java @@ -21,20 +21,21 @@ import static org.junit.Assert.assertNotNull; // Unit testcase for createSheetsChart snippet -public class TestCreateSheetsChart extends BaseTest{ - // TODO(developer) - change the IDs before executing - private final String DATA_SPREADSHEET_ID = "1ZCGbdHSvLnp776gDGSGtkEBxWQ-FDMuWEF4EOSmeDDw"; - private final Integer CHART_ID = 1107320627; - @Test - public void testCreateSheetsChart() throws IOException { - String presentationId = this.createTestPresentation(); - String pageId = this.createTestSlide(presentationId); - BatchUpdatePresentationResponse response = - CreateSheetsChart.createSheetsChart( - presentationId, pageId, DATA_SPREADSHEET_ID, CHART_ID); - assertEquals(1, response.getReplies().size()); - String chartId = response.getReplies().get(0).getCreateSheetsChart().getObjectId(); - assertNotNull(chartId); - deleteFileOnCleanup(presentationId); - } +public class TestCreateSheetsChart extends BaseTest { + // TODO(developer) - change the IDs before executing + private final String DATA_SPREADSHEET_ID = "1ZCGbdHSvLnp776gDGSGtkEBxWQ-FDMuWEF4EOSmeDDw"; + private final Integer CHART_ID = 1107320627; + + @Test + public void testCreateSheetsChart() throws IOException { + String presentationId = this.createTestPresentation(); + String pageId = this.createTestSlide(presentationId); + BatchUpdatePresentationResponse response = + CreateSheetsChart.createSheetsChart( + presentationId, pageId, DATA_SPREADSHEET_ID, CHART_ID); + assertEquals(1, response.getReplies().size()); + String chartId = response.getReplies().get(0).getCreateSheetsChart().getObjectId(); + assertNotNull(chartId); + deleteFileOnCleanup(presentationId); + } } diff --git a/slides/snippets/src/test/java/TestCreateSlide.java b/slides/snippets/src/test/java/TestCreateSlide.java index 84997780..506baa9d 100644 --- a/slides/snippets/src/test/java/TestCreateSlide.java +++ b/slides/snippets/src/test/java/TestCreateSlide.java @@ -21,17 +21,17 @@ import static org.junit.Assert.assertNotNull; // Unit testcase for createSlide snippet -public class TestCreateSlide extends BaseTest{ +public class TestCreateSlide extends BaseTest { - @Test - public void testCreateSlide() throws IOException { - String presentationId = createTestPresentation(); - BatchUpdatePresentationResponse response = - CreateSlide.createSlide(presentationId); - assertNotNull(response); - assertEquals(1, response.getReplies().size()); - String pageId = response.getReplies().get(0).getCreateSlide().getObjectId(); - assertNotNull(pageId); - deleteFileOnCleanup(presentationId); - } + @Test + public void testCreateSlide() throws IOException { + String presentationId = createTestPresentation(); + BatchUpdatePresentationResponse response = + CreateSlide.createSlide(presentationId); + assertNotNull(response); + assertEquals(1, response.getReplies().size()); + String pageId = response.getReplies().get(0).getCreateSlide().getObjectId(); + assertNotNull(pageId); + deleteFileOnCleanup(presentationId); + } } diff --git a/slides/snippets/src/test/java/TestCreateTextboxWithText.java b/slides/snippets/src/test/java/TestCreateTextboxWithText.java index 5fbf15bc..60dacb02 100644 --- a/slides/snippets/src/test/java/TestCreateTextboxWithText.java +++ b/slides/snippets/src/test/java/TestCreateTextboxWithText.java @@ -21,18 +21,18 @@ import static org.junit.Assert.assertNotNull; // Unit testcase for createTextboxWithText snippet -public class TestCreateTextboxWithText extends BaseTest{ +public class TestCreateTextboxWithText extends BaseTest { - @Test - public void testCreateTextBox() throws IOException { - String presentationId = createTestPresentation(); - String pageId = createTestSlide(presentationId); - BatchUpdatePresentationResponse response = - CreateTextboxWithText.createTextBoxWithText(presentationId, - pageId, "MyTextBox"); - assertEquals(2, response.getReplies().size()); - String boxId = response.getReplies().get(0).getCreateShape().getObjectId(); - assertNotNull(boxId); - deleteFileOnCleanup(presentationId); - } + @Test + public void testCreateTextBox() throws IOException { + String presentationId = createTestPresentation(); + String pageId = createTestSlide(presentationId); + BatchUpdatePresentationResponse response = + CreateTextboxWithText.createTextBoxWithText(presentationId, + pageId, "MyTextBox"); + assertEquals(2, response.getReplies().size()); + String boxId = response.getReplies().get(0).getCreateShape().getObjectId(); + assertNotNull(boxId); + deleteFileOnCleanup(presentationId); + } } diff --git a/slides/snippets/src/test/java/TestImageMerging.java b/slides/snippets/src/test/java/TestImageMerging.java index 73a16f90..43c6a4c4 100644 --- a/slides/snippets/src/test/java/TestImageMerging.java +++ b/slides/snippets/src/test/java/TestImageMerging.java @@ -22,24 +22,25 @@ import static org.junit.Assert.assertNotNull; // Unit testcase for imageMerging snippet -public class TestImageMerging extends BaseTest{ - // TODO(developer) - change the IDs before executing - private final String IMAGE_URL = - "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"; - private final String TEMPLATE_PRESENTATION_ID = "1wJUN1B5CQ2wQOBzmz2apky48QNK1OsE2oNKHPMLpKDc"; - private final String CUSTOMER_NAME = "Fake Customer"; - @Test - public void testImageMerge() throws IOException { - BatchUpdatePresentationResponse response = - ImageMerging.imageMerging(TEMPLATE_PRESENTATION_ID, IMAGE_URL, CUSTOMER_NAME); - String presentationId = response.getPresentationId(); - assertNotNull(presentationId); - assertEquals(2, response.getReplies().size()); - int numReplacements = 0; - for(Response resp: response.getReplies()) { - numReplacements += resp.getReplaceAllShapesWithImage().getOccurrencesChanged(); - } - assertEquals(2, numReplacements); - deleteFileOnCleanup(presentationId); +public class TestImageMerging extends BaseTest { + // TODO(developer) - change the IDs before executing + private final String IMAGE_URL = + "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"; + private final String TEMPLATE_PRESENTATION_ID = "1wJUN1B5CQ2wQOBzmz2apky48QNK1OsE2oNKHPMLpKDc"; + private final String CUSTOMER_NAME = "Fake Customer"; + + @Test + public void testImageMerge() throws IOException { + BatchUpdatePresentationResponse response = + ImageMerging.imageMerging(TEMPLATE_PRESENTATION_ID, IMAGE_URL, CUSTOMER_NAME); + String presentationId = response.getPresentationId(); + assertNotNull(presentationId); + assertEquals(2, response.getReplies().size()); + int numReplacements = 0; + for (Response resp : response.getReplies()) { + numReplacements += resp.getReplaceAllShapesWithImage().getOccurrencesChanged(); } + assertEquals(2, numReplacements); + deleteFileOnCleanup(presentationId); + } } diff --git a/slides/snippets/src/test/java/TestRefreshSheetsChart.java b/slides/snippets/src/test/java/TestRefreshSheetsChart.java index b2c17928..6031f85b 100644 --- a/slides/snippets/src/test/java/TestRefreshSheetsChart.java +++ b/slides/snippets/src/test/java/TestRefreshSheetsChart.java @@ -20,19 +20,20 @@ import static org.junit.Assert.assertEquals; // Unit testcase for refreshSheetsChart snippet -public class TestRefreshSheetsChart extends BaseTest{ - // TODO(developer) - change the IDs before executing - private final String DATA_SPREADSHEET_ID = "14KaZMq2aCAGt5acV77zaA_Ps8aDt04G7T0ei4KiXLX8"; - private final Integer CHART_ID = 1107320627; - @Test - public void testRefreshSheetsChart() throws IOException { - String presentationId = this.createTestPresentation(); - String pageId = this.createTestSlide(presentationId); - String chartId = - this.createTestSheetsChart(presentationId, pageId, DATA_SPREADSHEET_ID, CHART_ID); - BatchUpdatePresentationResponse response = - RefreshSheetsChart.refreshSheetsChart(presentationId, chartId); - assertEquals(1, response.getReplies().size()); - deleteFileOnCleanup(presentationId); - } +public class TestRefreshSheetsChart extends BaseTest { + // TODO(developer) - change the IDs before executing + private final String DATA_SPREADSHEET_ID = "14KaZMq2aCAGt5acV77zaA_Ps8aDt04G7T0ei4KiXLX8"; + private final Integer CHART_ID = 1107320627; + + @Test + public void testRefreshSheetsChart() throws IOException { + String presentationId = this.createTestPresentation(); + String pageId = this.createTestSlide(presentationId); + String chartId = + this.createTestSheetsChart(presentationId, pageId, DATA_SPREADSHEET_ID, CHART_ID); + BatchUpdatePresentationResponse response = + RefreshSheetsChart.refreshSheetsChart(presentationId, chartId); + assertEquals(1, response.getReplies().size()); + deleteFileOnCleanup(presentationId); + } } diff --git a/slides/snippets/src/test/java/TestSimpleTextReplace.java b/slides/snippets/src/test/java/TestSimpleTextReplace.java index 397a3263..67df2489 100644 --- a/slides/snippets/src/test/java/TestSimpleTextReplace.java +++ b/slides/snippets/src/test/java/TestSimpleTextReplace.java @@ -20,16 +20,16 @@ import static org.junit.Assert.assertEquals; // Unit testcase for simpleTextReplace snippet -public class TestSimpleTextReplace extends BaseTest{ +public class TestSimpleTextReplace extends BaseTest { - @Test - public void testSimpleTextReplace() throws IOException { - String presentationId = createTestPresentation(); - String pageId = createTestSlide(presentationId); - String boxId = createTestTextBox(presentationId, pageId); - BatchUpdatePresentationResponse response = - SimpleTextReplace.simpleTextReplace(presentationId, boxId, "MY NEW TEXT"); - assertEquals(2, response.getReplies().size()); - deleteFileOnCleanup(presentationId); - } + @Test + public void testSimpleTextReplace() throws IOException { + String presentationId = createTestPresentation(); + String pageId = createTestSlide(presentationId); + String boxId = createTestTextBox(presentationId, pageId); + BatchUpdatePresentationResponse response = + SimpleTextReplace.simpleTextReplace(presentationId, boxId, "MY NEW TEXT"); + assertEquals(2, response.getReplies().size()); + deleteFileOnCleanup(presentationId); + } } diff --git a/slides/snippets/src/test/java/TestTextMerging.java b/slides/snippets/src/test/java/TestTextMerging.java index 35917aa3..873e89f5 100644 --- a/slides/snippets/src/test/java/TestTextMerging.java +++ b/slides/snippets/src/test/java/TestTextMerging.java @@ -23,24 +23,25 @@ import static org.junit.Assert.assertNotNull; // Unit testcase for textMerging snippet -public class TestTextMerging extends BaseTest{ - // TODO(developer) - change the IDs before executing - private final String TEMPLATE_PRESENTATION_ID = "1wJUN1B5CQ2wQOBzmz2apky48QNK1OsE2oNKHPMLpKDc"; - private final String DATA_SPREADSHEET_ID = "14KaZMq2aCAGt5acV77zaA_Ps8aDt04G7T0ei4KiXLX8"; - @Test - public void testTextMerge() throws IOException { - List responses = - TextMerging.textMerging(TEMPLATE_PRESENTATION_ID, DATA_SPREADSHEET_ID); - for (BatchUpdatePresentationResponse response: responses) { - String presentationId = response.getPresentationId(); - assertNotNull(presentationId); - assertEquals(3, response.getReplies().size()); - int numReplacements = 0; - for (Response resp : response.getReplies()) { - numReplacements += resp.getReplaceAllText().getOccurrencesChanged(); - } - assertEquals(4, numReplacements); - deleteFileOnCleanup(presentationId); - } +public class TestTextMerging extends BaseTest { + // TODO(developer) - change the IDs before executing + private final String TEMPLATE_PRESENTATION_ID = "1wJUN1B5CQ2wQOBzmz2apky48QNK1OsE2oNKHPMLpKDc"; + private final String DATA_SPREADSHEET_ID = "14KaZMq2aCAGt5acV77zaA_Ps8aDt04G7T0ei4KiXLX8"; + + @Test + public void testTextMerge() throws IOException { + List responses = + TextMerging.textMerging(TEMPLATE_PRESENTATION_ID, DATA_SPREADSHEET_ID); + for (BatchUpdatePresentationResponse response : responses) { + String presentationId = response.getPresentationId(); + assertNotNull(presentationId); + assertEquals(3, response.getReplies().size()); + int numReplacements = 0; + for (Response resp : response.getReplies()) { + numReplacements += resp.getReplaceAllText().getOccurrencesChanged(); + } + assertEquals(4, numReplacements); + deleteFileOnCleanup(presentationId); } + } } diff --git a/slides/snippets/src/test/java/TestTextStyleUpdate.java b/slides/snippets/src/test/java/TestTextStyleUpdate.java index 6bf13102..d751c217 100644 --- a/slides/snippets/src/test/java/TestTextStyleUpdate.java +++ b/slides/snippets/src/test/java/TestTextStyleUpdate.java @@ -20,16 +20,16 @@ import static org.junit.Assert.assertEquals; // Unit testcase for textStyleUpdate snippet -public class TestTextStyleUpdate extends BaseTest{ +public class TestTextStyleUpdate extends BaseTest { - @Test - public void testTextStyleUpdate() throws IOException { - String presentationId = this.createTestPresentation(); - String pageId = this.createTestSlide(presentationId); - String boxId = this.createTestTextBox(presentationId, pageId); - BatchUpdatePresentationResponse response = - TextStyleUpdate.textStyleUpdate(presentationId, boxId); - assertEquals(3, response.getReplies().size()); - deleteFileOnCleanup(presentationId); - } + @Test + public void testTextStyleUpdate() throws IOException { + String presentationId = this.createTestPresentation(); + String pageId = this.createTestSlide(presentationId); + String boxId = this.createTestTextBox(presentationId, pageId); + BatchUpdatePresentationResponse response = + TextStyleUpdate.textStyleUpdate(presentationId, boxId); + assertEquals(3, response.getReplies().size()); + deleteFileOnCleanup(presentationId); + } } diff --git a/tasks/quickstart/src/main/java/TasksQuickstart.java b/tasks/quickstart/src/main/java/TasksQuickstart.java index 8a522fdd..3e3f8346 100644 --- a/tasks/quickstart/src/main/java/TasksQuickstart.java +++ b/tasks/quickstart/src/main/java/TasksQuickstart.java @@ -13,6 +13,7 @@ // limitations under the License. // [START tasks_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; @@ -27,7 +28,6 @@ import com.google.api.services.tasks.TasksScopes; import com.google.api.services.tasks.model.TaskList; import com.google.api.services.tasks.model.TaskLists; - import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; @@ -37,61 +37,64 @@ import java.util.List; public class TasksQuickstart { - private static final String APPLICATION_NAME = "Google Tasks API Java Quickstart"; - private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); - private static final String TOKENS_DIRECTORY_PATH = "tokens"; + private static final String APPLICATION_NAME = "Google Tasks API Java Quickstart"; + private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); + 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(TasksScopes.TASKS_READONLY); - private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; + /** + * 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(TasksScopes.TASKS_READONLY); + private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; - /** - * Creates an authorized Credential object. - * @param HTTP_TRANSPORT The network HTTP Transport. - * @return An authorized Credential object. - * @throws IOException If the credentials.json file cannot be found. - */ - private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException { - // Load client secrets. - InputStream in = TasksQuickstart.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"); + /** + * Creates an authorized Credential object. + * + * @param HTTP_TRANSPORT The network HTTP Transport. + * @return An authorized Credential object. + * @throws IOException If the credentials.json file cannot be found. + */ + private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) + throws IOException { + // Load client secrets. + InputStream in = TasksQuickstart.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"); + } - public static void main(String... args) throws IOException, GeneralSecurityException { - // Build a new authorized API client service. - final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); - Tasks service = new Tasks.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) - .setApplicationName(APPLICATION_NAME) - .build(); + public static void main(String... args) throws IOException, GeneralSecurityException { + // Build a new authorized API client service. + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + Tasks service = new Tasks.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) + .setApplicationName(APPLICATION_NAME) + .build(); - // Print the first 10 task lists. - TaskLists result = service.tasklists().list() - .setMaxResults(10) - .execute(); - List taskLists = result.getItems(); - if (taskLists == null || taskLists.isEmpty()) { - System.out.println("No task lists found."); - } else { - System.out.println("Task lists:"); - for (TaskList tasklist : taskLists) { - System.out.printf("%s (%s)\n", tasklist.getTitle(), tasklist.getId()); - } - } + // Print the first 10 task lists. + TaskLists result = service.tasklists().list() + .setMaxResults(10) + .execute(); + List taskLists = result.getItems(); + if (taskLists == null || taskLists.isEmpty()) { + System.out.println("No task lists found."); + } else { + System.out.println("Task lists:"); + for (TaskList tasklist : taskLists) { + System.out.printf("%s (%s)\n", tasklist.getTitle(), tasklist.getId()); + } } + } } // [END tasks_quickstart] diff --git a/vault/quickstart/src/main/java/Quickstart.java b/vault/quickstart/src/main/java/Quickstart.java index 742b6184..66d99a64 100644 --- a/vault/quickstart/src/main/java/Quickstart.java +++ b/vault/quickstart/src/main/java/Quickstart.java @@ -13,6 +13,7 @@ // limitations under the License. // [START vault_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; @@ -35,101 +36,109 @@ import java.util.List; public class Quickstart { - /** Application name. */ - private static final String APPLICATION_NAME = - "Google Vault API Java Quickstart"; - - /** Directory to store authorization tokens for this application. */ - private static final java.io.File DATA_STORE_DIR = new java.io.File("tokens"); - - /** Global instance of the {@link FileDataStoreFactory}. */ - private static FileDataStoreFactory DATA_STORE_FACTORY; - - /** Global instance of the JSON factory. */ - private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); - - /** Global instance of the HTTP transport. */ - private static HttpTransport HTTP_TRANSPORT; + /** + * Application name. + */ + private static final String APPLICATION_NAME = + "Google Vault API Java Quickstart"; - private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; + /** + * Directory to store authorization tokens for this application. + */ + private static final java.io.File DATA_STORE_DIR = new java.io.File("tokens"); + /** + * Global instance of the JSON factory. + */ + private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); + private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; + /** + * Global instance of the scopes required by this quickstart. + *

+ * If modifying these scopes, delete your previously saved credentials + * at ~/.credentials/vault.googleapis.com-java-quickstart + */ + private static final List SCOPES = + Arrays.asList(VaultScopes.EDISCOVERY_READONLY); + /** + * Global instance of the {@link FileDataStoreFactory}. + */ + private static FileDataStoreFactory DATA_STORE_FACTORY; + /** + * Global instance of the HTTP transport. + */ + private static HttpTransport HTTP_TRANSPORT; - /** Global instance of the scopes required by this quickstart. - * - * If modifying these scopes, delete your previously saved credentials - * at ~/.credentials/vault.googleapis.com-java-quickstart - */ - private static final List SCOPES = - Arrays.asList(VaultScopes.EDISCOVERY_READONLY); - - static { - try { - HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); - DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR); - } catch (Throwable t) { - t.printStackTrace(); - System.exit(1); - } + static { + try { + HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR); + } catch (Throwable t) { + t.printStackTrace(); + System.exit(1); } + } - /** - * Creates an authorized Credential object. - * @return an authorized Credential object. - * @throws IOException - */ - public static Credential authorize() throws IOException { - // Load client secrets. - InputStream in = - Quickstart.class.getResourceAsStream("/credentials.json"); - 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(DATA_STORE_FACTORY) - .setAccessType("offline") - .build(); - Credential credential = new AuthorizationCodeInstalledApp( - flow, new LocalServerReceiver()).authorize("user"); - System.out.println( - "Credentials saved to " + DATA_STORE_DIR.getAbsolutePath()); - return credential; + /** + * Creates an authorized Credential object. + * + * @return an authorized Credential object. + * @throws IOException + */ + public static Credential authorize() throws IOException { + // Load client secrets. + InputStream in = + Quickstart.class.getResourceAsStream("/credentials.json"); + if (in == null) { + throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH); } + GoogleClientSecrets clientSecrets = + GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in)); - /** - * Build and return an authorized Vault client service. - * @return an authorized Vault client service - * @throws IOException - */ - public static Vault getVaultService() throws IOException { - Credential credential = authorize(); - return new Vault.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) - .setApplicationName(APPLICATION_NAME) - .build(); - } + // Build flow and trigger user authorization request. + GoogleAuthorizationCodeFlow flow = + new GoogleAuthorizationCodeFlow.Builder( + HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES) + .setDataStoreFactory(DATA_STORE_FACTORY) + .setAccessType("offline") + .build(); + Credential credential = new AuthorizationCodeInstalledApp( + flow, new LocalServerReceiver()).authorize("user"); + System.out.println( + "Credentials saved to " + DATA_STORE_DIR.getAbsolutePath()); + return credential; + } - public static void main(String[] args) throws IOException { - // Build a new authorized API client service. - Vault service = getVaultService(); + /** + * Build and return an authorized Vault client service. + * + * @return an authorized Vault client service + * @throws IOException + */ + public static Vault getVaultService() throws IOException { + Credential credential = authorize(); + return new Vault.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) + .setApplicationName(APPLICATION_NAME) + .build(); + } - // List the first 10 matters. - ListMattersResponse response = service.matters().list() - .setPageSize(10) - .execute(); - List matters = response.getMatters(); - if (matters == null || matters.size() == 0) { - System.out.println("No matters found."); - return; - } - System.out.println("Matters:"); - for (Matter matter: matters) { - System.out.printf("%s (%s)\n", matter.getName(), - matter.getMatterId()); - } + public static void main(String[] args) throws IOException { + // Build a new authorized API client service. + Vault service = getVaultService(); + + // List the first 10 matters. + ListMattersResponse response = service.matters().list() + .setPageSize(10) + .execute(); + List matters = response.getMatters(); + if (matters == null || matters.size() == 0) { + System.out.println("No matters found."); + return; + } + System.out.println("Matters:"); + for (Matter matter : matters) { + System.out.printf("%s (%s)\n", matter.getName(), + matter.getMatterId()); } + } } // [END vault_quickstart] diff --git a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/DuplicateHold.java b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/DuplicateHold.java index cf8ef242..25a06f0f 100644 --- a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/DuplicateHold.java +++ b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/DuplicateHold.java @@ -35,15 +35,14 @@ import org.apache.commons.csv.CSVRecord; public class DuplicateHold { - private static Logger logger = Logger.getLogger(DuplicateHold.class.getName()); - private static final String ERROR_DESCRIPTION = "Error Description"; public static final String HOLD_NAME_SUFFIX = "_hangoutsChat"; + private static final String ERROR_DESCRIPTION = "Error Description"; private static final int MAX_ACCOUNTS_FOR_HOLD = 100; - + private static Logger logger = Logger.getLogger(DuplicateHold.class.getName()); + Vault vaultService; private CSVParser csvParser; private boolean includeRooms; private CSVPrinter errorReport; - Vault vaultService; private int numberOfHolds = 0; public DuplicateHold( @@ -66,8 +65,8 @@ public int duplicateHolds() throws Exception { (accounts.equals("")) ? null : Arrays.stream(accounts.split(",")) - .map(account -> new HeldAccount().setAccountId(account)) - .collect(Collectors.toList()); + .map(account -> new HeldAccount().setAccountId(account)) + .collect(Collectors.toList()); boolean exceedsAccountLimit = false; Hold hold = new Hold().setName(name + HOLD_NAME_SUFFIX).setCorpus("HANGOUTS_CHAT"); diff --git a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/HoldsReport.java b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/HoldsReport.java index b2bb1a07..b337cddf 100644 --- a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/HoldsReport.java +++ b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/HoldsReport.java @@ -31,8 +31,6 @@ public class HoldsReport { - private static final Logger LOGGER = Logger.getLogger(HoldsReport.class.getName()); - public static final String MATTER_ID = "Matter Id"; public static final String MATTER_NAME = "Matter Name"; public static final String HOLD_ID = "Hold Id"; @@ -46,7 +44,7 @@ public class HoldsReport { public static final String TERMS = "Terms"; public static final String START_TIME = "startTime"; public static final String END_TIME = "endTime"; - + private static final Logger LOGGER = Logger.getLogger(HoldsReport.class.getName()); private Vault vaultService; private DirectoryService directoryService; private CSVPrinter printer; @@ -71,11 +69,11 @@ private void iterateMatters(String nextPageToken) throws Exception { ListMattersResponse response = RetryableTemplate.callWithRetry( vaultService - .matters() - .list() - .setState("OPEN") - .setPageSize(100) - .setPageToken(nextPageToken) + .matters() + .list() + .setState("OPEN") + .setPageSize(100) + .setPageToken(nextPageToken) ::execute); List matters = response.getMatters(); diff --git a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/MigrationHelper.java b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/MigrationHelper.java index 2da593c3..e867ff63 100644 --- a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/MigrationHelper.java +++ b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/MigrationHelper.java @@ -43,44 +43,25 @@ public class MigrationHelper { - enum MigrationOptions { - GENERATE_REPORT("a", "genholdreport", "Generate Hold Report"), - DUPLICATE_HOLDS("b", "duplicateholds", "Duplicate Gmail Holds to Hangouts Chat"), - REPORT_FILE("f", "reportfile", "Path to holds report file"), - ERROR_FILE("e", "errorfile", "Path to error report file"), - INCLUDE_ROOMS("g", "includerooms", "Include Rooms when duplicating holds to Hangouts Chat"), - HELP("h", "help", "Options Help"); - - private final String option; - private final String longOpt; - private final String description; - - MigrationOptions(String opt, String longOpt, String description) { - this.option = opt; - this.longOpt = longOpt; - this.description = description; - } - - public String getOption() { - return option; - } - } - - /** Application name. */ + static final Option helpOption = + Option.builder(MigrationOptions.HELP.option) + .longOpt(MigrationOptions.HELP.longOpt) + .argName("help") + .desc(MigrationOptions.HELP.description) + .build(); + /** + * Application name. + */ private static final String APPLICATION_NAME = "Google Vault API Java Quickstart"; - /** Directory to store authorization tokens for this application. */ + /** + * Directory to store authorization tokens for this application. + */ private static final java.io.File DATA_STORE_DIR = new java.io.File("tokens"); - - /** Global instance of the {@link FileDataStoreFactory}. */ - private static FileDataStoreFactory DATA_STORE_FACTORY; - - /** Global instance of the JSON factory. */ + /** + * Global instance of the JSON factory. + */ private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); - - /** Global instance of the HTTP transport. */ - private static HttpTransport HTTP_TRANSPORT; - /** * Global instance of the scopes required by this quickstart. * @@ -92,6 +73,14 @@ public String getOption() { VaultScopes.EDISCOVERY, DirectoryScopes.ADMIN_DIRECTORY_USER_READONLY, DirectoryScopes.ADMIN_DIRECTORY_ORGUNIT_READONLY); + /** + * Global instance of the {@link FileDataStoreFactory}. + */ + private static FileDataStoreFactory DATA_STORE_FACTORY; + /** + * Global instance of the HTTP transport. + */ + private static HttpTransport HTTP_TRANSPORT; static { try { @@ -106,13 +95,6 @@ public String getOption() { } } - static final Option helpOption = - Option.builder(MigrationOptions.HELP.option) - .longOpt(MigrationOptions.HELP.longOpt) - .argName("help") - .desc(MigrationOptions.HELP.description) - .build(); - static Options buildOptions() { Options options = new Options(); @@ -214,4 +196,27 @@ public static Directory getDirectoryService() throws IOException { .build(); return service; } + + enum MigrationOptions { + GENERATE_REPORT("a", "genholdreport", "Generate Hold Report"), + DUPLICATE_HOLDS("b", "duplicateholds", "Duplicate Gmail Holds to Hangouts Chat"), + REPORT_FILE("f", "reportfile", "Path to holds report file"), + ERROR_FILE("e", "errorfile", "Path to error report file"), + INCLUDE_ROOMS("g", "includerooms", "Include Rooms when duplicating holds to Hangouts Chat"), + HELP("h", "help", "Options Help"); + + private final String option; + private final String longOpt; + private final String description; + + MigrationOptions(String opt, String longOpt, String description) { + this.option = opt; + this.longOpt = longOpt; + this.description = description; + } + + public String getOption() { + return option; + } + } } From d94b838de9f6e8d775c0fc7ddd4d37cefcd7ee5d Mon Sep 17 00:00:00 2001 From: googleworkspace-bot <109114539+googleworkspace-bot@users.noreply.github.com> Date: Tue, 9 Aug 2022 17:01:01 -0600 Subject: [PATCH 017/152] chore: Synced file(s) with googleworkspace/.github (#259) * chore: Synced local '.github/workflows/automation.yml' with remote 'sync-files/defaults/.github/workflows/automation.yml' * chore: Synced local '.github/linters/' with remote 'sync-files/defaults/.github/linters/' --- .github/linters/sun_checks.xml | 620 +++++++++++++++---------------- .github/workflows/automation.yml | 10 +- 2 files changed, 315 insertions(+), 315 deletions(-) diff --git a/.github/linters/sun_checks.xml b/.github/linters/sun_checks.xml index de6c6cd4..76d0840d 100644 --- a/.github/linters/sun_checks.xml +++ b/.github/linters/sun_checks.xml @@ -13,8 +13,8 @@ --> + "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN" + "https://checkstyle.org/dtds/configuration_1_3.dtd"> - - + + - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + - - - - - - - - + + + + + - - + + + + + - - + + + + + + + + + + + + + + + + + + + + + + + + + - - - - + + - - - - - + + + - - - - - + + + - - - + - - - - - - - - - + + + + + + + - - - - - - - - - - - - + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - + + + + + + + + + + - - - + - - - - + + + - - - - + + - - - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - + + - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + - \ No newline at end of file diff --git a/.github/workflows/automation.yml b/.github/workflows/automation.yml index b01e9cf9..95f323bf 100644 --- a/.github/workflows/automation.yml +++ b/.github/workflows/automation.yml @@ -13,7 +13,7 @@ # limitations under the License. --- name: Automation -on: [push, pull_request, workflow_dispatch] +on: [ push, pull_request, workflow_dispatch ] jobs: dependabot: runs-on: ubuntu-latest @@ -41,13 +41,13 @@ jobs: - name: Set env run: | # set DEFAULT BRANCH - echo "DEFAULT_BRANCH=$(gh repo view --json defaultBranchRef --jq '.defaultBranchRef.name')" >> $GITHUB_ENV; + echo "DEFAULT_BRANCH=$(gh repo view --json defaultBranchRef --jq '.defaultBranchRef.name')" >> "$GITHUB_ENV"; # set HAS_MASTER_BRANCH - if [ ! -z "$(git ls-remote --heads origin master)" ]; then - echo "HAS_MASTER_BRANCH=true" >> $GITHUB_ENV + if [ -n "$(git ls-remote --heads origin master)" ]; then + echo "HAS_MASTER_BRANCH=true" >> "$GITHUB_ENV" else - echo "HAS_MASTER_BRANCH=false" >> $GITHUB_ENV + echo "HAS_MASTER_BRANCH=false" >> "$GITHUB_ENV" fi env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} From 7793559faf46d4c11f93399c180abb1498259a09 Mon Sep 17 00:00:00 2001 From: Steve Bazyl Date: Mon, 29 Aug 2022 12:10:25 -0600 Subject: [PATCH 018/152] fix: Update branch for rennovate --- renovate.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/renovate.json b/renovate.json index f45d8f11..f93f9542 100644 --- a/renovate.json +++ b/renovate.json @@ -1,5 +1,6 @@ { "extends": [ - "config:base" + "config:base", + "baseBranches": ["main"] ] } From e0a895afcda7a3de65d4653ef18eb3109a874b3e Mon Sep 17 00:00:00 2001 From: Steve Bazyl Date: Tue, 30 Aug 2022 09:33:12 -0600 Subject: [PATCH 019/152] chore: Create initial dependabot config --- .github/dependabot.yml | 110 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 .github/dependabot.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..c8c55cd4 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,110 @@ +version: 2 +updates: + - package-ecosystem: "maven" + directory: "/calendar/sync" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/calendar/sync" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/calendar/quickstart" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/sheets/snippets" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/sheets/quickstart" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/adminSDK/alertcenter" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/adminSDK/directory/quickstart" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/adminSDK/reseller/quickstart" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/adminSDK/groups-settings/quickstart" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/adminSDK/reports/quickstart" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/classroom/snippets" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/classroom/quickstart" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/docs/outputJSON" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/docs/quickstart" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/slides/snippets" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/slides/quickstart" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/people/quickstart" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/appsScript/quickstart" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/drive/snippets/drive_v2" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/drive/snippets/drive_v3" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/drive/activity/quickstart" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/drive/quickstart" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/drive/activity-v2/quickstart" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/gmail/snippets" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/gmail/quickstart" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/vault/quickstart" + schedule: + interval: "weekly" + - package-ecosystem: "gradle" + directory: "/vault/vault-hold-migration-api" + schedule: + interval: "weekly" From 39f5e7a3aab99c7d6b1a1d835f89d02872a0dd76 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 15:33:34 +0000 Subject: [PATCH 020/152] Bump maven-compiler-plugin from 2.3.2 to 3.10.1 in /calendar/sync Bumps [maven-compiler-plugin](https://github.com/apache/maven-compiler-plugin) from 2.3.2 to 3.10.1. - [Release notes](https://github.com/apache/maven-compiler-plugin/releases) - [Commits](https://github.com/apache/maven-compiler-plugin/compare/maven-compiler-plugin-2.3.2...maven-compiler-plugin-3.10.1) --- updated-dependencies: - dependency-name: org.apache.maven.plugins:maven-compiler-plugin dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- calendar/sync/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/calendar/sync/pom.xml b/calendar/sync/pom.xml index 5c38dc4e..cfc48a4b 100644 --- a/calendar/sync/pom.xml +++ b/calendar/sync/pom.xml @@ -38,7 +38,7 @@ org.apache.maven.plugins maven-compiler-plugin - 2.3.2 + 3.10.1 1.6 1.6 From 459368bbbcc3021ea4d6a378f9b42b128bbc1209 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:45:26 -0600 Subject: [PATCH 021/152] Bump google-oauth-client-jetty in /adminSDK/directory/quickstart (#264) Bumps [google-oauth-client-jetty](https://github.com/googleapis/google-oauth-java-client) from 1.32.1 to 1.34.1. - [Release notes](https://github.com/googleapis/google-oauth-java-client/releases) - [Changelog](https://github.com/googleapis/google-oauth-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-oauth-java-client/compare/v1.32.1...v1.34.1) --- updated-dependencies: - dependency-name: com.google.oauth-client:google-oauth-client-jetty dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- adminSDK/directory/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adminSDK/directory/quickstart/build.gradle b/adminSDK/directory/quickstart/build.gradle index 4ea5ca58..3504f0b0 100644 --- a/adminSDK/directory/quickstart/build.gradle +++ b/adminSDK/directory/quickstart/build.gradle @@ -12,6 +12,6 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:1.33.0' - implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1' + implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-admin-directory:directory_v1-rev118-1.25.0' } From 723e95e437745700bd548947d8a4d5b99c6d36fb Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:45:50 -0600 Subject: [PATCH 022/152] Bump google-auth-library-oauth2-http in /sheets/snippets (#305) Bumps google-auth-library-oauth2-http from 1.6.0 to 1.10.0. --- updated-dependencies: - dependency-name: com.google.auth:google-auth-library-oauth2-http dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- sheets/snippets/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sheets/snippets/build.gradle b/sheets/snippets/build.gradle index 6988f011..e26101e4 100644 --- a/sheets/snippets/build.gradle +++ b/sheets/snippets/build.gradle @@ -5,7 +5,7 @@ repositories { } dependencies { - implementation 'com.google.auth:google-auth-library-oauth2-http:1.6.0' + implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' implementation 'com.google.apis:google-api-services-drive:v3-rev20220508-1.32.1' implementation 'com.google.apis:google-api-services-sheets:v4-rev20220411-1.32.1' testImplementation 'junit:junit:4.13.2' From e253f091b9c26042bc721e1601d26a989bb280be Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:47:25 -0600 Subject: [PATCH 023/152] Bump google-api-services-drive in /sheets/snippets (#302) Bumps google-api-services-drive from v3-rev20220508-1.32.1 to v3-rev20220815-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-drive dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- sheets/snippets/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sheets/snippets/build.gradle b/sheets/snippets/build.gradle index e26101e4..dc97d33a 100644 --- a/sheets/snippets/build.gradle +++ b/sheets/snippets/build.gradle @@ -6,7 +6,7 @@ repositories { dependencies { implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' - implementation 'com.google.apis:google-api-services-drive:v3-rev20220508-1.32.1' + implementation 'com.google.apis:google-api-services-drive:v3-rev20220815-2.0.0' implementation 'com.google.apis:google-api-services-sheets:v4-rev20220411-1.32.1' testImplementation 'junit:junit:4.13.2' } From e8efd560d4fbc64a37f3fb70ace03109420fd339 Mon Sep 17 00:00:00 2001 From: Steve Bazyl Date: Tue, 30 Aug 2022 09:51:11 -0600 Subject: [PATCH 024/152] Revert "Bump google-api-services-drive in /sheets/snippets (#302)" (#327) This reverts commit e253f091b9c26042bc721e1601d26a989bb280be. --- sheets/snippets/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sheets/snippets/build.gradle b/sheets/snippets/build.gradle index dc97d33a..e26101e4 100644 --- a/sheets/snippets/build.gradle +++ b/sheets/snippets/build.gradle @@ -6,7 +6,7 @@ repositories { dependencies { implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' - implementation 'com.google.apis:google-api-services-drive:v3-rev20220815-2.0.0' + implementation 'com.google.apis:google-api-services-drive:v3-rev20220508-1.32.1' implementation 'com.google.apis:google-api-services-sheets:v4-rev20220411-1.32.1' testImplementation 'junit:junit:4.13.2' } From aa8299e5d8e99d80c07bbf6280bf97ae9cb29cd2 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:51:39 -0600 Subject: [PATCH 025/152] Bump google-oauth-client-jetty in /appsScript/quickstart (#311) Bumps [google-oauth-client-jetty](https://github.com/googleapis/google-oauth-java-client) from 1.32.1 to 1.34.1. - [Release notes](https://github.com/googleapis/google-oauth-java-client/releases) - [Changelog](https://github.com/googleapis/google-oauth-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-oauth-java-client/compare/v1.32.1...v1.34.1) --- updated-dependencies: - dependency-name: com.google.oauth-client:google-oauth-client-jetty dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- appsScript/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/appsScript/quickstart/build.gradle b/appsScript/quickstart/build.gradle index 4990f03e..41dd51b6 100644 --- a/appsScript/quickstart/build.gradle +++ b/appsScript/quickstart/build.gradle @@ -12,6 +12,6 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:1.33.0' - implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1' + implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-script:v1-rev20210703-1.32.1' } From 52f1ea92012ee09ad5f00559edbcfc12d355eb78 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:51:51 -0600 Subject: [PATCH 026/152] Bump google-oauth-client-jetty in /slides/quickstart (#312) Bumps [google-oauth-client-jetty](https://github.com/googleapis/google-oauth-java-client) from 1.32.1 to 1.34.1. - [Release notes](https://github.com/googleapis/google-oauth-java-client/releases) - [Changelog](https://github.com/googleapis/google-oauth-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-oauth-java-client/compare/v1.32.1...v1.34.1) --- updated-dependencies: - dependency-name: com.google.oauth-client:google-oauth-client-jetty dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- slides/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/slides/quickstart/build.gradle b/slides/quickstart/build.gradle index 36d3ef1d..d4eac491 100644 --- a/slides/quickstart/build.gradle +++ b/slides/quickstart/build.gradle @@ -12,6 +12,6 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:1.33.0' - implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1' + implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-slides:v1-rev20210820-1.32.1' } From 3924b322468ca4c0892d2e319d0ccee6d479ce2a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:52:16 -0600 Subject: [PATCH 027/152] Bump google-auth-library-oauth2-http in /drive/snippets/drive_v3 (#317) Bumps google-auth-library-oauth2-http from 1.3.0 to 1.10.0. --- updated-dependencies: - dependency-name: com.google.auth:google-auth-library-oauth2-http dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- drive/snippets/drive_v3/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drive/snippets/drive_v3/build.gradle b/drive/snippets/drive_v3/build.gradle index 4327d404..0343fc54 100644 --- a/drive/snippets/drive_v3/build.gradle +++ b/drive/snippets/drive_v3/build.gradle @@ -6,7 +6,7 @@ repositories { dependencies { implementation 'com.google.apis:google-api-services-drive:v3-rev20211107-1.32.1' implementation 'com.google.api-client:google-api-client:1.23.0' - implementation 'com.google.auth:google-auth-library-oauth2-http:1.3.0' + implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' implementation 'com.google.code.gson:gson:2.4' testImplementation 'junit:junit:4.12' } From b3581e59e30cdd2e7b02ebb8341cb9eeb0defcde Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:52:30 -0600 Subject: [PATCH 028/152] Bump google-oauth-client-jetty in /gmail/quickstart (#320) Bumps [google-oauth-client-jetty](https://github.com/googleapis/google-oauth-java-client) from 1.32.1 to 1.34.1. - [Release notes](https://github.com/googleapis/google-oauth-java-client/releases) - [Changelog](https://github.com/googleapis/google-oauth-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-oauth-java-client/compare/v1.32.1...v1.34.1) --- updated-dependencies: - dependency-name: com.google.oauth-client:google-oauth-client-jetty dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- gmail/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gmail/quickstart/build.gradle b/gmail/quickstart/build.gradle index 0dae0ebf..ce120ab6 100644 --- a/gmail/quickstart/build.gradle +++ b/gmail/quickstart/build.gradle @@ -12,6 +12,6 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:1.33.0' - implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1' + implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-gmail:v1-rev20211108-1.32.1' } From 8db9cc176bfc2859ce1166c4740d3b859020fb24 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:52:54 -0600 Subject: [PATCH 029/152] Bump mockito-inline from 4.5.1 to 4.7.0 in /gmail/snippets (#321) Bumps [mockito-inline](https://github.com/mockito/mockito) from 4.5.1 to 4.7.0. - [Release notes](https://github.com/mockito/mockito/releases) - [Commits](https://github.com/mockito/mockito/compare/v4.5.1...v4.7.0) --- updated-dependencies: - dependency-name: org.mockito:mockito-inline dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- gmail/snippets/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gmail/snippets/build.gradle b/gmail/snippets/build.gradle index 85351fa9..5e89d634 100644 --- a/gmail/snippets/build.gradle +++ b/gmail/snippets/build.gradle @@ -10,5 +10,5 @@ dependencies { implementation 'javax.mail:mail:1.4.7' implementation 'org.apache.commons:commons-csv:1.9.0' testImplementation 'junit:junit:4.13.2' - testImplementation 'org.mockito:mockito-inline:4.5.1' + testImplementation 'org.mockito:mockito-inline:4.7.0' } From 852802a313111e3d53f7bb4de611d9621abb7e40 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:53:14 -0600 Subject: [PATCH 030/152] Bump google-oauth-client-jetty in /vault/vault-hold-migration-api (#324) Bumps [google-oauth-client-jetty](https://github.com/googleapis/google-oauth-java-client) from 1.32.1 to 1.34.1. - [Release notes](https://github.com/googleapis/google-oauth-java-client/releases) - [Changelog](https://github.com/googleapis/google-oauth-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-oauth-java-client/compare/v1.32.1...v1.34.1) --- updated-dependencies: - dependency-name: com.google.oauth-client:google-oauth-client-jetty dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- vault/vault-hold-migration-api/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vault/vault-hold-migration-api/build.gradle b/vault/vault-hold-migration-api/build.gradle index 83db2baf..82e95410 100644 --- a/vault/vault-hold-migration-api/build.gradle +++ b/vault/vault-hold-migration-api/build.gradle @@ -13,7 +13,7 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:1.33.0' - implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1' + implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-vault:v1-rev20211101-1.32.1' implementation group: 'org.apache.commons', name: 'commons-csv', version: '1.9.0' implementation 'com.github.rholder:guava-retrying:2.0.0' From eecc00323c0c60b4c7d23b96227f86e15554b719 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:53:34 -0600 Subject: [PATCH 031/152] Bump google-auth-library-oauth2-http in /slides/snippets (#326) Bumps google-auth-library-oauth2-http from 1.3.0 to 1.10.0. --- updated-dependencies: - dependency-name: com.google.auth:google-auth-library-oauth2-http dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- slides/snippets/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/slides/snippets/build.gradle b/slides/snippets/build.gradle index 1279246b..ea3403b8 100644 --- a/slides/snippets/build.gradle +++ b/slides/snippets/build.gradle @@ -5,7 +5,7 @@ repositories { } dependencies { - implementation 'com.google.auth:google-auth-library-oauth2-http:1.3.0' + implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' implementation 'com.google.apis:google-api-services-drive:v3-rev20211107-1.32.1' implementation 'com.google.apis:google-api-services-sheets:v4-rev20210629-1.32.1' implementation 'com.google.apis:google-api-services-slides:v1-rev20210820-1.32.1' From cb7ba0681710410b7ac2d3b988b2af0e8bae7131 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:54:10 -0600 Subject: [PATCH 032/152] Bump google-oauth-client-jetty in /adminSDK/reseller/quickstart (#294) Bumps [google-oauth-client-jetty](https://github.com/googleapis/google-oauth-java-client) from 1.32.1 to 1.34.1. - [Release notes](https://github.com/googleapis/google-oauth-java-client/releases) - [Changelog](https://github.com/googleapis/google-oauth-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-oauth-java-client/compare/v1.32.1...v1.34.1) --- updated-dependencies: - dependency-name: com.google.oauth-client:google-oauth-client-jetty dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- adminSDK/reseller/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adminSDK/reseller/quickstart/build.gradle b/adminSDK/reseller/quickstart/build.gradle index 11603c02..8903a301 100644 --- a/adminSDK/reseller/quickstart/build.gradle +++ b/adminSDK/reseller/quickstart/build.gradle @@ -12,6 +12,6 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:1.33.0' - implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1' + implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-reseller:v1-rev20211106-1.32.1' } From 5148cb485ae821b08fa46aefaeed93bc2e993bc8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:54:33 -0600 Subject: [PATCH 033/152] Bump google-oauth-client-jetty in /adminSDK/groups-settings/quickstart (#290) Bumps [google-oauth-client-jetty](https://github.com/googleapis/google-oauth-java-client) from 1.32.1 to 1.34.1. - [Release notes](https://github.com/googleapis/google-oauth-java-client/releases) - [Changelog](https://github.com/googleapis/google-oauth-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-oauth-java-client/compare/v1.32.1...v1.34.1) --- updated-dependencies: - dependency-name: com.google.oauth-client:google-oauth-client-jetty dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- adminSDK/groups-settings/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adminSDK/groups-settings/quickstart/build.gradle b/adminSDK/groups-settings/quickstart/build.gradle index 34720176..c03cdd97 100644 --- a/adminSDK/groups-settings/quickstart/build.gradle +++ b/adminSDK/groups-settings/quickstart/build.gradle @@ -12,6 +12,6 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:1.33.0' - implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1' + implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-groupssettings:v1-rev20210624-1.32.1' } From cdfdafa538a6cd5668eb069da2279ae4edec4b83 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:54:45 -0600 Subject: [PATCH 034/152] Bump google-oauth-client-jetty in /sheets/quickstart (#288) Bumps [google-oauth-client-jetty](https://github.com/googleapis/google-oauth-java-client) from 1.32.1 to 1.34.1. - [Release notes](https://github.com/googleapis/google-oauth-java-client/releases) - [Changelog](https://github.com/googleapis/google-oauth-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-oauth-java-client/compare/v1.32.1...v1.34.1) --- updated-dependencies: - dependency-name: com.google.oauth-client:google-oauth-client-jetty dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- sheets/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sheets/quickstart/build.gradle b/sheets/quickstart/build.gradle index d5b89b8c..dbf63a92 100644 --- a/sheets/quickstart/build.gradle +++ b/sheets/quickstart/build.gradle @@ -12,6 +12,6 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:1.33.0' - implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1' + implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-sheets:v4-rev20210629-1.32.1' } From ed883c8f816d8a223e0577881cbcd55a6f6159e0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:55:26 -0600 Subject: [PATCH 035/152] Bump google-oauth-client-jetty in /adminSDK/reports/quickstart (#265) Bumps [google-oauth-client-jetty](https://github.com/googleapis/google-oauth-java-client) from 1.32.1 to 1.34.1. - [Release notes](https://github.com/googleapis/google-oauth-java-client/releases) - [Changelog](https://github.com/googleapis/google-oauth-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-oauth-java-client/compare/v1.32.1...v1.34.1) --- updated-dependencies: - dependency-name: com.google.oauth-client:google-oauth-client-jetty dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- adminSDK/reports/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adminSDK/reports/quickstart/build.gradle b/adminSDK/reports/quickstart/build.gradle index 80e4d79b..f5ae3c7e 100644 --- a/adminSDK/reports/quickstart/build.gradle +++ b/adminSDK/reports/quickstart/build.gradle @@ -12,6 +12,6 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:1.33.0' - implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1' + implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-admin-reports:reports_v1-rev89-1.25.0' } From fd6359c2cd8000340b938b726785968692b2a831 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:55:43 -0600 Subject: [PATCH 036/152] Bump google-oauth-client-jetty in /calendar/quickstart (#267) Bumps [google-oauth-client-jetty](https://github.com/googleapis/google-oauth-java-client) from 1.32.1 to 1.34.1. - [Release notes](https://github.com/googleapis/google-oauth-java-client/releases) - [Changelog](https://github.com/googleapis/google-oauth-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-oauth-java-client/compare/v1.32.1...v1.34.1) --- updated-dependencies: - dependency-name: com.google.oauth-client:google-oauth-client-jetty dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- calendar/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/calendar/quickstart/build.gradle b/calendar/quickstart/build.gradle index 1c1455c3..deb17b9e 100644 --- a/calendar/quickstart/build.gradle +++ b/calendar/quickstart/build.gradle @@ -12,6 +12,6 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:1.33.0' - implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1' + implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-calendar:v3-rev20211026-1.32.1' } From c7643e9f39cc6bd71b0d5582e97672a81bc371ce Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:56:00 -0600 Subject: [PATCH 037/152] Bump google-oauth-client-jetty in /classroom/quickstart (#268) Bumps [google-oauth-client-jetty](https://github.com/googleapis/google-oauth-java-client) from 1.32.1 to 1.34.1. - [Release notes](https://github.com/googleapis/google-oauth-java-client/releases) - [Changelog](https://github.com/googleapis/google-oauth-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-oauth-java-client/compare/v1.32.1...v1.34.1) --- updated-dependencies: - dependency-name: com.google.oauth-client:google-oauth-client-jetty dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- classroom/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/classroom/quickstart/build.gradle b/classroom/quickstart/build.gradle index c3dd8ad2..663c1057 100644 --- a/classroom/quickstart/build.gradle +++ b/classroom/quickstart/build.gradle @@ -12,6 +12,6 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:1.33.0' - implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1' + implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-classroom:v1-rev20211029-1.32.1' } From 7d4d744f16b7dceef787374504e3d247a8d34931 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:56:12 -0600 Subject: [PATCH 038/152] Bump google-auth-library-oauth2-http in /classroom/snippets (#270) Bumps google-auth-library-oauth2-http from 1.6.0 to 1.10.0. --- updated-dependencies: - dependency-name: com.google.auth:google-auth-library-oauth2-http dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- classroom/snippets/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/classroom/snippets/build.gradle b/classroom/snippets/build.gradle index 1f4cdc7b..f9591fca 100644 --- a/classroom/snippets/build.gradle +++ b/classroom/snippets/build.gradle @@ -7,7 +7,7 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:1.34.1' - implementation 'com.google.auth:google-auth-library-oauth2-http:1.6.0' + implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' implementation 'com.google.apis:google-api-services-classroom:v1-rev20220323-1.32.1' testImplementation 'junit:junit:4.13.2' } From 8045076a85329574aa2e68f817ed0b3f470bb64f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:56:29 -0600 Subject: [PATCH 039/152] Bump google-oauth-client-jetty from 1.32.1 to 1.34.1 in /docs/quickstart (#271) Bumps [google-oauth-client-jetty](https://github.com/googleapis/google-oauth-java-client) from 1.32.1 to 1.34.1. - [Release notes](https://github.com/googleapis/google-oauth-java-client/releases) - [Changelog](https://github.com/googleapis/google-oauth-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-oauth-java-client/compare/v1.32.1...v1.34.1) --- updated-dependencies: - dependency-name: com.google.oauth-client:google-oauth-client-jetty dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- docs/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/quickstart/build.gradle b/docs/quickstart/build.gradle index 48c9c11a..6583c267 100644 --- a/docs/quickstart/build.gradle +++ b/docs/quickstart/build.gradle @@ -12,6 +12,6 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:1.33.0' - implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1' + implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-docs:v1-rev20210707-1.32.1' } From a1094e4be0868062e19d5f73edf1db0f70afed6f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:56:39 -0600 Subject: [PATCH 040/152] Bump google-oauth-client-jetty from 1.32.1 to 1.34.1 in /docs/outputJSON (#272) Bumps [google-oauth-client-jetty](https://github.com/googleapis/google-oauth-java-client) from 1.32.1 to 1.34.1. - [Release notes](https://github.com/googleapis/google-oauth-java-client/releases) - [Changelog](https://github.com/googleapis/google-oauth-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-oauth-java-client/compare/v1.32.1...v1.34.1) --- updated-dependencies: - dependency-name: com.google.oauth-client:google-oauth-client-jetty dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- docs/outputJSON/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/outputJSON/build.gradle b/docs/outputJSON/build.gradle index 9a65d38a..7d9f8019 100644 --- a/docs/outputJSON/build.gradle +++ b/docs/outputJSON/build.gradle @@ -12,7 +12,7 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:1.33.0' - implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1' + implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-docs:v1-rev20210707-1.32.1' implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.9' } From 3677bb015f4273a1c389286dddfccea08ae7b51d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:56:56 -0600 Subject: [PATCH 041/152] Bump google-oauth-client-jetty in /people/quickstart (#274) Bumps [google-oauth-client-jetty](https://github.com/googleapis/google-oauth-java-client) from 1.32.1 to 1.34.1. - [Release notes](https://github.com/googleapis/google-oauth-java-client/releases) - [Changelog](https://github.com/googleapis/google-oauth-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-oauth-java-client/compare/v1.32.1...v1.34.1) --- updated-dependencies: - dependency-name: com.google.oauth-client:google-oauth-client-jetty dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- people/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/people/quickstart/build.gradle b/people/quickstart/build.gradle index 6b72f13a..8592e052 100644 --- a/people/quickstart/build.gradle +++ b/people/quickstart/build.gradle @@ -13,6 +13,6 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:1.33.0' - implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1' + implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-people:v1-rev20210903-1.32.1' } From 92a97507f19ed251922a9f0138b5b6a134692e07 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:57:12 -0600 Subject: [PATCH 042/152] Bump gson from 2.8.9 to 2.9.1 in /docs/outputJSON (#275) Bumps [gson](https://github.com/google/gson) from 2.8.9 to 2.9.1. - [Release notes](https://github.com/google/gson/releases) - [Changelog](https://github.com/google/gson/blob/master/CHANGELOG.md) - [Commits](https://github.com/google/gson/compare/gson-parent-2.8.9...gson-parent-2.9.1) --- updated-dependencies: - dependency-name: com.google.code.gson:gson dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- docs/outputJSON/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/outputJSON/build.gradle b/docs/outputJSON/build.gradle index 7d9f8019..1a1343c3 100644 --- a/docs/outputJSON/build.gradle +++ b/docs/outputJSON/build.gradle @@ -14,5 +14,5 @@ dependencies { implementation 'com.google.api-client:google-api-client:1.33.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-docs:v1-rev20210707-1.32.1' - implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.9' + implementation group: 'com.google.code.gson', name: 'gson', version: '2.9.1' } From edb6ed7f72ef4da6de1841687054efc7332909df Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:57:26 -0600 Subject: [PATCH 043/152] Bump google-oauth-client-jetty in /drive/quickstart (#277) Bumps [google-oauth-client-jetty](https://github.com/googleapis/google-oauth-java-client) from 1.32.1 to 1.34.1. - [Release notes](https://github.com/googleapis/google-oauth-java-client/releases) - [Changelog](https://github.com/googleapis/google-oauth-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-oauth-java-client/compare/v1.32.1...v1.34.1) --- updated-dependencies: - dependency-name: com.google.oauth-client:google-oauth-client-jetty dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- drive/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drive/quickstart/build.gradle b/drive/quickstart/build.gradle index b83619da..0cc1a504 100644 --- a/drive/quickstart/build.gradle +++ b/drive/quickstart/build.gradle @@ -12,6 +12,6 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:1.33.0' - implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1' + implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-drive:v3-rev20211107-1.32.1' } From 047cc2e3d5e5a99bcf424c0960ef87dd4951dcca Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:57:41 -0600 Subject: [PATCH 044/152] Bump google-oauth-client-jetty in /drive/activity-v2/quickstart (#279) Bumps [google-oauth-client-jetty](https://github.com/googleapis/google-oauth-java-client) from 1.32.1 to 1.34.1. - [Release notes](https://github.com/googleapis/google-oauth-java-client/releases) - [Changelog](https://github.com/googleapis/google-oauth-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-oauth-java-client/compare/v1.32.1...v1.34.1) --- updated-dependencies: - dependency-name: com.google.oauth-client:google-oauth-client-jetty dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- drive/activity-v2/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drive/activity-v2/quickstart/build.gradle b/drive/activity-v2/quickstart/build.gradle index 7d0a08b6..8cc523f1 100644 --- a/drive/activity-v2/quickstart/build.gradle +++ b/drive/activity-v2/quickstart/build.gradle @@ -12,6 +12,6 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:1.33.0' - implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1' + implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-driveactivity:v2-rev20210319-1.32.1' } From b30dff3187f1a9f446e184daacd522dd8103d164 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:57:55 -0600 Subject: [PATCH 045/152] Bump google-oauth-client-jetty in /vault/quickstart (#281) Bumps [google-oauth-client-jetty](https://github.com/googleapis/google-oauth-java-client) from 1.32.1 to 1.34.1. - [Release notes](https://github.com/googleapis/google-oauth-java-client/releases) - [Changelog](https://github.com/googleapis/google-oauth-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-oauth-java-client/compare/v1.32.1...v1.34.1) --- updated-dependencies: - dependency-name: com.google.oauth-client:google-oauth-client-jetty dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- vault/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vault/quickstart/build.gradle b/vault/quickstart/build.gradle index c7428927..26e72d92 100644 --- a/vault/quickstart/build.gradle +++ b/vault/quickstart/build.gradle @@ -12,6 +12,6 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:1.33.0' - implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1' + implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-vault:v1-rev20211101-1.32.1' } From c3286021e30dbaccf4d19cf0f152d4e794bd3436 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:58:06 -0600 Subject: [PATCH 046/152] Bump google-oauth-client-jetty in /drive/activity/quickstart (#282) Bumps [google-oauth-client-jetty](https://github.com/googleapis/google-oauth-java-client) from 1.32.1 to 1.34.1. - [Release notes](https://github.com/googleapis/google-oauth-java-client/releases) - [Changelog](https://github.com/googleapis/google-oauth-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-oauth-java-client/compare/v1.32.1...v1.34.1) --- updated-dependencies: - dependency-name: com.google.oauth-client:google-oauth-client-jetty dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- drive/activity/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drive/activity/quickstart/build.gradle b/drive/activity/quickstart/build.gradle index 32e034a8..583730c7 100644 --- a/drive/activity/quickstart/build.gradle +++ b/drive/activity/quickstart/build.gradle @@ -12,6 +12,6 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:1.33.0' - implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1' + implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-appsactivity:v1-rev20200128-1.30.10' } From 1e7064a1480edfcfb1cc1a7707e89d54583cfba7 Mon Sep 17 00:00:00 2001 From: Steve Bazyl Date: Tue, 30 Aug 2022 13:33:06 -0600 Subject: [PATCH 047/152] chore: disable rennovate --- renovate.json | 6 ------ 1 file changed, 6 deletions(-) delete mode 100644 renovate.json diff --git a/renovate.json b/renovate.json deleted file mode 100644 index f93f9542..00000000 --- a/renovate.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "extends": [ - "config:base", - "baseBranches": ["main"] - ] -} From 6ba16c3c4ae46e2cb2e682eb997f4c390cbe126a Mon Sep 17 00:00:00 2001 From: Steve Bazyl Date: Tue, 30 Aug 2022 13:38:47 -0600 Subject: [PATCH 048/152] fix: FIx broken path + add commit message prefix --- .github/dependabot.yml | 54 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 52 insertions(+), 2 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index c8c55cd4..f8f45ff1 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -4,62 +4,92 @@ updates: directory: "/calendar/sync" schedule: interval: "weekly" + commit-message: + prefix: "chore(deps):" - package-ecosystem: "gradle" - directory: "/calendar/sync" + directory: "/tasks/quickstart" schedule: interval: "weekly" + commit-message: + prefix: "chore(deps):" - package-ecosystem: "gradle" directory: "/calendar/quickstart" schedule: interval: "weekly" + commit-message: + prefix: "chore(deps):" - package-ecosystem: "gradle" directory: "/sheets/snippets" schedule: interval: "weekly" + commit-message: + prefix: "chore(deps):" - package-ecosystem: "gradle" directory: "/sheets/quickstart" schedule: interval: "weekly" + commit-message: + prefix: "chore(deps):" - package-ecosystem: "gradle" - directory: "/adminSDK/alertcenter" + directory: "/adminSDK/alertcenter/quickstart" schedule: interval: "weekly" + commit-message: + prefix: "chore(deps):" - package-ecosystem: "gradle" directory: "/adminSDK/directory/quickstart" schedule: interval: "weekly" + commit-message: + prefix: "chore(deps):" - package-ecosystem: "gradle" directory: "/adminSDK/reseller/quickstart" schedule: interval: "weekly" + commit-message: + prefix: "chore(deps):" - package-ecosystem: "gradle" directory: "/adminSDK/groups-settings/quickstart" schedule: interval: "weekly" + commit-message: + prefix: "chore(deps):" - package-ecosystem: "gradle" directory: "/adminSDK/reports/quickstart" schedule: interval: "weekly" + commit-message: + prefix: "chore(deps):" - package-ecosystem: "gradle" directory: "/classroom/snippets" schedule: interval: "weekly" + commit-message: + prefix: "chore(deps):" - package-ecosystem: "gradle" directory: "/classroom/quickstart" schedule: interval: "weekly" + commit-message: + prefix: "chore(deps):" - package-ecosystem: "gradle" directory: "/docs/outputJSON" schedule: interval: "weekly" + commit-message: + prefix: "chore(deps):" - package-ecosystem: "gradle" directory: "/docs/quickstart" schedule: interval: "weekly" + commit-message: + prefix: "chore(deps):" - package-ecosystem: "gradle" directory: "/slides/snippets" schedule: interval: "weekly" + commit-message: + prefix: "chore(deps):" - package-ecosystem: "gradle" directory: "/slides/quickstart" schedule: @@ -68,42 +98,62 @@ updates: directory: "/people/quickstart" schedule: interval: "weekly" + commit-message: + prefix: "chore(deps):" - package-ecosystem: "gradle" directory: "/appsScript/quickstart" schedule: interval: "weekly" + commit-message: + prefix: "chore(deps):" - package-ecosystem: "gradle" directory: "/drive/snippets/drive_v2" schedule: interval: "weekly" + commit-message: + prefix: "chore(deps):" - package-ecosystem: "gradle" directory: "/drive/snippets/drive_v3" schedule: interval: "weekly" + commit-message: + prefix: "chore(deps):" - package-ecosystem: "gradle" directory: "/drive/activity/quickstart" schedule: interval: "weekly" + commit-message: + prefix: "chore(deps):" - package-ecosystem: "gradle" directory: "/drive/quickstart" schedule: interval: "weekly" + commit-message: + prefix: "chore(deps):" - package-ecosystem: "gradle" directory: "/drive/activity-v2/quickstart" schedule: interval: "weekly" + commit-message: + prefix: "chore(deps):" - package-ecosystem: "gradle" directory: "/gmail/snippets" schedule: interval: "weekly" + commit-message: + prefix: "chore(deps):" - package-ecosystem: "gradle" directory: "/gmail/quickstart" schedule: interval: "weekly" + commit-message: + prefix: "chore(deps):" - package-ecosystem: "gradle" directory: "/vault/quickstart" schedule: interval: "weekly" + commit-message: + prefix: "chore(deps):" - package-ecosystem: "gradle" directory: "/vault/vault-hold-migration-api" schedule: From 462ee2a9792b76f74085904df6a428dedeb5ae49 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 13:58:21 -0600 Subject: [PATCH 049/152] chore(deps): bump google-auth-library-oauth2-http (#348) Bumps google-auth-library-oauth2-http from 1.3.0 to 1.10.0. --- updated-dependencies: - dependency-name: com.google.auth:google-auth-library-oauth2-http dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- adminSDK/alertcenter/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adminSDK/alertcenter/quickstart/build.gradle b/adminSDK/alertcenter/quickstart/build.gradle index 5cd6a28e..ddd97edc 100644 --- a/adminSDK/alertcenter/quickstart/build.gradle +++ b/adminSDK/alertcenter/quickstart/build.gradle @@ -13,6 +13,6 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:1.33.0' - implementation 'com.google.auth:google-auth-library-oauth2-http:1.3.0' + implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' implementation 'com.google.apis:google-api-services-alertcenter:v1beta1-rev20211012-1.32.1' } \ No newline at end of file From c80f847bc4d9e9c15d9a5154f61f5e8e57fad05c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 13:58:42 -0600 Subject: [PATCH 050/152] chore(deps): bump google-oauth-client-jetty in /tasks/quickstart (#350) Bumps [google-oauth-client-jetty](https://github.com/googleapis/google-oauth-java-client) from 1.32.1 to 1.34.1. - [Release notes](https://github.com/googleapis/google-oauth-java-client/releases) - [Changelog](https://github.com/googleapis/google-oauth-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-oauth-java-client/compare/v1.32.1...v1.34.1) --- updated-dependencies: - dependency-name: com.google.oauth-client:google-oauth-client-jetty dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- tasks/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tasks/quickstart/build.gradle b/tasks/quickstart/build.gradle index d1d434d1..929d1afd 100644 --- a/tasks/quickstart/build.gradle +++ b/tasks/quickstart/build.gradle @@ -12,6 +12,6 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:1.33.0' - implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1' + implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-tasks:v1-rev20210709-1.32.1' } \ No newline at end of file From a274c4379bb3c9f515644bcc2045346d93dcc2b7 Mon Sep 17 00:00:00 2001 From: Steven Bazyl Date: Tue, 30 Aug 2022 14:09:44 -0600 Subject: [PATCH 051/152] fix: Remove obsolete files --- .../snippets/src/test/java/CoursesTest.java | 142 ------------------ .../src/main/java/AppDataSnippets.java | 78 ---------- .../src/main/java/ChangeSnippets.java | 64 -------- .../drive_v2/src/main/java/DriveSnippets.java | 96 ------------ .../src/test/java/AppDataSnippetsTest.java | 56 ------- .../src/test/java/ChangeSnippetsTest.java | 47 ------ .../src/test/java/DriveSnippetsTest.java | 66 -------- .../src/test/java/FileSnippetsTest.java | 137 ----------------- .../src/test/java/TeamDriveSnippetsTest.java | 66 -------- .../src/main/java/AppDataSnippets.java | 76 ---------- .../src/main/java/ChangeSnippets.java | 63 -------- .../drive_v3/src/main/java/DriveSnippets.java | 97 ------------ .../src/test/java/AppDataSnippetsTest.java | 57 ------- .../src/test/java/ChangeSnippetsTest.java | 47 ------ .../src/test/java/DriveSnippetsTest.java | 66 -------- .../src/test/java/FileSnippetsTest.java | 137 ----------------- .../src/test/java/TeamDriveSnippetsTest.java | 66 -------- 17 files changed, 1361 deletions(-) delete mode 100644 classroom/snippets/src/test/java/CoursesTest.java delete mode 100644 drive/snippets/drive_v2/src/main/java/AppDataSnippets.java delete mode 100644 drive/snippets/drive_v2/src/main/java/ChangeSnippets.java delete mode 100644 drive/snippets/drive_v2/src/main/java/DriveSnippets.java delete mode 100644 drive/snippets/drive_v2/src/test/java/AppDataSnippetsTest.java delete mode 100644 drive/snippets/drive_v2/src/test/java/ChangeSnippetsTest.java delete mode 100644 drive/snippets/drive_v2/src/test/java/DriveSnippetsTest.java delete mode 100644 drive/snippets/drive_v2/src/test/java/FileSnippetsTest.java delete mode 100644 drive/snippets/drive_v2/src/test/java/TeamDriveSnippetsTest.java delete mode 100644 drive/snippets/drive_v3/src/main/java/AppDataSnippets.java delete mode 100644 drive/snippets/drive_v3/src/main/java/ChangeSnippets.java delete mode 100644 drive/snippets/drive_v3/src/main/java/DriveSnippets.java delete mode 100644 drive/snippets/drive_v3/src/test/java/AppDataSnippetsTest.java delete mode 100644 drive/snippets/drive_v3/src/test/java/ChangeSnippetsTest.java delete mode 100644 drive/snippets/drive_v3/src/test/java/DriveSnippetsTest.java delete mode 100644 drive/snippets/drive_v3/src/test/java/FileSnippetsTest.java delete mode 100644 drive/snippets/drive_v3/src/test/java/TeamDriveSnippetsTest.java diff --git a/classroom/snippets/src/test/java/CoursesTest.java b/classroom/snippets/src/test/java/CoursesTest.java deleted file mode 100644 index 81b6de6e..00000000 --- a/classroom/snippets/src/test/java/CoursesTest.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * 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. - */ - -import com.google.api.services.classroom.Classroom; -import com.google.api.services.classroom.model.Course; -import com.google.api.services.classroom.model.CourseAlias; -import com.google.api.services.classroom.model.Student; -import com.google.api.services.classroom.model.Teacher; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.UUID; - -/** - * Tests for the courses snippets. - */ -public class CoursesTest extends BaseTest { - private Classroom service; - private Course testCourse; - private String otherUser = "erics@homeroomacademy.com"; - - public CoursesTest() throws IOException { - this.service = this.getService(); - } - - @Before - public void setUp() throws IOException { - this.testCourse = createTestCourse("me"); - } - - @After - public void tearDown() throws IOException { - deleteCourse(this.testCourse.getId()); - this.testCourse = null; - } - - @Test - public void testCreateCourse() throws IOException { - Course course = Courses.createCourse(this.service); - Assert.assertNotNull("Course not returned.", course); - deleteCourse(course.getId()); - } - - @Test - public void testGetCourse() throws IOException { - Course course = Courses.getCourse(this.service, this.testCourse.getId()); - Assert.assertNotNull("Course not returned.", course); - Assert.assertEquals("Wrong course returned.", this.testCourse.getId(), course.getId()); - } - - @Test - public void testListCourses() throws IOException { - List courses = Courses.listCourses(this.service); - Assert.assertTrue("No courses returned.", courses.size() > 0); - } - - @Test - public void testUpdateCourse() throws IOException { - Course course = Courses.updateCourse(this.service, this.testCourse.getId()); - Assert.assertNotNull("Course not returned.", course); - Assert.assertEquals("Wrong course returned.", this.testCourse.getId(), course.getId()); - } - - @Test - public void testPatchCourse() throws IOException { - Course course = Courses.patchCourse(this.service, this.testCourse.getId()); - Assert.assertNotNull("Course not returned.", course); - Assert.assertEquals("Wrong course returned.", this.testCourse.getId(), course.getId()); - } - - @Test - public void testCreateCourseAlias() throws IOException { - String alias = "p:" + UUID.randomUUID().toString(); - CourseAlias courseAlias = - Courses.createCourseAlias(this.service, this.testCourse.getId(), alias); - Assert.assertNotNull("Course alias not returned.", courseAlias); - Assert.assertEquals("Wrong course alias returned.", alias, courseAlias.getAlias()); - } - - @Test - public void testListCourseAliases() throws IOException { - List courseAliases = - Courses.listCourseAliases(this.service, this.testCourse.getId()); - Assert.assertTrue("Incorrect number of course aliases returned.", courseAliases.size() == 1); - } - - @Test - public void testAddTeacher() throws IOException { - Teacher teacher = Courses.addTeacher(this.service, this.testCourse.getId(), this.otherUser); - Assert.assertNotNull("Teacher not returned.", teacher); - Assert.assertEquals("Teacher added to wrong course.", this.testCourse.getId(), - teacher.getCourseId()); - } - - @Test - public void testEnrollAsStudent() throws IOException { - Course course = this.createTestCourse(this.otherUser); - Student student = - Courses.enrollAsStudent(this.service, course.getId(), course.getEnrollmentCode()); - this.deleteCourse(course.getId()); - Assert.assertNotNull("Student not returned.", student); - Assert.assertEquals("Student added to wrong course.", course.getId(), - student.getCourseId()); - } - - @Test - public void testBatchAddStudents() throws IOException { - List studentEmails = - Arrays.asList("erics@homeroomacademy.com", "zach@homeroomacademy.com"); - Courses.batchAddStudents(this.service, this.testCourse.getId(), studentEmails); - } - - private Course createTestCourse(String ownerId) throws IOException { - String alias = "p:" + UUID.randomUUID().toString(); - Course course = new Course().setId(alias).setName("Test Course").setSection("Section") - .setOwnerId(ownerId); - return this.service.courses().create(course).execute(); - } - - private void deleteCourse(String courseId) throws IOException { - this.service.courses().delete(courseId).execute(); - } -} diff --git a/drive/snippets/drive_v2/src/main/java/AppDataSnippets.java b/drive/snippets/drive_v2/src/main/java/AppDataSnippets.java deleted file mode 100644 index 6d13d7a4..00000000 --- a/drive/snippets/drive_v2/src/main/java/AppDataSnippets.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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. - */ - -import com.google.api.client.http.FileContent; -import com.google.api.services.drive.Drive; -import com.google.api.services.drive.model.File; -import com.google.api.services.drive.model.FileList; -import com.google.api.services.drive.model.ParentReference; -import java.io.IOException; -import java.util.Collections; - - -public class AppDataSnippets { - - private Drive service; - - public AppDataSnippets(Drive service) { - this.service = service; - } - - public String uploadAppData() throws IOException { - Drive driveService = this.service; - // [START uploadAppData] - File fileMetadata = new File(); - fileMetadata.setTitle("config.json"); - fileMetadata.setParents(Collections.singletonList( - new ParentReference().setId("appDataFolder"))); - java.io.File filePath = new java.io.File("files/config.json"); - FileContent mediaContent = new FileContent("application/json", filePath); - File file = driveService.files().insert(fileMetadata, mediaContent) - .setFields("id") - .execute(); - System.out.println("File ID: " + file.getId()); - // [END uploadAppData] - return file.getId(); - } - - public FileList listAppData() throws IOException { - Drive driveService = this.service; - // [START listAppData] - FileList files = driveService.files().list() - .setSpaces("appDataFolder") - .setFields("nextPageToken, items(id, title)") - .setMaxResults(10) - .execute(); - for (File file : files.getItems()) { - System.out.printf("Found file: %s (%s)\n", - file.getTitle(), file.getId()); - } - // [END listAppData] - return files; - } - - public String fetchAppDataFolder() throws IOException { - Drive driveService = this.service; - // [START fetchAppDataFolder] - File file = driveService.files().get("appDataFolder") - .setFields("id") - .execute(); - System.out.println("Folder ID: " + file.getId()); - // [END fetchAppDataFolder] - return file.getId(); - } - -} diff --git a/drive/snippets/drive_v2/src/main/java/ChangeSnippets.java b/drive/snippets/drive_v2/src/main/java/ChangeSnippets.java deleted file mode 100644 index b3999d88..00000000 --- a/drive/snippets/drive_v2/src/main/java/ChangeSnippets.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 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. - */ - -import com.google.api.services.drive.Drive; -import com.google.api.services.drive.model.Change; -import com.google.api.services.drive.model.ChangeList; -import com.google.api.services.drive.model.StartPageToken; -import java.io.IOException; - -public class ChangeSnippets { - - private Drive service; - - public ChangeSnippets(Drive service) { - this.service = service; - } - - public String fetchStartPageToken() throws IOException { - Drive driveService = this.service; - // [START fetchStartPageToken] - StartPageToken response = driveService.changes() - .getStartPageToken().execute(); - System.out.println("Start token: " + response.getStartPageToken()); - // [END fetchStartPageToken] - return response.getStartPageToken(); - } - - public String fetchChanges(String savedStartPageToken) throws IOException { - Drive driveService = this.service; - // [START fetchChanges] - // Begin with our last saved start token for this user or the - // current token from getStartPageToken() - String pageToken = savedStartPageToken; - while (pageToken != null) { - ChangeList changes = driveService.changes().list() - .setPageToken(pageToken) - .execute(); - for (Change change : changes.getItems()) { - // Process change - System.out.println("Change found for file: " + change.getFileId()); - } - if (changes.getNewStartPageToken() != null) { - // Last page, save this token for the next polling interval - savedStartPageToken = changes.getNewStartPageToken(); - } - pageToken = changes.getNextPageToken(); - } - // [END fetchChanges] - return savedStartPageToken; - } -} diff --git a/drive/snippets/drive_v2/src/main/java/DriveSnippets.java b/drive/snippets/drive_v2/src/main/java/DriveSnippets.java deleted file mode 100644 index a40483bc..00000000 --- a/drive/snippets/drive_v2/src/main/java/DriveSnippets.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * 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. - */ - -import com.google.api.services.drive.model.Drive; -import com.google.api.services.drive.model.DriveList; -import com.google.api.services.drive.model.Permission; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -public class DriveSnippets { - private com.google.api.services.drive.Drive service; - - public DriveSnippets(com.google.api.services.drive.Drive service) { - this.service = service; - } - - public String createDrive() throws IOException { - com.google.api.services.drive.Drive driveService = this.service; - // [START createDrive] - Drive driveMetadata = new Drive(); - driveMetadata.setName("Project Resources"); - String requestId = UUID.randomUUID().toString(); - Drive drive = driveService.drives().insert(requestId, driveMetadata) - .execute(); - System.out.println("Drive ID: " + drive.getId()); - // [END createDrive] - return drive.getId(); - } - - public List recoverDrives(String realUser) - throws IOException { - com.google.api.services.drive.Drive driveService = this.service; - List drives = new ArrayList(); - // [START recoverDrives] - // Find all shared drives without an organizer and add one. - // Note: This example does not capture all cases. Shared drives - // that have an empty group as the sole organizer, or an - // organizer outside the organization are not captured. A - // more exhaustive approach would evaluate each shared drive - // and the associated permissions and groups to ensure an active - // organizer is assigned. - String pageToken = null; - Permission newOrganizerPermission = new Permission() - .setType("user") - .setRole("organizer") - .setValue("user@example.com"); - // [START_EXCLUDE silent] - newOrganizerPermission.setValue(realUser); - // [END_EXCLUDE] - - do { - DriveList result = driveService.drives().list() - .setQ("organizerCount = 0") - .setUseDomainAdminAccess(true) - .setFields("nextPageToken, items(id, name)") - .setPageToken(pageToken) - .execute(); - for (Drive drive : result.getItems()) { - System.out.printf("Found drive without organizer: %s (%s)\n", - drive.getName(), drive.getId()); - // Note: For improved efficiency, consider batching - // permission insert requests - Permission permissionResult = driveService.permissions() - .insert(drive.getId(), newOrganizerPermission) - .setUseDomainAdminAccess(true) - .setSupportsAllDrives(true) - .setFields("id") - .execute(); - System.out.printf("Added organizer permission: %s\n", - permissionResult.getId()); - - } - // [START_EXCLUDE silent] - drives.addAll(result.getItems()); - // [END_EXCLUDE] - pageToken = result.getNextPageToken(); - } while (pageToken != null); - // [END recoverDrives] - return drives; - } -} diff --git a/drive/snippets/drive_v2/src/test/java/AppDataSnippetsTest.java b/drive/snippets/drive_v2/src/test/java/AppDataSnippetsTest.java deleted file mode 100644 index 31726d4e..00000000 --- a/drive/snippets/drive_v2/src/test/java/AppDataSnippetsTest.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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. - */ - -import static org.junit.Assert.assertNotNull; - -import com.google.api.services.drive.model.FileList; -import java.io.IOException; -import java.security.GeneralSecurityException; -import org.junit.Before; -import org.junit.Test; - -public class AppDataSnippetsTest extends BaseTest { - - private AppDataSnippets snippets; - - @Before - public void createSnippets() { - this.snippets = new AppDataSnippets(this.service); - } - - @Test - public void fetchAppDataFolder() throws IOException, GeneralSecurityException { - String id = this.snippets.fetchAppDataFolder(); - assertNotNull(id); - } - - @Test - public void uploadAppData() - throws IOException, GeneralSecurityException { - String id = this.snippets.uploadAppData(); - assertNotNull(id); - deleteFileOnCleanup(id); - } - - @Test - public void listAppData() throws IOException, GeneralSecurityException { - String id = this.snippets.uploadAppData(); - deleteFileOnCleanup(id); - FileList files = this.snippets.listAppData(); - assertNotEquals(0, files.getItems().size()); - } - -} diff --git a/drive/snippets/drive_v2/src/test/java/ChangeSnippetsTest.java b/drive/snippets/drive_v2/src/test/java/ChangeSnippetsTest.java deleted file mode 100644 index 7ad14676..00000000 --- a/drive/snippets/drive_v2/src/test/java/ChangeSnippetsTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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. - */ - -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.IOException; -import org.junit.Before; -import org.junit.Test; - -public class ChangeSnippetsTest extends BaseTest { - - private ChangeSnippets snippets; - - @Before - public void createSnippets() { - this.snippets = new ChangeSnippets(this.service); - } - - @Test - public void fetchStartPageToken() throws IOException { - String token = this.snippets.fetchStartPageToken(); - assertNotNull(token); - } - - @Test - public void fetchChanges() throws IOException { - String startPageToken = this.snippets.fetchStartPageToken(); - this.createTestBlob(); - String newStartPageToken = this.snippets.fetchChanges(startPageToken); - assertNotNull(newStartPageToken); - assertNotEquals(startPageToken, newStartPageToken); - } -} diff --git a/drive/snippets/drive_v2/src/test/java/DriveSnippetsTest.java b/drive/snippets/drive_v2/src/test/java/DriveSnippetsTest.java deleted file mode 100644 index ebe24d24..00000000 --- a/drive/snippets/drive_v2/src/test/java/DriveSnippetsTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * 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. - */ - -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; - -import com.google.api.services.drive.model.Drive; -import com.google.api.services.drive.model.Permission; -import com.google.api.services.drive.model.PermissionList; -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.util.List; -import org.junit.Before; -import org.junit.Test; - -public class DriveSnippetsTest extends BaseTest { - - private DriveSnippets snippets; - - @Before - public void createSnippets() { - this.snippets = new DriveSnippets(this.service); - } - - @Test - public void createDrive() throws IOException, GeneralSecurityException { - String id = this.snippets.createDrive(); - assertNotNull(id); - this.service.drives().delete(id); - } - - @Test - public void recoverDrives() throws IOException { - String id = this.createOrphanedDrive(); - List results = this.snippets.recoverDrives( - "sbazyl@test.appsdevtesting.com"); - assertNotEquals(0, results.size()); - this.service.drives().delete(id).execute(); - } - - private String createOrphanedDrive() throws IOException { - String driveId = this.snippets.createDrive(); - PermissionList response = this.service.permissions().list(driveId) - .setSupportsAllDrives(true) - .execute(); - for (Permission permission : response.getItems()) { - this.service.permissions().delete(driveId, permission.getId()) - .setSupportsAllDrives(true) - .execute(); - } - return driveId; - } -} diff --git a/drive/snippets/drive_v2/src/test/java/FileSnippetsTest.java b/drive/snippets/drive_v2/src/test/java/FileSnippetsTest.java deleted file mode 100644 index 7703c464..00000000 --- a/drive/snippets/drive_v2/src/test/java/FileSnippetsTest.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * 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. - */ - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import com.google.api.services.drive.model.File; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.util.List; -import org.junit.Before; -import org.junit.Test; - -public class FileSnippetsTest extends BaseTest { - - private FileSnippets snippets; - - @Before - public void createSnippets() { - this.snippets = new FileSnippets(this.service); - } - - @Test - public void uploadBasic() throws IOException, GeneralSecurityException { - String id = this.snippets.uploadBasic(); - assertNotNull(id); - deleteFileOnCleanup(id); - } - - @Test - public void uploadRevision() throws IOException, GeneralSecurityException { - String id = this.snippets.uploadBasic(); - assertNotNull(id); - deleteFileOnCleanup(id); - String id2 = this.snippets.uploadRevision(id); - assertEquals(id, id2); - } - - @Test - public void uploadToFolder() throws IOException, GeneralSecurityException { - String folderId = this.snippets.createFolder(); - File file = this.snippets.uploadToFolder(folderId); - assertTrue(file.getParents().get(0).getId().equals(folderId)); - deleteFileOnCleanup(file.getId()); - deleteFileOnCleanup(folderId); - } - - @Test - public void uploadWithConversion() - throws IOException, GeneralSecurityException { - String id = this.snippets.uploadWithConversion(); - assertNotNull(id); - deleteFileOnCleanup(id); - } - - @Test - public void exportPdf() throws IOException, GeneralSecurityException { - String id = createTestDocument(); - ByteArrayOutputStream out = this.snippets.exportPdf(id); - assertEquals("%PDF", out.toString("UTF-8").substring(0, 4)); - } - - @Test - public void downloadFile() throws IOException, GeneralSecurityException { - String id = createTestBlob(); - ByteArrayOutputStream out = this.snippets.downloadFile(id); - byte[] bytes = out.toByteArray(); - assertEquals((byte) 0xFF, bytes[0]); - assertEquals((byte) 0xD8, bytes[1]); - } - - @Test - public void createShortcut() throws IOException, GeneralSecurityException { - String id = this.snippets.createShortcut(); - assertNotNull(id); - deleteFileOnCleanup(id); - } - - @Test - public void touchFile() throws IOException, GeneralSecurityException { - String id = this.createTestBlob(); - long now = System.currentTimeMillis(); - long modifiedTime = this.snippets.touchFile(id, now); - assertEquals(now, modifiedTime); - } - - @Test - public void createFolder() throws IOException, GeneralSecurityException { - String id = this.snippets.createFolder(); - assertNotNull(id); - deleteFileOnCleanup(id); - } - - @Test - public void moveFileToFolder() - throws IOException, GeneralSecurityException { - String folderId = this.snippets.createFolder(); - deleteFileOnCleanup(folderId); - String fileId = this.createTestBlob(); - List parents = this.snippets.moveFileToFolder(fileId, folderId); - assertEquals(1, parents.size()); - assertTrue(parents.contains(folderId)); - } - - @Test - public void searchFiles() - throws IOException, GeneralSecurityException { - this.createTestBlob(); - List files = this.snippets.searchFiles(); - assertNotEquals(0, files.size()); - } - - @Test - public void shareFile() throws IOException { - String fileId = this.createTestBlob(); - List ids = this.snippets.shareFile(fileId, - "user@test.appsdevtesting.com", - "test.appsdevtesting.com"); - assertEquals(2, ids.size()); - } -} diff --git a/drive/snippets/drive_v2/src/test/java/TeamDriveSnippetsTest.java b/drive/snippets/drive_v2/src/test/java/TeamDriveSnippetsTest.java deleted file mode 100644 index a0f53e9c..00000000 --- a/drive/snippets/drive_v2/src/test/java/TeamDriveSnippetsTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * 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. - */ - -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; - -import com.google.api.services.drive.model.Permission; -import com.google.api.services.drive.model.PermissionList; -import com.google.api.services.drive.model.TeamDrive; -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.util.List; -import org.junit.Before; -import org.junit.Test; - -public class TeamDriveSnippetsTest extends BaseTest { - - private TeamDriveSnippets snippets; - - @Before - public void createSnippets() { - this.snippets = new TeamDriveSnippets(this.service); - } - - @Test - public void createTeamDrive() throws IOException, GeneralSecurityException { - String id = this.snippets.createTeamDrive(); - assertNotNull(id); - this.service.teamdrives().delete(id); - } - - @Test - public void recoverTeamDrives() throws IOException { - String id = this.createOrphanedTeamDrive(); - List results = this.snippets.recoverTeamDrives( - "sbazyl@test.appsdevtesting.com"); - assertNotEquals(0, results.size()); - this.service.teamdrives().delete(id).execute(); - } - - private String createOrphanedTeamDrive() throws IOException { - String teamDriveId = this.snippets.createTeamDrive(); - PermissionList response = this.service.permissions().list(teamDriveId) - .setSupportsTeamDrives(true) - .execute(); - for (Permission permission : response.getItems()) { - this.service.permissions().delete(teamDriveId, permission.getId()) - .setSupportsTeamDrives(true) - .execute(); - } - return teamDriveId; - } -} diff --git a/drive/snippets/drive_v3/src/main/java/AppDataSnippets.java b/drive/snippets/drive_v3/src/main/java/AppDataSnippets.java deleted file mode 100644 index 5f75f5c4..00000000 --- a/drive/snippets/drive_v3/src/main/java/AppDataSnippets.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * 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. - */ - -import com.google.api.client.http.FileContent; -import com.google.api.services.drive.Drive; -import com.google.api.services.drive.model.File; -import com.google.api.services.drive.model.FileList; -import java.io.IOException; -import java.util.Collections; - - -public class AppDataSnippets { - - private Drive service; - - public AppDataSnippets(Drive service) { - this.service = service; - } - - public String uploadAppData() throws IOException { - Drive driveService = this.service; - // [START uploadAppData] - File fileMetadata = new File(); - fileMetadata.setName("config.json"); - fileMetadata.setParents(Collections.singletonList("appDataFolder")); - java.io.File filePath = new java.io.File("files/config.json"); - FileContent mediaContent = new FileContent("application/json", filePath); - File file = driveService.files().create(fileMetadata, mediaContent) - .setFields("id") - .execute(); - System.out.println("File ID: " + file.getId()); - // [END uploadAppData] - return file.getId(); - } - - public FileList listAppData() throws IOException { - Drive driveService = this.service; - // [START listAppData] - FileList files = driveService.files().list() - .setSpaces("appDataFolder") - .setFields("nextPageToken, files(id, name)") - .setPageSize(10) - .execute(); - for (File file : files.getFiles()) { - System.out.printf("Found file: %s (%s)\n", - file.getName(), file.getId()); - } - // [END listAppData] - return files; - } - - public String fetchAppDataFolder() throws IOException { - Drive driveService = this.service; - // [START fetchAppDataFolder] - File file = driveService.files().get("appDataFolder") - .setFields("id") - .execute(); - System.out.println("Folder ID: " + file.getId()); - // [END fetchAppDataFolder] - return file.getId(); - } - -} diff --git a/drive/snippets/drive_v3/src/main/java/ChangeSnippets.java b/drive/snippets/drive_v3/src/main/java/ChangeSnippets.java deleted file mode 100644 index 141991bc..00000000 --- a/drive/snippets/drive_v3/src/main/java/ChangeSnippets.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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. - */ - -import com.google.api.services.drive.Drive; -import com.google.api.services.drive.model.Change; -import com.google.api.services.drive.model.ChangeList; -import com.google.api.services.drive.model.StartPageToken; -import java.io.IOException; - -public class ChangeSnippets { - - private Drive service; - - public ChangeSnippets(Drive service) { - this.service = service; - } - - public String fetchStartPageToken() throws IOException { - Drive driveService = this.service; - // [START fetchStartPageToken] - StartPageToken response = driveService.changes() - .getStartPageToken().execute(); - System.out.println("Start token: " + response.getStartPageToken()); - // [END fetchStartPageToken] - return response.getStartPageToken(); - } - - public String fetchChanges(String savedStartPageToken) throws IOException { - Drive driveService = this.service; - // [START fetchChanges] - // Begin with our last saved start token for this user or the - // current token from getStartPageToken() - String pageToken = savedStartPageToken; - while (pageToken != null) { - ChangeList changes = driveService.changes().list(pageToken) - .execute(); - for (Change change : changes.getChanges()) { - // Process change - System.out.println("Change found for file: " + change.getFileId()); - } - if (changes.getNewStartPageToken() != null) { - // Last page, save this token for the next polling interval - savedStartPageToken = changes.getNewStartPageToken(); - } - pageToken = changes.getNextPageToken(); - } - // [END fetchChanges] - return savedStartPageToken; - } -} diff --git a/drive/snippets/drive_v3/src/main/java/DriveSnippets.java b/drive/snippets/drive_v3/src/main/java/DriveSnippets.java deleted file mode 100644 index 9fa22647..00000000 --- a/drive/snippets/drive_v3/src/main/java/DriveSnippets.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * 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. - */ - -import com.google.api.services.drive.model.Drive; -import com.google.api.services.drive.model.DriveList; -import com.google.api.services.drive.model.Permission; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -public class DriveSnippets { - private com.google.api.services.drive.Drive service; - - public DriveSnippets(com.google.api.services.drive.Drive service) { - this.service = service; - } - - public String createDrive() throws IOException { - com.google.api.services.drive.Drive driveService = this.service; - // [START createDrive] - Drive driveMetadata = new Drive(); - driveMetadata.setName("Project Resources"); - String requestId = UUID.randomUUID().toString(); - Drive drive = driveService.drives().create(requestId, - driveMetadata) - .execute(); - System.out.println("Drive ID: " + drive.getId()); - // [END createDrive] - return drive.getId(); - } - - public List recoverDrives(String realUser) - throws IOException { - com.google.api.services.drive.Drive driveService = this.service; - List drives = new ArrayList(); - // [START recoverDrives] - // Find all shared drives without an organizer and add one. - // Note: This example does not capture all cases. Shared drives - // that have an empty group as the sole organizer, or an - // organizer outside the organization are not captured. A - // more exhaustive approach would evaluate each shared drive - // and the associated permissions and groups to ensure an active - // organizer is assigned. - String pageToken = null; - Permission newOrganizerPermission = new Permission() - .setType("user") - .setRole("organizer") - .setEmailAddress("user@example.com"); - // [START_EXCLUDE silent] - newOrganizerPermission.setEmailAddress(realUser); - // [END_EXCLUDE] - - do { - DriveList result = driveService.drives().list() - .setQ("organizerCount = 0") - .setFields("nextPageToken, drives(id, name)") - .setUseDomainAdminAccess(true) - .setPageToken(pageToken) - .execute(); - for (Drive drive : result.getDrives()) { - System.out.printf("Found drive without organizer: %s (%s)\n", - drive.getName(), drive.getId()); - // Note: For improved efficiency, consider batching - // permission insert requests - Permission permissionResult = driveService.permissions() - .create(drive.getId(), newOrganizerPermission) - .setUseDomainAdminAccess(true) - .setSupportsAllDrives(true) - .setFields("id") - .execute(); - System.out.printf("Added organizer permission: %s\n", - permissionResult.getId()); - - } - // [START_EXCLUDE silent] - drives.addAll(result.getDrives()); - // [END_EXCLUDE] - pageToken = result.getNextPageToken(); - } while (pageToken != null); - // [END recoverDrives] - return drives; - } -} diff --git a/drive/snippets/drive_v3/src/test/java/AppDataSnippetsTest.java b/drive/snippets/drive_v3/src/test/java/AppDataSnippetsTest.java deleted file mode 100644 index 446af287..00000000 --- a/drive/snippets/drive_v3/src/test/java/AppDataSnippetsTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * 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. - */ - -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; - -import com.google.api.services.drive.model.FileList; -import java.io.IOException; -import java.security.GeneralSecurityException; -import org.junit.Before; -import org.junit.Test; - -public class AppDataSnippetsTest extends BaseTest { - - private AppDataSnippets snippets; - - @Before - public void createSnippets() { - this.snippets = new AppDataSnippets(this.service); - } - - @Test - public void fetchAppDataFolder() throws IOException, GeneralSecurityException { - String id = this.snippets.fetchAppDataFolder(); - assertNotNull(id); - } - - @Test - public void uploadAppData() - throws IOException, GeneralSecurityException { - String id = this.snippets.uploadAppData(); - assertNotNull(id); - deleteFileOnCleanup(id); - } - - @Test - public void listAppData() throws IOException, GeneralSecurityException { - String id = this.snippets.uploadAppData(); - deleteFileOnCleanup(id); - FileList files = this.snippets.listAppData(); - assertNotEquals(0, files.getFiles().size()); - } - -} diff --git a/drive/snippets/drive_v3/src/test/java/ChangeSnippetsTest.java b/drive/snippets/drive_v3/src/test/java/ChangeSnippetsTest.java deleted file mode 100644 index 7ad14676..00000000 --- a/drive/snippets/drive_v3/src/test/java/ChangeSnippetsTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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. - */ - -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.IOException; -import org.junit.Before; -import org.junit.Test; - -public class ChangeSnippetsTest extends BaseTest { - - private ChangeSnippets snippets; - - @Before - public void createSnippets() { - this.snippets = new ChangeSnippets(this.service); - } - - @Test - public void fetchStartPageToken() throws IOException { - String token = this.snippets.fetchStartPageToken(); - assertNotNull(token); - } - - @Test - public void fetchChanges() throws IOException { - String startPageToken = this.snippets.fetchStartPageToken(); - this.createTestBlob(); - String newStartPageToken = this.snippets.fetchChanges(startPageToken); - assertNotNull(newStartPageToken); - assertNotEquals(startPageToken, newStartPageToken); - } -} diff --git a/drive/snippets/drive_v3/src/test/java/DriveSnippetsTest.java b/drive/snippets/drive_v3/src/test/java/DriveSnippetsTest.java deleted file mode 100644 index e32dc904..00000000 --- a/drive/snippets/drive_v3/src/test/java/DriveSnippetsTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * 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. - */ - -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; - -import com.google.api.services.drive.model.Drive; -import com.google.api.services.drive.model.Permission; -import com.google.api.services.drive.model.PermissionList; -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.util.List; -import org.junit.Before; -import org.junit.Test; - -public class DriveSnippetsTest extends BaseTest { - - private DriveSnippets snippets; - - @Before - public void createSnippets() { - this.snippets = new DriveSnippets(this.service); - } - - @Test - public void createDrive() throws IOException, GeneralSecurityException { - String id = this.snippets.createDrive(); - assertNotNull(id); - this.service.drives().delete(id); - } - - @Test - public void recoverDrives() throws IOException { - String id = this.createOrphanedDrive(); - List results = this.snippets.recoverDrives( - "sbazyl@test.appsdevtesting.com"); - assertNotEquals(0, results.size()); - this.service.drives().delete(id).execute(); - } - - private String createOrphanedDrive() throws IOException { - String driveId = this.snippets.createDrive(); - PermissionList response = this.service.permissions().list(driveId) - .setSupportsAllDrives(true) - .execute(); - for (Permission permission : response.getPermissions()) { - this.service.permissions().delete(driveId, permission.getId()) - .setSupportsAllDrives(true) - .execute(); - } - return driveId; - } -} diff --git a/drive/snippets/drive_v3/src/test/java/FileSnippetsTest.java b/drive/snippets/drive_v3/src/test/java/FileSnippetsTest.java deleted file mode 100644 index 383a7935..00000000 --- a/drive/snippets/drive_v3/src/test/java/FileSnippetsTest.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * 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. - */ - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import com.google.api.services.drive.model.File; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.util.List; -import org.junit.Before; -import org.junit.Test; - -public class FileSnippetsTest extends BaseTest { - - private FileSnippets snippets; - - @Before - public void createSnippets() { - this.snippets = new FileSnippets(this.service); - } - - @Test - public void uploadBasic() throws IOException, GeneralSecurityException { - String id = this.snippets.uploadBasic(); - assertNotNull(id); - deleteFileOnCleanup(id); - } - - @Test - public void uploadRevision() throws IOException, GeneralSecurityException { - String id = this.snippets.uploadBasic(); - assertNotNull(id); - deleteFileOnCleanup(id); - String id2 = this.snippets.uploadRevision(id); - assertEquals(id, id2); - } - - @Test - public void uploadToFolder() throws IOException, GeneralSecurityException { - String folderId = this.snippets.createFolder(); - File file = this.snippets.uploadToFolder(folderId); - assertTrue(file.getParents().contains(folderId)); - deleteFileOnCleanup(file.getId()); - deleteFileOnCleanup(folderId); - } - - @Test - public void uploadWithConversion() - throws IOException, GeneralSecurityException { - String id = this.snippets.uploadWithConversion(); - assertNotNull(id); - deleteFileOnCleanup(id); - } - - @Test - public void exportPdf() throws IOException, GeneralSecurityException { - String id = createTestDocument(); - ByteArrayOutputStream out = this.snippets.exportPdf(id); - assertEquals("%PDF", out.toString("UTF-8").substring(0, 4)); - } - - @Test - public void downloadFile() throws IOException, GeneralSecurityException { - String id = createTestBlob(); - ByteArrayOutputStream out = this.snippets.downloadFile(id); - byte[] bytes = out.toByteArray(); - assertEquals((byte) 0xFF, bytes[0]); - assertEquals((byte) 0xD8, bytes[1]); - } - - @Test - public void createShortcut() throws IOException, GeneralSecurityException { - String id = this.snippets.createShortcut(); - assertNotNull(id); - deleteFileOnCleanup(id); - } - - @Test - public void touchFile() throws IOException, GeneralSecurityException { - String id = this.createTestBlob(); - long now = System.currentTimeMillis(); - long modifiedTime = this.snippets.touchFile(id, now); - assertEquals(now, modifiedTime); - } - - @Test - public void createFolder() throws IOException, GeneralSecurityException { - String id = this.snippets.createFolder(); - assertNotNull(id); - deleteFileOnCleanup(id); - } - - @Test - public void moveFileToFolder() - throws IOException, GeneralSecurityException { - String folderId = this.snippets.createFolder(); - deleteFileOnCleanup(folderId); - String fileId = this.createTestBlob(); - List parents = this.snippets.moveFileToFolder(fileId, folderId); - assertTrue(parents.contains(folderId)); - assertEquals(1, parents.size()); - } - - @Test - public void searchFiles() - throws IOException, GeneralSecurityException { - this.createTestBlob(); - List files = this.snippets.searchFiles(); - assertNotEquals(0, files.size()); - } - - @Test - public void shareFile() throws IOException { - String fileId = this.createTestBlob(); - List ids = this.snippets.shareFile(fileId, - "user@test.appsdevtesting.com", - "test.appsdevtesting.com"); - assertEquals(2, ids.size()); - } -} diff --git a/drive/snippets/drive_v3/src/test/java/TeamDriveSnippetsTest.java b/drive/snippets/drive_v3/src/test/java/TeamDriveSnippetsTest.java deleted file mode 100644 index b59b235a..00000000 --- a/drive/snippets/drive_v3/src/test/java/TeamDriveSnippetsTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * 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. - */ - -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; - -import com.google.api.services.drive.model.Permission; -import com.google.api.services.drive.model.PermissionList; -import com.google.api.services.drive.model.TeamDrive; -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.util.List; -import org.junit.Before; -import org.junit.Test; - -public class TeamDriveSnippetsTest extends BaseTest { - - private TeamDriveSnippets snippets; - - @Before - public void createSnippets() { - this.snippets = new TeamDriveSnippets(this.service); - } - - @Test - public void createTeamDrive() throws IOException, GeneralSecurityException { - String id = this.snippets.createTeamDrive(); - assertNotNull(id); - this.service.teamdrives().delete(id); - } - - @Test - public void recoverTeamDrives() throws IOException { - String id = this.createOrphanedTeamDrive(); - List results = this.snippets.recoverTeamDrives( - "sbazyl@test.appsdevtesting.com"); - assertNotEquals(0, results.size()); - this.service.teamdrives().delete(id).execute(); - } - - private String createOrphanedTeamDrive() throws IOException { - String teamDriveId = this.snippets.createTeamDrive(); - PermissionList response = this.service.permissions().list(teamDriveId) - .setSupportsTeamDrives(true) - .execute(); - for (Permission permission : response.getPermissions()) { - this.service.permissions().delete(teamDriveId, permission.getId()) - .setSupportsTeamDrives(true) - .execute(); - } - return teamDriveId; - } -} From 5877f2c40642f2b13a1e392cb0de961e1cc2d7b4 Mon Sep 17 00:00:00 2001 From: Steven Bazyl Date: Tue, 30 Aug 2022 14:41:15 -0600 Subject: [PATCH 052/152] fix: Add missing hamcrest dependency --- gmail/snippets/build.gradle | 1 + 1 file changed, 1 insertion(+) diff --git a/gmail/snippets/build.gradle b/gmail/snippets/build.gradle index 5e89d634..2881c148 100644 --- a/gmail/snippets/build.gradle +++ b/gmail/snippets/build.gradle @@ -11,4 +11,5 @@ dependencies { implementation 'org.apache.commons:commons-csv:1.9.0' testImplementation 'junit:junit:4.13.2' testImplementation 'org.mockito:mockito-inline:4.7.0' + testImplementation 'org.hamcrest:hamcrest:2.2' } From 4eec0616549ecd59bed4045048e0cd753c1b8f57 Mon Sep 17 00:00:00 2001 From: Steven Bazyl Date: Tue, 30 Aug 2022 14:52:19 -0600 Subject: [PATCH 053/152] fix: Add missing import --- drive/snippets/drive_v2/src/test/java/TestListAppdata.java | 1 + 1 file changed, 1 insertion(+) diff --git a/drive/snippets/drive_v2/src/test/java/TestListAppdata.java b/drive/snippets/drive_v2/src/test/java/TestListAppdata.java index 3aa6558b..a6baf68c 100644 --- a/drive/snippets/drive_v2/src/test/java/TestListAppdata.java +++ b/drive/snippets/drive_v2/src/test/java/TestListAppdata.java @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +import static org.junit.Assert.assertNotEquals; import com.google.api.services.drive.model.FileList; import java.io.IOException; import java.security.GeneralSecurityException; From 4d0174d516835e95fe732cb7f57da6896c57f86b Mon Sep 17 00:00:00 2001 From: Steve Bazyl Date: Tue, 30 Aug 2022 16:20:31 -0600 Subject: [PATCH 054/152] chore: update maven plugin --- calendar/sync/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/calendar/sync/pom.xml b/calendar/sync/pom.xml index cfc48a4b..f788e4a1 100644 --- a/calendar/sync/pom.xml +++ b/calendar/sync/pom.xml @@ -30,7 +30,7 @@ TODO: Determine the final URL. 2014 - 2.0.9 + 3.0.0 @@ -40,8 +40,8 @@ maven-compiler-plugin 3.10.1 - 1.6 - 1.6 + 1.8 + 1.8 From 88165e8561c2d7b27e26b8e4feeaab5b1ebf023b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:21:43 -0600 Subject: [PATCH 055/152] Bump exec-maven-plugin from 1.1 to 3.1.0 in /calendar/sync (#285) Bumps [exec-maven-plugin](https://github.com/mojohaus/exec-maven-plugin) from 1.1 to 3.1.0. - [Release notes](https://github.com/mojohaus/exec-maven-plugin/releases) - [Commits](https://github.com/mojohaus/exec-maven-plugin/compare/exec-maven-plugin-1.1...exec-maven-plugin-3.1.0) --- updated-dependencies: - dependency-name: org.codehaus.mojo:exec-maven-plugin dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- calendar/sync/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/calendar/sync/pom.xml b/calendar/sync/pom.xml index f788e4a1..f35f8cc1 100644 --- a/calendar/sync/pom.xml +++ b/calendar/sync/pom.xml @@ -47,7 +47,7 @@ org.codehaus.mojo exec-maven-plugin - 1.1 + 3.1.0 From 5c5338b45862bdf25556260be32b4b449f69ae71 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:51:04 -0600 Subject: [PATCH 056/152] Bump junit from 4.12 to 4.13.2 in /drive/snippets/drive_v3 (#342) Bumps [junit](https://github.com/junit-team/junit4) from 4.12 to 4.13.2. - [Release notes](https://github.com/junit-team/junit4/releases) - [Changelog](https://github.com/junit-team/junit4/blob/main/doc/ReleaseNotes4.12.md) - [Commits](https://github.com/junit-team/junit4/compare/r4.12...r4.13.2) --- updated-dependencies: - dependency-name: junit:junit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- drive/snippets/drive_v3/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drive/snippets/drive_v3/build.gradle b/drive/snippets/drive_v3/build.gradle index 0343fc54..ade01244 100644 --- a/drive/snippets/drive_v3/build.gradle +++ b/drive/snippets/drive_v3/build.gradle @@ -8,7 +8,7 @@ dependencies { implementation 'com.google.api-client:google-api-client:1.23.0' implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' implementation 'com.google.code.gson:gson:2.4' - testImplementation 'junit:junit:4.12' + testImplementation 'junit:junit:4.13.2' } test { From a795407379e070697d9bc7dee78508555cd12428 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:51:06 -0600 Subject: [PATCH 057/152] Bump junit from 4.12 to 4.13.2 in /drive/snippets/drive_v2 (#339) Bumps [junit](https://github.com/junit-team/junit4) from 4.12 to 4.13.2. - [Release notes](https://github.com/junit-team/junit4/releases) - [Changelog](https://github.com/junit-team/junit4/blob/main/doc/ReleaseNotes4.12.md) - [Commits](https://github.com/junit-team/junit4/compare/r4.12...r4.13.2) --- updated-dependencies: - dependency-name: junit:junit dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- drive/snippets/drive_v2/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drive/snippets/drive_v2/build.gradle b/drive/snippets/drive_v2/build.gradle index a9b22fb3..6a111d9a 100644 --- a/drive/snippets/drive_v2/build.gradle +++ b/drive/snippets/drive_v2/build.gradle @@ -10,7 +10,7 @@ dependencies { implementation 'com.google.auth:google-auth-library-oauth2-http:1.3.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1' implementation 'com.google.code.gson:gson:2.4' - testImplementation 'junit:junit:4.12' + testImplementation 'junit:junit:4.13.2' } test { From 0dc73faedbfbbb8295ddc438a234a73cfcfd4b55 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:51:08 -0600 Subject: [PATCH 058/152] Bump google-api-client from 1.33.0 to 2.0.0 in /vault/quickstart (#341) Bumps [google-api-client](https://github.com/googleapis/google-api-java-client) from 1.33.0 to 2.0.0. - [Release notes](https://github.com/googleapis/google-api-java-client/releases) - [Changelog](https://github.com/googleapis/google-api-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-api-java-client/compare/v1.33.0...v2.0.0) --- updated-dependencies: - dependency-name: com.google.api-client:google-api-client dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- vault/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vault/quickstart/build.gradle b/vault/quickstart/build.gradle index 26e72d92..d60d73f4 100644 --- a/vault/quickstart/build.gradle +++ b/vault/quickstart/build.gradle @@ -11,7 +11,7 @@ repositories { } dependencies { - implementation 'com.google.api-client:google-api-client:1.33.0' + implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-vault:v1-rev20211101-1.32.1' } From 38e5e3bcb26658c91ab7ec59f5162742c323f35f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:51:10 -0600 Subject: [PATCH 059/152] Bump google-api-client from 1.33.0 to 2.0.0 in /gmail/quickstart (#340) Bumps [google-api-client](https://github.com/googleapis/google-api-java-client) from 1.33.0 to 2.0.0. - [Release notes](https://github.com/googleapis/google-api-java-client/releases) - [Changelog](https://github.com/googleapis/google-api-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-api-java-client/compare/v1.33.0...v2.0.0) --- updated-dependencies: - dependency-name: com.google.api-client:google-api-client dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- gmail/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gmail/quickstart/build.gradle b/gmail/quickstart/build.gradle index ce120ab6..9de1d325 100644 --- a/gmail/quickstart/build.gradle +++ b/gmail/quickstart/build.gradle @@ -11,7 +11,7 @@ repositories { } dependencies { - implementation 'com.google.api-client:google-api-client:1.33.0' + implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-gmail:v1-rev20211108-1.32.1' } From fc8277e1f68875efacf7629a82f5131e1d57310e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:51:13 -0600 Subject: [PATCH 060/152] Bump google-api-client from 1.33.0 to 2.0.0 in /docs/outputJSON (#314) Bumps [google-api-client](https://github.com/googleapis/google-api-java-client) from 1.33.0 to 2.0.0. - [Release notes](https://github.com/googleapis/google-api-java-client/releases) - [Changelog](https://github.com/googleapis/google-api-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-api-java-client/compare/v1.33.0...v2.0.0) --- updated-dependencies: - dependency-name: com.google.api-client:google-api-client dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- docs/outputJSON/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/outputJSON/build.gradle b/docs/outputJSON/build.gradle index 1a1343c3..32220cf2 100644 --- a/docs/outputJSON/build.gradle +++ b/docs/outputJSON/build.gradle @@ -11,7 +11,7 @@ repositories { } dependencies { - implementation 'com.google.api-client:google-api-client:1.33.0' + implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-docs:v1-rev20210707-1.32.1' implementation group: 'com.google.code.gson', name: 'gson', version: '2.9.1' From e1eb9e47edf41c22f9f147cff11a12512542d668 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:51:15 -0600 Subject: [PATCH 061/152] Bump google-api-client from 1.33.0 to 2.0.0 in /slides/quickstart (#308) Bumps [google-api-client](https://github.com/googleapis/google-api-java-client) from 1.33.0 to 2.0.0. - [Release notes](https://github.com/googleapis/google-api-java-client/releases) - [Changelog](https://github.com/googleapis/google-api-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-api-java-client/compare/v1.33.0...v2.0.0) --- updated-dependencies: - dependency-name: com.google.api-client:google-api-client dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- slides/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/slides/quickstart/build.gradle b/slides/quickstart/build.gradle index d4eac491..05916c6f 100644 --- a/slides/quickstart/build.gradle +++ b/slides/quickstart/build.gradle @@ -11,7 +11,7 @@ repositories { } dependencies { - implementation 'com.google.api-client:google-api-client:1.33.0' + implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-slides:v1-rev20210820-1.32.1' } From f6db2027a9b0d9bb6de529c719e036a4d9081270 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:51:17 -0600 Subject: [PATCH 062/152] Bump google-api-client in /adminSDK/directory/quickstart (#295) Bumps [google-api-client](https://github.com/googleapis/google-api-java-client) from 1.33.0 to 2.0.0. - [Release notes](https://github.com/googleapis/google-api-java-client/releases) - [Changelog](https://github.com/googleapis/google-api-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-api-java-client/compare/v1.33.0...v2.0.0) --- updated-dependencies: - dependency-name: com.google.api-client:google-api-client dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- adminSDK/directory/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adminSDK/directory/quickstart/build.gradle b/adminSDK/directory/quickstart/build.gradle index 3504f0b0..c2dfbf80 100644 --- a/adminSDK/directory/quickstart/build.gradle +++ b/adminSDK/directory/quickstart/build.gradle @@ -11,7 +11,7 @@ repositories { } dependencies { - implementation 'com.google.api-client:google-api-client:1.33.0' + implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-admin-directory:directory_v1-rev118-1.25.0' } From ef296bc7c30fa487d55079f2561fca0596d8aa24 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:51:19 -0600 Subject: [PATCH 063/152] Bump google-api-client from 1.33.0 to 2.0.0 in /appsScript/quickstart (#307) Bumps [google-api-client](https://github.com/googleapis/google-api-java-client) from 1.33.0 to 2.0.0. - [Release notes](https://github.com/googleapis/google-api-java-client/releases) - [Changelog](https://github.com/googleapis/google-api-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-api-java-client/compare/v1.33.0...v2.0.0) --- updated-dependencies: - dependency-name: com.google.api-client:google-api-client dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- appsScript/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/appsScript/quickstart/build.gradle b/appsScript/quickstart/build.gradle index 41dd51b6..f26ede54 100644 --- a/appsScript/quickstart/build.gradle +++ b/appsScript/quickstart/build.gradle @@ -11,7 +11,7 @@ repositories { } dependencies { - implementation 'com.google.api-client:google-api-client:1.33.0' + implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-script:v1-rev20210703-1.32.1' } From d38841c9295a5496a1402ef9ae87fdda7243cdf1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:51:22 -0600 Subject: [PATCH 064/152] Bump google-api-client from 1.33.0 to 2.0.0 in /calendar/quickstart (#300) Bumps [google-api-client](https://github.com/googleapis/google-api-java-client) from 1.33.0 to 2.0.0. - [Release notes](https://github.com/googleapis/google-api-java-client/releases) - [Changelog](https://github.com/googleapis/google-api-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-api-java-client/compare/v1.33.0...v2.0.0) --- updated-dependencies: - dependency-name: com.google.api-client:google-api-client dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- calendar/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/calendar/quickstart/build.gradle b/calendar/quickstart/build.gradle index deb17b9e..923ec144 100644 --- a/calendar/quickstart/build.gradle +++ b/calendar/quickstart/build.gradle @@ -11,7 +11,7 @@ repositories { } dependencies { - implementation 'com.google.api-client:google-api-client:1.33.0' + implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-calendar:v3-rev20211026-1.32.1' } From 9a0422723e59cd272ec4283030ff932b8e198850 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:51:24 -0600 Subject: [PATCH 065/152] Bump google-api-client from 1.33.0 to 2.0.0 in /classroom/quickstart (#301) Bumps [google-api-client](https://github.com/googleapis/google-api-java-client) from 1.33.0 to 2.0.0. - [Release notes](https://github.com/googleapis/google-api-java-client/releases) - [Changelog](https://github.com/googleapis/google-api-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-api-java-client/compare/v1.33.0...v2.0.0) --- updated-dependencies: - dependency-name: com.google.api-client:google-api-client dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- classroom/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/classroom/quickstart/build.gradle b/classroom/quickstart/build.gradle index 663c1057..7773fab2 100644 --- a/classroom/quickstart/build.gradle +++ b/classroom/quickstart/build.gradle @@ -11,7 +11,7 @@ repositories { } dependencies { - implementation 'com.google.api-client:google-api-client:1.33.0' + implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-classroom:v1-rev20211029-1.32.1' } From 52cd4e6021248f99faa3c27aa82cf2c82860a436 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:51:26 -0600 Subject: [PATCH 066/152] Bump google-api-client in /adminSDK/reports/quickstart (#296) Bumps [google-api-client](https://github.com/googleapis/google-api-java-client) from 1.33.0 to 2.0.0. - [Release notes](https://github.com/googleapis/google-api-java-client/releases) - [Changelog](https://github.com/googleapis/google-api-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-api-java-client/compare/v1.33.0...v2.0.0) --- updated-dependencies: - dependency-name: com.google.api-client:google-api-client dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- adminSDK/reports/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adminSDK/reports/quickstart/build.gradle b/adminSDK/reports/quickstart/build.gradle index f5ae3c7e..450d681a 100644 --- a/adminSDK/reports/quickstart/build.gradle +++ b/adminSDK/reports/quickstart/build.gradle @@ -11,7 +11,7 @@ repositories { } dependencies { - implementation 'com.google.api-client:google-api-client:1.33.0' + implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-admin-reports:reports_v1-rev89-1.25.0' } From 323089fdcbb60f8e6e876a28c45463e70294e88f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:51:28 -0600 Subject: [PATCH 067/152] Bump google-api-client from 1.34.1 to 2.0.0 in /classroom/snippets (#269) Bumps [google-api-client](https://github.com/googleapis/google-api-java-client) from 1.34.1 to 2.0.0. - [Release notes](https://github.com/googleapis/google-api-java-client/releases) - [Changelog](https://github.com/googleapis/google-api-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-api-java-client/compare/v1.34.1...v2.0.0) --- updated-dependencies: - dependency-name: com.google.api-client:google-api-client dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- classroom/snippets/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/classroom/snippets/build.gradle b/classroom/snippets/build.gradle index f9591fca..f1deeb31 100644 --- a/classroom/snippets/build.gradle +++ b/classroom/snippets/build.gradle @@ -6,7 +6,7 @@ repositories { } dependencies { - implementation 'com.google.api-client:google-api-client:1.34.1' + implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' implementation 'com.google.apis:google-api-services-classroom:v1-rev20220323-1.32.1' testImplementation 'junit:junit:4.13.2' From 4eab80287bf95eb8d79fca7f38d4c740f736989b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:51:31 -0600 Subject: [PATCH 068/152] Bump google-api-client in /drive/activity/quickstart (#278) Bumps [google-api-client](https://github.com/googleapis/google-api-java-client) from 1.33.0 to 2.0.0. - [Release notes](https://github.com/googleapis/google-api-java-client/releases) - [Changelog](https://github.com/googleapis/google-api-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-api-java-client/compare/v1.33.0...v2.0.0) --- updated-dependencies: - dependency-name: com.google.api-client:google-api-client dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- drive/activity/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drive/activity/quickstart/build.gradle b/drive/activity/quickstart/build.gradle index 583730c7..de3ddb63 100644 --- a/drive/activity/quickstart/build.gradle +++ b/drive/activity/quickstart/build.gradle @@ -11,7 +11,7 @@ repositories { } dependencies { - implementation 'com.google.api-client:google-api-client:1.33.0' + implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-appsactivity:v1-rev20200128-1.30.10' } From b4b350cf6fed83665d0ba61bfdb22f7c429884bf Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:51:33 -0600 Subject: [PATCH 069/152] Bump google-api-client from 1.33.0 to 2.0.0 in /drive/quickstart (#280) Bumps [google-api-client](https://github.com/googleapis/google-api-java-client) from 1.33.0 to 2.0.0. - [Release notes](https://github.com/googleapis/google-api-java-client/releases) - [Changelog](https://github.com/googleapis/google-api-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-api-java-client/compare/v1.33.0...v2.0.0) --- updated-dependencies: - dependency-name: com.google.api-client:google-api-client dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- drive/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drive/quickstart/build.gradle b/drive/quickstart/build.gradle index 0cc1a504..ba1f28b5 100644 --- a/drive/quickstart/build.gradle +++ b/drive/quickstart/build.gradle @@ -11,7 +11,7 @@ repositories { } dependencies { - implementation 'com.google.api-client:google-api-client:1.33.0' + implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-drive:v3-rev20211107-1.32.1' } From fda3bf3992ac4e00bf50525f1a20ea01ba3bf262 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:51:35 -0600 Subject: [PATCH 070/152] Bump google-api-client from 1.33.0 to 2.0.0 in /people/quickstart (#276) Bumps [google-api-client](https://github.com/googleapis/google-api-java-client) from 1.33.0 to 2.0.0. - [Release notes](https://github.com/googleapis/google-api-java-client/releases) - [Changelog](https://github.com/googleapis/google-api-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-api-java-client/compare/v1.33.0...v2.0.0) --- updated-dependencies: - dependency-name: com.google.api-client:google-api-client dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- people/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/people/quickstart/build.gradle b/people/quickstart/build.gradle index 8592e052..540e613c 100644 --- a/people/quickstart/build.gradle +++ b/people/quickstart/build.gradle @@ -12,7 +12,7 @@ repositories { } dependencies { - implementation 'com.google.api-client:google-api-client:1.33.0' + implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-people:v1-rev20210903-1.32.1' } From 5eb04cab3ad46e92bc0503b10817df4cbf64ee62 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:51:38 -0600 Subject: [PATCH 071/152] Bump google-api-client from 1.33.0 to 2.0.0 in /docs/quickstart (#273) Bumps [google-api-client](https://github.com/googleapis/google-api-java-client) from 1.33.0 to 2.0.0. - [Release notes](https://github.com/googleapis/google-api-java-client/releases) - [Changelog](https://github.com/googleapis/google-api-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-api-java-client/compare/v1.33.0...v2.0.0) --- updated-dependencies: - dependency-name: com.google.api-client:google-api-client dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- docs/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/quickstart/build.gradle b/docs/quickstart/build.gradle index 6583c267..1b5fed39 100644 --- a/docs/quickstart/build.gradle +++ b/docs/quickstart/build.gradle @@ -11,7 +11,7 @@ repositories { } dependencies { - implementation 'com.google.api-client:google-api-client:1.33.0' + implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-docs:v1-rev20210707-1.32.1' } From 112b1d8312b8a7f144e3b863ca82715a9dd4e44f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:51:39 -0600 Subject: [PATCH 072/152] Bump google-api-client in /adminSDK/reseller/quickstart (#266) Bumps [google-api-client](https://github.com/googleapis/google-api-java-client) from 1.33.0 to 2.0.0. - [Release notes](https://github.com/googleapis/google-api-java-client/releases) - [Changelog](https://github.com/googleapis/google-api-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-api-java-client/compare/v1.33.0...v2.0.0) --- updated-dependencies: - dependency-name: com.google.api-client:google-api-client dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- adminSDK/reseller/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adminSDK/reseller/quickstart/build.gradle b/adminSDK/reseller/quickstart/build.gradle index 8903a301..20e39b10 100644 --- a/adminSDK/reseller/quickstart/build.gradle +++ b/adminSDK/reseller/quickstart/build.gradle @@ -11,7 +11,7 @@ repositories { } dependencies { - implementation 'com.google.api-client:google-api-client:1.33.0' + implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-reseller:v1-rev20211106-1.32.1' } From a2c2e4b9d46f33588768149986389807e63e8c31 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:51:42 -0600 Subject: [PATCH 073/152] Bump google-api-client from 1.33.0 to 2.0.0 in /sheets/quickstart (#263) Bumps [google-api-client](https://github.com/googleapis/google-api-java-client) from 1.33.0 to 2.0.0. - [Release notes](https://github.com/googleapis/google-api-java-client/releases) - [Changelog](https://github.com/googleapis/google-api-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-api-java-client/compare/v1.33.0...v2.0.0) --- updated-dependencies: - dependency-name: com.google.api-client:google-api-client dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- sheets/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sheets/quickstart/build.gradle b/sheets/quickstart/build.gradle index dbf63a92..4dff318c 100644 --- a/sheets/quickstart/build.gradle +++ b/sheets/quickstart/build.gradle @@ -11,7 +11,7 @@ repositories { } dependencies { - implementation 'com.google.api-client:google-api-client:1.33.0' + implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-sheets:v4-rev20210629-1.32.1' } From 653aa48009e8a0f0b9adfd8f7178c8e5afd635a5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:51:46 -0600 Subject: [PATCH 074/152] Bump google-api-client from 1.33.0 to 2.0.0 in /calendar/sync (#262) Bumps [google-api-client](https://github.com/googleapis/google-api-java-client) from 1.33.0 to 2.0.0. - [Release notes](https://github.com/googleapis/google-api-java-client/releases) - [Changelog](https://github.com/googleapis/google-api-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-api-java-client/compare/v1.33.0...v2.0.0) --- updated-dependencies: - dependency-name: com.google.api-client:google-api-client dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- calendar/sync/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/calendar/sync/pom.xml b/calendar/sync/pom.xml index f35f8cc1..01f4b039 100644 --- a/calendar/sync/pom.xml +++ b/calendar/sync/pom.xml @@ -77,7 +77,7 @@ com.google.api-client google-api-client - 1.33.0 + 2.0.0 com.google.http-client From 3fc1d73e79a277479d37af6ef91154a04f87ed64 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:51:48 -0600 Subject: [PATCH 075/152] chore(deps): bump google-api-client in /adminSDK/alertcenter/quickstart (#346) Bumps [google-api-client](https://github.com/googleapis/google-api-java-client) from 1.33.0 to 2.0.0. - [Release notes](https://github.com/googleapis/google-api-java-client/releases) - [Changelog](https://github.com/googleapis/google-api-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-api-java-client/compare/v1.33.0...v2.0.0) --- updated-dependencies: - dependency-name: com.google.api-client:google-api-client dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- adminSDK/alertcenter/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adminSDK/alertcenter/quickstart/build.gradle b/adminSDK/alertcenter/quickstart/build.gradle index ddd97edc..c5be324b 100644 --- a/adminSDK/alertcenter/quickstart/build.gradle +++ b/adminSDK/alertcenter/quickstart/build.gradle @@ -12,7 +12,7 @@ repositories { } dependencies { - implementation 'com.google.api-client:google-api-client:1.33.0' + implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' implementation 'com.google.apis:google-api-services-alertcenter:v1beta1-rev20211012-1.32.1' } \ No newline at end of file From 4cd8181cca329e63beaca759f8fc42a6bdd2ba89 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:51:52 -0600 Subject: [PATCH 076/152] chore(deps): bump google-api-client in /tasks/quickstart (#344) Bumps [google-api-client](https://github.com/googleapis/google-api-java-client) from 1.33.0 to 2.0.0. - [Release notes](https://github.com/googleapis/google-api-java-client/releases) - [Changelog](https://github.com/googleapis/google-api-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-api-java-client/compare/v1.33.0...v2.0.0) --- updated-dependencies: - dependency-name: com.google.api-client:google-api-client dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- tasks/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tasks/quickstart/build.gradle b/tasks/quickstart/build.gradle index 929d1afd..c8f052b1 100644 --- a/tasks/quickstart/build.gradle +++ b/tasks/quickstart/build.gradle @@ -11,7 +11,7 @@ repositories { } dependencies { - implementation 'com.google.api-client:google-api-client:1.33.0' + implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-tasks:v1-rev20210709-1.32.1' } \ No newline at end of file From 1d7f663c6765e26c9ce249c1f31d7a18181fa534 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:51:54 -0600 Subject: [PATCH 077/152] Bump google-api-client in /drive/activity-v2/quickstart (#343) Bumps [google-api-client](https://github.com/googleapis/google-api-java-client) from 1.33.0 to 2.0.0. - [Release notes](https://github.com/googleapis/google-api-java-client/releases) - [Changelog](https://github.com/googleapis/google-api-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-api-java-client/compare/v1.33.0...v2.0.0) --- updated-dependencies: - dependency-name: com.google.api-client:google-api-client dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- drive/activity-v2/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drive/activity-v2/quickstart/build.gradle b/drive/activity-v2/quickstart/build.gradle index 8cc523f1..8663a975 100644 --- a/drive/activity-v2/quickstart/build.gradle +++ b/drive/activity-v2/quickstart/build.gradle @@ -11,7 +11,7 @@ repositories { } dependencies { - implementation 'com.google.api-client:google-api-client:1.33.0' + implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-driveactivity:v2-rev20210319-1.32.1' } From aa4c3cff0953c09fd2d789e8eb0a95f8301ae829 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:51:56 -0600 Subject: [PATCH 078/152] Bump google-auth-library-oauth2-http in /gmail/snippets (#337) Bumps google-auth-library-oauth2-http from 1.6.0 to 1.10.0. --- updated-dependencies: - dependency-name: com.google.auth:google-auth-library-oauth2-http dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- gmail/snippets/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gmail/snippets/build.gradle b/gmail/snippets/build.gradle index 2881c148..7df49f06 100644 --- a/gmail/snippets/build.gradle +++ b/gmail/snippets/build.gradle @@ -5,7 +5,7 @@ repositories { } dependencies { - implementation 'com.google.auth:google-auth-library-oauth2-http:1.6.0' + implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' implementation 'com.google.apis:google-api-services-gmail:v1-rev20220404-1.32.1' implementation 'javax.mail:mail:1.4.7' implementation 'org.apache.commons:commons-csv:1.9.0' From c0eac2c66cacaab57b0e3793525943e206ff483d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:51:58 -0600 Subject: [PATCH 079/152] Bump google-api-services-vault in /vault/quickstart (#334) Bumps google-api-services-vault from v1-rev20211101-1.32.1 to v1-rev20220423-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-vault dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- vault/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vault/quickstart/build.gradle b/vault/quickstart/build.gradle index d60d73f4..d3221860 100644 --- a/vault/quickstart/build.gradle +++ b/vault/quickstart/build.gradle @@ -13,5 +13,5 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' - implementation 'com.google.apis:google-api-services-vault:v1-rev20211101-1.32.1' + implementation 'com.google.apis:google-api-services-vault:v1-rev20220423-2.0.0' } From 4ddb547838c9352cd2bc00b8b9a2e4cbc144e3ed Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:00 -0600 Subject: [PATCH 080/152] Bump google-auth-library-oauth2-http in /drive/snippets/drive_v2 (#332) Bumps google-auth-library-oauth2-http from 1.3.0 to 1.10.0. --- updated-dependencies: - dependency-name: com.google.auth:google-auth-library-oauth2-http dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- drive/snippets/drive_v2/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drive/snippets/drive_v2/build.gradle b/drive/snippets/drive_v2/build.gradle index 6a111d9a..1c46fca4 100644 --- a/drive/snippets/drive_v2/build.gradle +++ b/drive/snippets/drive_v2/build.gradle @@ -7,7 +7,7 @@ repositories { dependencies { implementation 'com.google.apis:google-api-services-drive:v2-rev20211205-1.32.1' implementation 'com.google.api-client:google-api-client:1.23.0' - implementation 'com.google.auth:google-auth-library-oauth2-http:1.3.0' + implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1' implementation 'com.google.code.gson:gson:2.4' testImplementation 'junit:junit:4.13.2' From a2603ceac54b42006f290f6bf280298b6ad23368 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:03 -0600 Subject: [PATCH 081/152] Bump google-api-services-drive in /drive/quickstart (#328) Bumps google-api-services-drive from v3-rev20211107-1.32.1 to v3-rev20220815-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-drive dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- drive/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drive/quickstart/build.gradle b/drive/quickstart/build.gradle index ba1f28b5..bcc8c21a 100644 --- a/drive/quickstart/build.gradle +++ b/drive/quickstart/build.gradle @@ -13,5 +13,5 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' - implementation 'com.google.apis:google-api-services-drive:v3-rev20211107-1.32.1' + implementation 'com.google.apis:google-api-services-drive:v3-rev20220815-2.0.0' } From 05deb03358e28dd4dedaf0630889f4f47ced6a2e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:05 -0600 Subject: [PATCH 082/152] Bump google-api-services-sheets in /sheets/snippets (#338) Bumps google-api-services-sheets from v4-rev20220411-1.32.1 to v4-rev20220620-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-sheets dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- sheets/snippets/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sheets/snippets/build.gradle b/sheets/snippets/build.gradle index e26101e4..e086836c 100644 --- a/sheets/snippets/build.gradle +++ b/sheets/snippets/build.gradle @@ -7,7 +7,7 @@ repositories { dependencies { implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' implementation 'com.google.apis:google-api-services-drive:v3-rev20220508-1.32.1' - implementation 'com.google.apis:google-api-services-sheets:v4-rev20220411-1.32.1' + implementation 'com.google.apis:google-api-services-sheets:v4-rev20220620-2.0.0' testImplementation 'junit:junit:4.13.2' } From 0ee109b81c133d71ab5e2484946a31adf6070982 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:08 -0600 Subject: [PATCH 083/152] Bump google-api-services-sheets in /slides/snippets (#336) Bumps google-api-services-sheets from v4-rev20210629-1.32.1 to v4-rev20220620-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-sheets dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- slides/snippets/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/slides/snippets/build.gradle b/slides/snippets/build.gradle index ea3403b8..73a6c2e1 100644 --- a/slides/snippets/build.gradle +++ b/slides/snippets/build.gradle @@ -7,7 +7,7 @@ repositories { dependencies { implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' implementation 'com.google.apis:google-api-services-drive:v3-rev20211107-1.32.1' - implementation 'com.google.apis:google-api-services-sheets:v4-rev20210629-1.32.1' + implementation 'com.google.apis:google-api-services-sheets:v4-rev20220620-2.0.0' implementation 'com.google.apis:google-api-services-slides:v1-rev20210820-1.32.1' testImplementation 'junit:junit:4.13.2' From 401ec9f4da5aa3c02f6a23cc91f5095cbf905c41 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:10 -0600 Subject: [PATCH 084/152] Bump google-api-client in /vault/vault-hold-migration-api (#323) Bumps [google-api-client](https://github.com/googleapis/google-api-java-client) from 1.33.0 to 2.0.0. - [Release notes](https://github.com/googleapis/google-api-java-client/releases) - [Changelog](https://github.com/googleapis/google-api-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-api-java-client/compare/v1.33.0...v2.0.0) --- updated-dependencies: - dependency-name: com.google.api-client:google-api-client dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- vault/vault-hold-migration-api/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vault/vault-hold-migration-api/build.gradle b/vault/vault-hold-migration-api/build.gradle index 82e95410..1eaa2531 100644 --- a/vault/vault-hold-migration-api/build.gradle +++ b/vault/vault-hold-migration-api/build.gradle @@ -12,7 +12,7 @@ repositories { } dependencies { - implementation 'com.google.api-client:google-api-client:1.33.0' + implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-vault:v1-rev20211101-1.32.1' implementation group: 'org.apache.commons', name: 'commons-csv', version: '1.9.0' From a7aee284fe5a58c2b53590868ad87f276faddcc3 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:12 -0600 Subject: [PATCH 085/152] Bump google-api-client from 1.23.0 to 2.0.0 in /drive/snippets/drive_v3 (#322) Bumps [google-api-client](https://github.com/googleapis/google-api-java-client) from 1.23.0 to 2.0.0. - [Release notes](https://github.com/googleapis/google-api-java-client/releases) - [Changelog](https://github.com/googleapis/google-api-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-api-java-client/compare/1.23.0...v2.0.0) --- updated-dependencies: - dependency-name: com.google.api-client:google-api-client dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- drive/snippets/drive_v3/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drive/snippets/drive_v3/build.gradle b/drive/snippets/drive_v3/build.gradle index ade01244..f1f21c4b 100644 --- a/drive/snippets/drive_v3/build.gradle +++ b/drive/snippets/drive_v3/build.gradle @@ -5,7 +5,7 @@ repositories { } dependencies { implementation 'com.google.apis:google-api-services-drive:v3-rev20211107-1.32.1' - implementation 'com.google.api-client:google-api-client:1.23.0' + implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' implementation 'com.google.code.gson:gson:2.4' testImplementation 'junit:junit:4.13.2' From a22a92de96285b393afc4006d9f520870c1a869e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:15 -0600 Subject: [PATCH 086/152] Bump google-api-client in /adminSDK/groups-settings/quickstart (#297) Bumps [google-api-client](https://github.com/googleapis/google-api-java-client) from 1.33.0 to 2.0.0. - [Release notes](https://github.com/googleapis/google-api-java-client/releases) - [Changelog](https://github.com/googleapis/google-api-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-api-java-client/compare/v1.33.0...v2.0.0) --- updated-dependencies: - dependency-name: com.google.api-client:google-api-client dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- adminSDK/groups-settings/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adminSDK/groups-settings/quickstart/build.gradle b/adminSDK/groups-settings/quickstart/build.gradle index c03cdd97..8026c439 100644 --- a/adminSDK/groups-settings/quickstart/build.gradle +++ b/adminSDK/groups-settings/quickstart/build.gradle @@ -11,7 +11,7 @@ repositories { } dependencies { - implementation 'com.google.api-client:google-api-client:1.33.0' + implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.apis:google-api-services-groupssettings:v1-rev20210624-1.32.1' } From afe6dbee7829c1866267f9a2ff6d4188ba32dcb3 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:17 -0600 Subject: [PATCH 087/152] Bump google-api-services-script in /appsScript/quickstart (#303) Bumps google-api-services-script from v1-rev20210703-1.32.1 to v1-rev20220323-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-script dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- appsScript/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/appsScript/quickstart/build.gradle b/appsScript/quickstart/build.gradle index f26ede54..7ce6076f 100644 --- a/appsScript/quickstart/build.gradle +++ b/appsScript/quickstart/build.gradle @@ -13,5 +13,5 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' - implementation 'com.google.apis:google-api-services-script:v1-rev20210703-1.32.1' + implementation 'com.google.apis:google-api-services-script:v1-rev20220323-2.0.0' } From 20cbee839086ca40576af3f06d0093df7e73d287 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:20 -0600 Subject: [PATCH 088/152] Bump google-api-services-slides in /slides/quickstart (#304) Bumps google-api-services-slides from v1-rev20210820-1.32.1 to v1-rev20220722-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-slides dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- slides/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/slides/quickstart/build.gradle b/slides/quickstart/build.gradle index 05916c6f..8350296e 100644 --- a/slides/quickstart/build.gradle +++ b/slides/quickstart/build.gradle @@ -13,5 +13,5 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' - implementation 'com.google.apis:google-api-services-slides:v1-rev20210820-1.32.1' + implementation 'com.google.apis:google-api-services-slides:v1-rev20220722-2.0.0' } From 8b3665d51638bd00d34b5f62a07d9004afccce8e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:22 -0600 Subject: [PATCH 089/152] Bump google-api-services-sheets in /sheets/quickstart (#284) Bumps google-api-services-sheets from v4-rev20210629-1.32.1 to v4-rev20220620-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-sheets dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- sheets/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sheets/quickstart/build.gradle b/sheets/quickstart/build.gradle index 4dff318c..c12db6f3 100644 --- a/sheets/quickstart/build.gradle +++ b/sheets/quickstart/build.gradle @@ -13,5 +13,5 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' - implementation 'com.google.apis:google-api-services-sheets:v4-rev20210629-1.32.1' + implementation 'com.google.apis:google-api-services-sheets:v4-rev20220620-2.0.0' } From 7b4903e3d1c0591e9992906e2e0e1d08f8a87d1f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:24 -0600 Subject: [PATCH 090/152] Bump google-api-services-classroom in /classroom/snippets (#298) Bumps google-api-services-classroom from v1-rev20220323-1.32.1 to v1-rev20220323-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-classroom dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- classroom/snippets/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/classroom/snippets/build.gradle b/classroom/snippets/build.gradle index f1deeb31..b0776149 100644 --- a/classroom/snippets/build.gradle +++ b/classroom/snippets/build.gradle @@ -8,7 +8,7 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' - implementation 'com.google.apis:google-api-services-classroom:v1-rev20220323-1.32.1' + implementation 'com.google.apis:google-api-services-classroom:v1-rev20220323-2.0.0' testImplementation 'junit:junit:4.13.2' } From 64e7c92db342bdc288ea03ef762743a5dd147822 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:26 -0600 Subject: [PATCH 091/152] Bump google-api-services-calendar in /calendar/quickstart (#292) Bumps google-api-services-calendar from v3-rev20211026-1.32.1 to v3-rev20220715-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-calendar dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- calendar/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/calendar/quickstart/build.gradle b/calendar/quickstart/build.gradle index 923ec144..6252ad03 100644 --- a/calendar/quickstart/build.gradle +++ b/calendar/quickstart/build.gradle @@ -13,5 +13,5 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' - implementation 'com.google.apis:google-api-services-calendar:v3-rev20211026-1.32.1' + implementation 'com.google.apis:google-api-services-calendar:v3-rev20220715-2.0.0' } From 4405ee52951ab758386db772c3efeab6b3681557 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:29 -0600 Subject: [PATCH 092/152] Bump google-api-services-people in /people/quickstart (#310) Bumps google-api-services-people from v1-rev20210903-1.32.1 to v1-rev20220531-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-people dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- people/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/people/quickstart/build.gradle b/people/quickstart/build.gradle index 540e613c..8009371c 100644 --- a/people/quickstart/build.gradle +++ b/people/quickstart/build.gradle @@ -14,5 +14,5 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' - implementation 'com.google.apis:google-api-services-people:v1-rev20210903-1.32.1' + implementation 'com.google.apis:google-api-services-people:v1-rev20220531-2.0.0' } From da2bb7af850e4d4a4e6021400f25f0527631f221 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:30 -0600 Subject: [PATCH 093/152] Bump google-api-services-docs in /docs/outputJSON (#309) Bumps google-api-services-docs from v1-rev20210707-1.32.1 to v1-rev20220609-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-docs dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- docs/outputJSON/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/outputJSON/build.gradle b/docs/outputJSON/build.gradle index 32220cf2..0e76e226 100644 --- a/docs/outputJSON/build.gradle +++ b/docs/outputJSON/build.gradle @@ -13,6 +13,6 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' - implementation 'com.google.apis:google-api-services-docs:v1-rev20210707-1.32.1' + implementation 'com.google.apis:google-api-services-docs:v1-rev20220609-2.0.0' implementation group: 'com.google.code.gson', name: 'gson', version: '2.9.1' } From 3b3695cc679418fb8bc4f6ca360fe9f64bb7bf7f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:33 -0600 Subject: [PATCH 094/152] Bump google-api-services-slides in /slides/snippets (#325) Bumps google-api-services-slides from v1-rev20210820-1.32.1 to v1-rev20220722-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-slides dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- slides/snippets/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/slides/snippets/build.gradle b/slides/snippets/build.gradle index 73a6c2e1..415434c8 100644 --- a/slides/snippets/build.gradle +++ b/slides/snippets/build.gradle @@ -8,7 +8,7 @@ dependencies { implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' implementation 'com.google.apis:google-api-services-drive:v3-rev20211107-1.32.1' implementation 'com.google.apis:google-api-services-sheets:v4-rev20220620-2.0.0' - implementation 'com.google.apis:google-api-services-slides:v1-rev20210820-1.32.1' + implementation 'com.google.apis:google-api-services-slides:v1-rev20220722-2.0.0' testImplementation 'junit:junit:4.13.2' implementation fileTree(dir: 'lib', include: ['*.jar']) From c2c9c2de58423fb11f2990cf76437f33b41805e9 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:35 -0600 Subject: [PATCH 095/152] Bump google-api-services-gmail in /gmail/quickstart (#316) Bumps google-api-services-gmail from v1-rev20211108-1.32.1 to v1-rev20220404-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-gmail dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- gmail/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gmail/quickstart/build.gradle b/gmail/quickstart/build.gradle index 9de1d325..ca113827 100644 --- a/gmail/quickstart/build.gradle +++ b/gmail/quickstart/build.gradle @@ -13,5 +13,5 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' - implementation 'com.google.apis:google-api-services-gmail:v1-rev20211108-1.32.1' + implementation 'com.google.apis:google-api-services-gmail:v1-rev20220404-2.0.0' } From 0594e7fc829b3b9b4f9257ce3ec6beeef44696a8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:37 -0600 Subject: [PATCH 096/152] Bump google-api-services-docs in /docs/quickstart (#306) Bumps google-api-services-docs from v1-rev20210707-1.32.1 to v1-rev20220609-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-docs dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- docs/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/quickstart/build.gradle b/docs/quickstart/build.gradle index 1b5fed39..9f6c9fd7 100644 --- a/docs/quickstart/build.gradle +++ b/docs/quickstart/build.gradle @@ -13,5 +13,5 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' - implementation 'com.google.apis:google-api-services-docs:v1-rev20210707-1.32.1' + implementation 'com.google.apis:google-api-services-docs:v1-rev20220609-2.0.0' } From bd1b219247a1a702f562fcbe156b1297eb908015 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:39 -0600 Subject: [PATCH 097/152] Bump google-api-services-gmail in /gmail/snippets (#313) Bumps google-api-services-gmail from v1-rev20220404-1.32.1 to v1-rev20220404-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-gmail dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- gmail/snippets/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gmail/snippets/build.gradle b/gmail/snippets/build.gradle index 7df49f06..88a66631 100644 --- a/gmail/snippets/build.gradle +++ b/gmail/snippets/build.gradle @@ -6,7 +6,7 @@ repositories { dependencies { implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' - implementation 'com.google.apis:google-api-services-gmail:v1-rev20220404-1.32.1' + implementation 'com.google.apis:google-api-services-gmail:v1-rev20220404-2.0.0' implementation 'javax.mail:mail:1.4.7' implementation 'org.apache.commons:commons-csv:1.9.0' testImplementation 'junit:junit:4.13.2' From 32e412b5625831b6a477107eeb27704784a00792 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:41 -0600 Subject: [PATCH 098/152] Bump google-api-services-classroom in /classroom/quickstart (#293) Bumps google-api-services-classroom from v1-rev20211029-1.32.1 to v1-rev20220323-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-classroom dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- classroom/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/classroom/quickstart/build.gradle b/classroom/quickstart/build.gradle index 7773fab2..d69815f0 100644 --- a/classroom/quickstart/build.gradle +++ b/classroom/quickstart/build.gradle @@ -13,5 +13,5 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' - implementation 'com.google.apis:google-api-services-classroom:v1-rev20211029-1.32.1' + implementation 'com.google.apis:google-api-services-classroom:v1-rev20220323-2.0.0' } From a9d9ce28f09fb27ae2e153b9a242ead3efa7701d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:43 -0600 Subject: [PATCH 099/152] Bump google-api-services-calendar in /calendar/sync (#283) Bumps google-api-services-calendar from v3-rev20211026-1.32.1 to v3-rev20220715-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-calendar dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- calendar/sync/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/calendar/sync/pom.xml b/calendar/sync/pom.xml index 01f4b039..af98470c 100644 --- a/calendar/sync/pom.xml +++ b/calendar/sync/pom.xml @@ -72,7 +72,7 @@ com.google.apis google-api-services-calendar - v3-rev20211026-1.32.1 + v3-rev20220715-2.0.0 com.google.api-client From e9a78eaf65e17a30b3227057ca59a33250448d5a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:45 -0600 Subject: [PATCH 100/152] chore(deps): bump google-api-services-alertcenter (#345) Bumps google-api-services-alertcenter from v1beta1-rev20211012-1.32.1 to v1beta1-rev20220718-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-alertcenter dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- adminSDK/alertcenter/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adminSDK/alertcenter/quickstart/build.gradle b/adminSDK/alertcenter/quickstart/build.gradle index c5be324b..b448253b 100644 --- a/adminSDK/alertcenter/quickstart/build.gradle +++ b/adminSDK/alertcenter/quickstart/build.gradle @@ -14,5 +14,5 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' - implementation 'com.google.apis:google-api-services-alertcenter:v1beta1-rev20211012-1.32.1' + implementation 'com.google.apis:google-api-services-alertcenter:v1beta1-rev20220718-2.0.0' } \ No newline at end of file From 12afbc230c73f03d5f72881aa03e7ceaf3b11121 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:47 -0600 Subject: [PATCH 101/152] chore(deps): bump google-api-services-tasks in /tasks/quickstart (#349) Bumps google-api-services-tasks from v1-rev20210709-1.32.1 to v1-rev20210709-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-tasks dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- tasks/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tasks/quickstart/build.gradle b/tasks/quickstart/build.gradle index c8f052b1..2ae5b7d2 100644 --- a/tasks/quickstart/build.gradle +++ b/tasks/quickstart/build.gradle @@ -13,5 +13,5 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' - implementation 'com.google.apis:google-api-services-tasks:v1-rev20210709-1.32.1' + implementation 'com.google.apis:google-api-services-tasks:v1-rev20210709-2.0.0' } \ No newline at end of file From 0fa7379cdd8cfb4f49f485f80fa5a71f98cd6c81 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:49 -0600 Subject: [PATCH 102/152] chore(deps): bump google-api-services-drive in /sheets/snippets (#347) Bumps google-api-services-drive from v3-rev20220508-1.32.1 to v3-rev20220815-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-drive dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- sheets/snippets/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sheets/snippets/build.gradle b/sheets/snippets/build.gradle index e086836c..8763dd63 100644 --- a/sheets/snippets/build.gradle +++ b/sheets/snippets/build.gradle @@ -6,7 +6,7 @@ repositories { dependencies { implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' - implementation 'com.google.apis:google-api-services-drive:v3-rev20220508-1.32.1' + implementation 'com.google.apis:google-api-services-drive:v3-rev20220815-2.0.0' implementation 'com.google.apis:google-api-services-sheets:v4-rev20220620-2.0.0' testImplementation 'junit:junit:4.13.2' } From 4e7a24324de42d3ac88bfefe74a7cb3cfac56bec Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:52 -0600 Subject: [PATCH 103/152] Bump google-api-services-vault in /vault/vault-hold-migration-api (#335) Bumps google-api-services-vault from v1-rev20211101-1.32.1 to v1-rev20220423-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-vault dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- vault/vault-hold-migration-api/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vault/vault-hold-migration-api/build.gradle b/vault/vault-hold-migration-api/build.gradle index 1eaa2531..8b389d2a 100644 --- a/vault/vault-hold-migration-api/build.gradle +++ b/vault/vault-hold-migration-api/build.gradle @@ -14,7 +14,7 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' - implementation 'com.google.apis:google-api-services-vault:v1-rev20211101-1.32.1' + implementation 'com.google.apis:google-api-services-vault:v1-rev20220423-2.0.0' implementation group: 'org.apache.commons', name: 'commons-csv', version: '1.9.0' implementation 'com.github.rholder:guava-retrying:2.0.0' implementation 'com.google.apis:google-api-services-admin-directory:directory_v1-rev118-1.25.0' From 9f841ac51ff95d2feef41a7d446ea5b6b0f2b680 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:54 -0600 Subject: [PATCH 104/152] Bump google-api-services-drive in /drive/snippets/drive_v2 (#331) Bumps google-api-services-drive from v2-rev20211205-1.32.1 to v3-rev20220815-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-drive dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- drive/snippets/drive_v2/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drive/snippets/drive_v2/build.gradle b/drive/snippets/drive_v2/build.gradle index 1c46fca4..96be2075 100644 --- a/drive/snippets/drive_v2/build.gradle +++ b/drive/snippets/drive_v2/build.gradle @@ -5,7 +5,7 @@ repositories { } dependencies { - implementation 'com.google.apis:google-api-services-drive:v2-rev20211205-1.32.1' + implementation 'com.google.apis:google-api-services-drive:v3-rev20220815-2.0.0' implementation 'com.google.api-client:google-api-client:1.23.0' implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1' From a8969da96266b5fa7dae376a9af1ba1fba340697 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:56 -0600 Subject: [PATCH 105/152] Bump google-api-services-drive in /drive/snippets/drive_v3 (#315) Bumps google-api-services-drive from v3-rev20211107-1.32.1 to v3-rev20220815-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-drive dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- drive/snippets/drive_v3/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drive/snippets/drive_v3/build.gradle b/drive/snippets/drive_v3/build.gradle index f1f21c4b..a94160c8 100644 --- a/drive/snippets/drive_v3/build.gradle +++ b/drive/snippets/drive_v3/build.gradle @@ -4,7 +4,7 @@ repositories { mavenCentral() } dependencies { - implementation 'com.google.apis:google-api-services-drive:v3-rev20211107-1.32.1' + implementation 'com.google.apis:google-api-services-drive:v3-rev20220815-2.0.0' implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' implementation 'com.google.code.gson:gson:2.4' From 21008d82696f073ccc122a1c2976ede6fd10d04c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:52:58 -0600 Subject: [PATCH 106/152] Bump google-api-services-driveactivity in /drive/activity-v2/quickstart (#319) Bumps google-api-services-driveactivity from v2-rev20210319-1.32.1 to v2-rev20210319-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-driveactivity dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- drive/activity-v2/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drive/activity-v2/quickstart/build.gradle b/drive/activity-v2/quickstart/build.gradle index 8663a975..0f90a6c1 100644 --- a/drive/activity-v2/quickstart/build.gradle +++ b/drive/activity-v2/quickstart/build.gradle @@ -13,5 +13,5 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' - implementation 'com.google.apis:google-api-services-driveactivity:v2-rev20210319-1.32.1' + implementation 'com.google.apis:google-api-services-driveactivity:v2-rev20210319-2.0.0' } From 534ef4f9d9229577614cdcdf1208561b2f656e46 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:53:00 -0600 Subject: [PATCH 107/152] Bump google-api-services-admin-reports in /adminSDK/reports/quickstart (#289) Bumps google-api-services-admin-reports from reports_v1-rev89-1.25.0 to reports_v1-rev20211207-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-admin-reports dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- adminSDK/reports/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adminSDK/reports/quickstart/build.gradle b/adminSDK/reports/quickstart/build.gradle index 450d681a..9f9aff5d 100644 --- a/adminSDK/reports/quickstart/build.gradle +++ b/adminSDK/reports/quickstart/build.gradle @@ -13,5 +13,5 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' - implementation 'com.google.apis:google-api-services-admin-reports:reports_v1-rev89-1.25.0' + implementation 'com.google.apis:google-api-services-admin-reports:reports_v1-rev20211207-2.0.0' } From e8656cfd86bd43b75ca4d88b6cad2e097a8cddde Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:53:03 -0600 Subject: [PATCH 108/152] Bump google-api-services-reseller in /adminSDK/reseller/quickstart (#291) Bumps google-api-services-reseller from v1-rev20211106-1.32.1 to v1sandbox-rev60-1.22.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-reseller dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- adminSDK/reseller/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adminSDK/reseller/quickstart/build.gradle b/adminSDK/reseller/quickstart/build.gradle index 20e39b10..3e382f87 100644 --- a/adminSDK/reseller/quickstart/build.gradle +++ b/adminSDK/reseller/quickstart/build.gradle @@ -13,5 +13,5 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' - implementation 'com.google.apis:google-api-services-reseller:v1-rev20211106-1.32.1' + implementation 'com.google.apis:google-api-services-reseller:v1sandbox-rev60-1.22.0' } From 1a33fe3b9a25a7ada9437d73a2d041ff44a966ac Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:53:05 -0600 Subject: [PATCH 109/152] Bump google-api-services-groupssettings (#286) Bumps google-api-services-groupssettings from v1-rev20210624-1.32.1 to v1-rev20210624-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-groupssettings dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- adminSDK/groups-settings/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adminSDK/groups-settings/quickstart/build.gradle b/adminSDK/groups-settings/quickstart/build.gradle index 8026c439..26e5218e 100644 --- a/adminSDK/groups-settings/quickstart/build.gradle +++ b/adminSDK/groups-settings/quickstart/build.gradle @@ -13,5 +13,5 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' - implementation 'com.google.apis:google-api-services-groupssettings:v1-rev20210624-1.32.1' + implementation 'com.google.apis:google-api-services-groupssettings:v1-rev20210624-2.0.0' } From 4c511910090a8484165fb08883604eb8353794a5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:53:07 -0600 Subject: [PATCH 110/152] Bump google-api-services-admin-directory (#318) Bumps google-api-services-admin-directory from directory_v1-rev118-1.25.0 to directory_v1-rev20220816-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-admin-directory dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- vault/vault-hold-migration-api/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vault/vault-hold-migration-api/build.gradle b/vault/vault-hold-migration-api/build.gradle index 8b389d2a..964a2c63 100644 --- a/vault/vault-hold-migration-api/build.gradle +++ b/vault/vault-hold-migration-api/build.gradle @@ -17,6 +17,6 @@ dependencies { implementation 'com.google.apis:google-api-services-vault:v1-rev20220423-2.0.0' implementation group: 'org.apache.commons', name: 'commons-csv', version: '1.9.0' implementation 'com.github.rholder:guava-retrying:2.0.0' - implementation 'com.google.apis:google-api-services-admin-directory:directory_v1-rev118-1.25.0' + implementation 'com.google.apis:google-api-services-admin-directory:directory_v1-rev20220816-2.0.0' implementation group: 'commons-cli', name: 'commons-cli', version: '1.5.0' } \ No newline at end of file From 3e25cfd9bcc9dd0c6404cf1a494a681a466da987 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:53:09 -0600 Subject: [PATCH 111/152] Bump google-api-services-admin-directory (#287) Bumps google-api-services-admin-directory from directory_v1-rev118-1.25.0 to directory_v1-rev20220816-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-admin-directory dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- adminSDK/directory/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adminSDK/directory/quickstart/build.gradle b/adminSDK/directory/quickstart/build.gradle index c2dfbf80..5cc56d2a 100644 --- a/adminSDK/directory/quickstart/build.gradle +++ b/adminSDK/directory/quickstart/build.gradle @@ -13,5 +13,5 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' - implementation 'com.google.apis:google-api-services-admin-directory:directory_v1-rev118-1.25.0' + implementation 'com.google.apis:google-api-services-admin-directory:directory_v1-rev20220816-2.0.0' } From d4567a58806fbe35c5405dc2fb3d3e090a30e779 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:55:42 -0600 Subject: [PATCH 112/152] Bump gson from 2.4 to 2.9.1 in /drive/snippets/drive_v3 (#333) Bumps [gson](https://github.com/google/gson) from 2.4 to 2.9.1. - [Release notes](https://github.com/google/gson/releases) - [Changelog](https://github.com/google/gson/blob/master/CHANGELOG.md) - [Commits](https://github.com/google/gson/compare/gson-2.4...gson-parent-2.9.1) --- updated-dependencies: - dependency-name: com.google.code.gson:gson dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- drive/snippets/drive_v3/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drive/snippets/drive_v3/build.gradle b/drive/snippets/drive_v3/build.gradle index a94160c8..b1196d59 100644 --- a/drive/snippets/drive_v3/build.gradle +++ b/drive/snippets/drive_v3/build.gradle @@ -7,7 +7,7 @@ dependencies { implementation 'com.google.apis:google-api-services-drive:v3-rev20220815-2.0.0' implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' - implementation 'com.google.code.gson:gson:2.4' + implementation 'com.google.code.gson:gson:2.9.1' testImplementation 'junit:junit:4.13.2' } From 3315352dd6c0f413453a8da647f6b4c2220973ca Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:55:44 -0600 Subject: [PATCH 113/152] Bump gson from 2.4 to 2.9.1 in /drive/snippets/drive_v2 (#330) Bumps [gson](https://github.com/google/gson) from 2.4 to 2.9.1. - [Release notes](https://github.com/google/gson/releases) - [Changelog](https://github.com/google/gson/blob/master/CHANGELOG.md) - [Commits](https://github.com/google/gson/compare/gson-2.4...gson-parent-2.9.1) --- updated-dependencies: - dependency-name: com.google.code.gson:gson dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- drive/snippets/drive_v2/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drive/snippets/drive_v2/build.gradle b/drive/snippets/drive_v2/build.gradle index 96be2075..c3a4a34c 100644 --- a/drive/snippets/drive_v2/build.gradle +++ b/drive/snippets/drive_v2/build.gradle @@ -9,7 +9,7 @@ dependencies { implementation 'com.google.api-client:google-api-client:1.23.0' implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1' - implementation 'com.google.code.gson:gson:2.4' + implementation 'com.google.code.gson:gson:2.9.1' testImplementation 'junit:junit:4.13.2' } From 4280aec2a0310e3860879390d0d33e91486f865a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:55:48 -0600 Subject: [PATCH 114/152] Bump google-api-services-drive in /slides/snippets (#299) Bumps google-api-services-drive from v3-rev20211107-1.32.1 to v3-rev20220815-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-drive dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- slides/snippets/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/slides/snippets/build.gradle b/slides/snippets/build.gradle index 415434c8..48965f8c 100644 --- a/slides/snippets/build.gradle +++ b/slides/snippets/build.gradle @@ -6,7 +6,7 @@ repositories { dependencies { implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' - implementation 'com.google.apis:google-api-services-drive:v3-rev20211107-1.32.1' + implementation 'com.google.apis:google-api-services-drive:v3-rev20220815-2.0.0' implementation 'com.google.apis:google-api-services-sheets:v4-rev20220620-2.0.0' implementation 'com.google.apis:google-api-services-slides:v1-rev20220722-2.0.0' testImplementation 'junit:junit:4.13.2' From fb2ae2384e26a358d4ebd8fd8776d3cf97c60c5d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Aug 2022 16:56:11 -0600 Subject: [PATCH 115/152] Bump google-oauth-client-jetty in /drive/snippets/drive_v2 (#329) Bumps [google-oauth-client-jetty](https://github.com/googleapis/google-oauth-java-client) from 1.32.1 to 1.34.1. - [Release notes](https://github.com/googleapis/google-oauth-java-client/releases) - [Changelog](https://github.com/googleapis/google-oauth-java-client/blob/main/CHANGELOG.md) - [Commits](https://github.com/googleapis/google-oauth-java-client/compare/v1.32.1...v1.34.1) --- updated-dependencies: - dependency-name: com.google.oauth-client:google-oauth-client-jetty dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- drive/snippets/drive_v2/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drive/snippets/drive_v2/build.gradle b/drive/snippets/drive_v2/build.gradle index c3a4a34c..9be525c6 100644 --- a/drive/snippets/drive_v2/build.gradle +++ b/drive/snippets/drive_v2/build.gradle @@ -8,7 +8,7 @@ dependencies { implementation 'com.google.apis:google-api-services-drive:v3-rev20220815-2.0.0' implementation 'com.google.api-client:google-api-client:1.23.0' implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' - implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1' + implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' implementation 'com.google.code.gson:gson:2.9.1' testImplementation 'junit:junit:4.13.2' } From ac95ef4c01f808b28a264c2125942ee3a0e4a9d0 Mon Sep 17 00:00:00 2001 From: Steve Bazyl Date: Tue, 30 Aug 2022 17:47:20 -0600 Subject: [PATCH 116/152] fix: Update package names for new version of client lib --- .../src/main/java/AdminSDKDirectoryQuickstart.java | 8 ++++---- .../src/main/java/AdminSDKReportsQuickstart.java | 8 ++++---- drive/snippets/drive_v2/build.gradle | 2 +- gmail/snippets/src/test/java/TestCreateSmimeInfo.java | 1 + .../com/google/vault/chatmigration/DirectoryService.java | 8 ++++---- .../java/com/google/vault/chatmigration/HoldsReport.java | 2 +- .../com/google/vault/chatmigration/MigrationHelper.java | 4 ++-- .../java/com/google/vault/chatmigration/QuickStart.java | 2 +- 8 files changed, 18 insertions(+), 17 deletions(-) diff --git a/adminSDK/directory/quickstart/src/main/java/AdminSDKDirectoryQuickstart.java b/adminSDK/directory/quickstart/src/main/java/AdminSDKDirectoryQuickstart.java index f0573b6f..a5466fc3 100644 --- a/adminSDK/directory/quickstart/src/main/java/AdminSDKDirectoryQuickstart.java +++ b/adminSDK/directory/quickstart/src/main/java/AdminSDKDirectoryQuickstart.java @@ -24,10 +24,10 @@ 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.services.admin.directory.Directory; -import com.google.api.services.admin.directory.DirectoryScopes; -import com.google.api.services.admin.directory.model.User; -import com.google.api.services.admin.directory.model.Users; +import com.google.api.services.directory.Directory; +import com.google.api.services.directory.DirectoryScopes; +import com.google.api.services.directory.model.User; +import com.google.api.services.directory.model.Users; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; diff --git a/adminSDK/reports/quickstart/src/main/java/AdminSDKReportsQuickstart.java b/adminSDK/reports/quickstart/src/main/java/AdminSDKReportsQuickstart.java index 3b5b6881..3b0d2d69 100644 --- a/adminSDK/reports/quickstart/src/main/java/AdminSDKReportsQuickstart.java +++ b/adminSDK/reports/quickstart/src/main/java/AdminSDKReportsQuickstart.java @@ -25,10 +25,10 @@ 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.services.admin.reports.Reports; -import com.google.api.services.admin.reports.ReportsScopes; -import com.google.api.services.admin.reports.model.Activities; -import com.google.api.services.admin.reports.model.Activity; +import com.google.api.services.reports.Reports; +import com.google.api.services.reports.ReportsScopes; +import com.google.api.services.reports.model.Activities; +import com.google.api.services.reports.model.Activity; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; diff --git a/drive/snippets/drive_v2/build.gradle b/drive/snippets/drive_v2/build.gradle index 9be525c6..e3bfcd2b 100644 --- a/drive/snippets/drive_v2/build.gradle +++ b/drive/snippets/drive_v2/build.gradle @@ -5,7 +5,7 @@ repositories { } dependencies { - implementation 'com.google.apis:google-api-services-drive:v3-rev20220815-2.0.0' + implementation 'com.google.apis:google-api-services-drive:v2-rev20220815-2.0.0' implementation 'com.google.api-client:google-api-client:1.23.0' implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' diff --git a/gmail/snippets/src/test/java/TestCreateSmimeInfo.java b/gmail/snippets/src/test/java/TestCreateSmimeInfo.java index 6e304814..dcf90890 100644 --- a/gmail/snippets/src/test/java/TestCreateSmimeInfo.java +++ b/gmail/snippets/src/test/java/TestCreateSmimeInfo.java @@ -17,6 +17,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; import com.google.api.services.gmail.model.SmimeInfo; import org.junit.Test; diff --git a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/DirectoryService.java b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/DirectoryService.java index 24514a5e..4c36043a 100644 --- a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/DirectoryService.java +++ b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/DirectoryService.java @@ -17,10 +17,10 @@ package com.google.vault.chatmigration; import com.github.rholder.retry.RetryException; -import com.google.api.services.admin.directory.Directory; -import com.google.api.services.admin.directory.model.OrgUnit; -import com.google.api.services.admin.directory.model.OrgUnits; -import com.google.api.services.admin.directory.model.User; +import com.google.api.services.directory.Directory; +import com.google.api.services.directory.model.OrgUnit; +import com.google.api.services.directory.model.OrgUnits; +import com.google.api.services.directory.model.User; import java.io.IOException; import java.util.HashMap; import java.util.Map; diff --git a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/HoldsReport.java b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/HoldsReport.java index b337cddf..d42f608b 100644 --- a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/HoldsReport.java +++ b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/HoldsReport.java @@ -16,7 +16,7 @@ package com.google.vault.chatmigration; -import com.google.api.services.admin.directory.model.OrgUnit; +import com.google.api.services.directory.model.OrgUnit; import com.google.api.services.vault.v1.Vault; import com.google.api.services.vault.v1.model.Hold; import com.google.api.services.vault.v1.model.ListHoldsResponse; diff --git a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/MigrationHelper.java b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/MigrationHelper.java index e867ff63..c18f697c 100644 --- a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/MigrationHelper.java +++ b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/MigrationHelper.java @@ -26,8 +26,8 @@ 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.services.admin.directory.Directory; -import com.google.api.services.admin.directory.DirectoryScopes; +import com.google.api.services.directory.Directory; +import com.google.api.services.directory.DirectoryScopes; import com.google.api.services.vault.v1.Vault; import com.google.api.services.vault.v1.VaultScopes; import java.io.IOException; diff --git a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/QuickStart.java b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/QuickStart.java index 70e5943e..c94ccbfc 100644 --- a/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/QuickStart.java +++ b/vault/vault-hold-migration-api/src/main/java/com/google/vault/chatmigration/QuickStart.java @@ -16,7 +16,7 @@ package com.google.vault.chatmigration; -import com.google.api.services.admin.directory.Directory; +import com.google.api.services.directory.Directory; import com.google.api.services.vault.v1.Vault; import com.google.vault.chatmigration.MigrationHelper.MigrationOptions; import java.io.File; From 96f5406d37fa75436cc6d550f747181295df68e8 Mon Sep 17 00:00:00 2001 From: Steve Bazyl Date: Wed, 31 Aug 2022 16:23:25 -0600 Subject: [PATCH 117/152] fix: Enable drive tests + fix failing classrom one --- classroom/snippets/src/main/java/AddStudent.java | 2 +- drive/snippets/drive_v2/build.gradle | 4 ++-- drive/snippets/drive_v3/build.gradle | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/classroom/snippets/src/main/java/AddStudent.java b/classroom/snippets/src/main/java/AddStudent.java index 142072a3..c04c38fb 100644 --- a/classroom/snippets/src/main/java/AddStudent.java +++ b/classroom/snippets/src/main/java/AddStudent.java @@ -55,7 +55,7 @@ public static Student addStudent(String courseId, String enrollmentCode) .setApplicationName("Classroom samples") .build(); - Student student = new Student().setUserId("me"); + Student student = new Student().setUserId("gduser1@workspacesamples.dev"); try { // Enrolling a student to a specified course student = service.courses().students().create(courseId, student) diff --git a/drive/snippets/drive_v2/build.gradle b/drive/snippets/drive_v2/build.gradle index e3bfcd2b..13db3ac6 100644 --- a/drive/snippets/drive_v2/build.gradle +++ b/drive/snippets/drive_v2/build.gradle @@ -14,5 +14,5 @@ dependencies { } test { - useJUnitPlatform() -} \ No newline at end of file + testLogging.showStandardStreams = true +} diff --git a/drive/snippets/drive_v3/build.gradle b/drive/snippets/drive_v3/build.gradle index b1196d59..b7c50196 100644 --- a/drive/snippets/drive_v3/build.gradle +++ b/drive/snippets/drive_v3/build.gradle @@ -12,5 +12,5 @@ dependencies { } test { - useJUnitPlatform() -} \ No newline at end of file + testLogging.showStandardStreams = true +} From b75a5f9a5e180f2e904daea3cfcd89f2a60a5cc3 Mon Sep 17 00:00:00 2001 From: googleworkspace-bot <109114539+googleworkspace-bot@users.noreply.github.com> Date: Fri, 30 Sep 2022 08:56:12 -0600 Subject: [PATCH 118/152] chore: Synced local '.github/sync-repo-settings.yaml' with remote 'sync-files/defaults/.github/sync-repo-settings.yaml' (#363) --- .github/sync-repo-settings.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/sync-repo-settings.yaml b/.github/sync-repo-settings.yaml index 1e81cab7..fc025621 100644 --- a/.github/sync-repo-settings.yaml +++ b/.github/sync-repo-settings.yaml @@ -37,3 +37,5 @@ branchProtectionRules: permissionRules: - team: workspace-devrel-dpe permission: admin + - team: workspace-devrel + permission: write From 953c2c0472968fdc3ff476df36f86fcd1d856e00 Mon Sep 17 00:00:00 2001 From: googleworkspace-bot <109114539+googleworkspace-bot@users.noreply.github.com> Date: Mon, 3 Oct 2022 10:27:43 -0600 Subject: [PATCH 119/152] chore: Synced local '.github/sync-repo-settings.yaml' with remote 'sync-files/defaults/.github/sync-repo-settings.yaml' (#365) --- .github/sync-repo-settings.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/sync-repo-settings.yaml b/.github/sync-repo-settings.yaml index fc025621..7b363bc4 100644 --- a/.github/sync-repo-settings.yaml +++ b/.github/sync-repo-settings.yaml @@ -38,4 +38,4 @@ permissionRules: - team: workspace-devrel-dpe permission: admin - team: workspace-devrel - permission: write + permission: push From 1c8b4497fa19bc4ac05c58501731a01d73105ab0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 Oct 2022 14:52:19 -0600 Subject: [PATCH 120/152] chore(deps): bump google-api-services-sheets in /sheets/quickstart (#369) Bumps google-api-services-sheets from v4-rev20220620-2.0.0 to v4-rev20220927-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-sheets dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- sheets/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sheets/quickstart/build.gradle b/sheets/quickstart/build.gradle index c12db6f3..e0c6f5a5 100644 --- a/sheets/quickstart/build.gradle +++ b/sheets/quickstart/build.gradle @@ -13,5 +13,5 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' - implementation 'com.google.apis:google-api-services-sheets:v4-rev20220620-2.0.0' + implementation 'com.google.apis:google-api-services-sheets:v4-rev20220927-2.0.0' } From 95618d9ead845d53cc4057bb104394833f4047d8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 Oct 2022 14:52:34 -0600 Subject: [PATCH 121/152] chore(deps): bump google-api-services-sheets in /slides/snippets (#368) Bumps google-api-services-sheets from v4-rev20220620-2.0.0 to v4-rev20220927-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-sheets dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- slides/snippets/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/slides/snippets/build.gradle b/slides/snippets/build.gradle index 48965f8c..406a6b20 100644 --- a/slides/snippets/build.gradle +++ b/slides/snippets/build.gradle @@ -7,7 +7,7 @@ repositories { dependencies { implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' implementation 'com.google.apis:google-api-services-drive:v3-rev20220815-2.0.0' - implementation 'com.google.apis:google-api-services-sheets:v4-rev20220620-2.0.0' + implementation 'com.google.apis:google-api-services-sheets:v4-rev20220927-2.0.0' implementation 'com.google.apis:google-api-services-slides:v1-rev20220722-2.0.0' testImplementation 'junit:junit:4.13.2' From 40c542d7ae8a5d28190d91172c8f5df0c461452c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 Oct 2022 14:52:53 -0600 Subject: [PATCH 122/152] chore(deps): bump google-api-services-sheets in /sheets/snippets (#367) Bumps google-api-services-sheets from v4-rev20220620-2.0.0 to v4-rev20220927-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-sheets dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- sheets/snippets/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sheets/snippets/build.gradle b/sheets/snippets/build.gradle index 8763dd63..cda0250f 100644 --- a/sheets/snippets/build.gradle +++ b/sheets/snippets/build.gradle @@ -7,7 +7,7 @@ repositories { dependencies { implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' implementation 'com.google.apis:google-api-services-drive:v3-rev20220815-2.0.0' - implementation 'com.google.apis:google-api-services-sheets:v4-rev20220620-2.0.0' + implementation 'com.google.apis:google-api-services-sheets:v4-rev20220927-2.0.0' testImplementation 'junit:junit:4.13.2' } From 3a06524bf6183ffb7ca99f80afd58c104640400b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 Oct 2022 14:53:09 -0600 Subject: [PATCH 123/152] chore(deps): bump google-api-services-driveactivity (#366) Bumps google-api-services-driveactivity from v2-rev20210319-2.0.0 to v2-rev20220926-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-driveactivity dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- drive/activity-v2/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drive/activity-v2/quickstart/build.gradle b/drive/activity-v2/quickstart/build.gradle index 0f90a6c1..86df8be7 100644 --- a/drive/activity-v2/quickstart/build.gradle +++ b/drive/activity-v2/quickstart/build.gradle @@ -13,5 +13,5 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' - implementation 'com.google.apis:google-api-services-driveactivity:v2-rev20210319-2.0.0' + implementation 'com.google.apis:google-api-services-driveactivity:v2-rev20220926-2.0.0' } From e97ff9e465bf76814ce0e5592b37d3522933d46f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 Oct 2022 14:53:21 -0600 Subject: [PATCH 124/152] chore(deps): bump google-api-services-admin-directory (#361) Bumps google-api-services-admin-directory from directory_v1-rev20220816-2.0.0 to directory_v1-rev20220919-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-admin-directory dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- adminSDK/directory/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adminSDK/directory/quickstart/build.gradle b/adminSDK/directory/quickstart/build.gradle index 5cc56d2a..08a0538e 100644 --- a/adminSDK/directory/quickstart/build.gradle +++ b/adminSDK/directory/quickstart/build.gradle @@ -13,5 +13,5 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1' - implementation 'com.google.apis:google-api-services-admin-directory:directory_v1-rev20220816-2.0.0' + implementation 'com.google.apis:google-api-services-admin-directory:directory_v1-rev20220919-2.0.0' } From 264538d3a7c6ad51028455d23577a36f2e1101b8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 Oct 2022 14:53:39 -0600 Subject: [PATCH 125/152] chore(deps): bump google-api-services-admin-directory (#360) Bumps google-api-services-admin-directory from directory_v1-rev20220816-2.0.0 to directory_v1-rev20220919-2.0.0. --- updated-dependencies: - dependency-name: com.google.apis:google-api-services-admin-directory dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- vault/vault-hold-migration-api/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vault/vault-hold-migration-api/build.gradle b/vault/vault-hold-migration-api/build.gradle index 964a2c63..16a5b2c2 100644 --- a/vault/vault-hold-migration-api/build.gradle +++ b/vault/vault-hold-migration-api/build.gradle @@ -17,6 +17,6 @@ dependencies { implementation 'com.google.apis:google-api-services-vault:v1-rev20220423-2.0.0' implementation group: 'org.apache.commons', name: 'commons-csv', version: '1.9.0' implementation 'com.github.rholder:guava-retrying:2.0.0' - implementation 'com.google.apis:google-api-services-admin-directory:directory_v1-rev20220816-2.0.0' + implementation 'com.google.apis:google-api-services-admin-directory:directory_v1-rev20220919-2.0.0' implementation group: 'commons-cli', name: 'commons-cli', version: '1.5.0' } \ No newline at end of file From 3f9de3ed792e12ce48008b3dbd04ab8605c7c319 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 Oct 2022 14:53:53 -0600 Subject: [PATCH 126/152] chore(deps): bump mockito-inline from 4.7.0 to 4.8.0 in /gmail/snippets (#359) Bumps [mockito-inline](https://github.com/mockito/mockito) from 4.7.0 to 4.8.0. - [Release notes](https://github.com/mockito/mockito/releases) - [Commits](https://github.com/mockito/mockito/compare/v4.7.0...v4.8.0) --- updated-dependencies: - dependency-name: org.mockito:mockito-inline dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- gmail/snippets/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gmail/snippets/build.gradle b/gmail/snippets/build.gradle index 88a66631..0a4690d9 100644 --- a/gmail/snippets/build.gradle +++ b/gmail/snippets/build.gradle @@ -10,6 +10,6 @@ dependencies { implementation 'javax.mail:mail:1.4.7' implementation 'org.apache.commons:commons-csv:1.9.0' testImplementation 'junit:junit:4.13.2' - testImplementation 'org.mockito:mockito-inline:4.7.0' + testImplementation 'org.mockito:mockito-inline:4.8.0' testImplementation 'org.hamcrest:hamcrest:2.2' } From 18921fbb21c10b9c059f2a4fb032b0269edebe8a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 Oct 2022 14:54:06 -0600 Subject: [PATCH 127/152] chore(deps): bump google-auth-library-oauth2-http in /gmail/snippets (#358) Bumps google-auth-library-oauth2-http from 1.10.0 to 1.11.0. --- updated-dependencies: - dependency-name: com.google.auth:google-auth-library-oauth2-http dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- gmail/snippets/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gmail/snippets/build.gradle b/gmail/snippets/build.gradle index 0a4690d9..69378a2d 100644 --- a/gmail/snippets/build.gradle +++ b/gmail/snippets/build.gradle @@ -5,7 +5,7 @@ repositories { } dependencies { - implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' + implementation 'com.google.auth:google-auth-library-oauth2-http:1.11.0' implementation 'com.google.apis:google-api-services-gmail:v1-rev20220404-2.0.0' implementation 'javax.mail:mail:1.4.7' implementation 'org.apache.commons:commons-csv:1.9.0' From 16ee39e8db1636b6c8207da2d051a5b87507a291 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 Oct 2022 14:54:16 -0600 Subject: [PATCH 128/152] chore(deps): bump google-auth-library-oauth2-http in /slides/snippets (#357) Bumps google-auth-library-oauth2-http from 1.10.0 to 1.11.0. --- updated-dependencies: - dependency-name: com.google.auth:google-auth-library-oauth2-http dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- slides/snippets/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/slides/snippets/build.gradle b/slides/snippets/build.gradle index 406a6b20..0471dc29 100644 --- a/slides/snippets/build.gradle +++ b/slides/snippets/build.gradle @@ -5,7 +5,7 @@ repositories { } dependencies { - implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' + implementation 'com.google.auth:google-auth-library-oauth2-http:1.11.0' implementation 'com.google.apis:google-api-services-drive:v3-rev20220815-2.0.0' implementation 'com.google.apis:google-api-services-sheets:v4-rev20220927-2.0.0' implementation 'com.google.apis:google-api-services-slides:v1-rev20220722-2.0.0' From db010abcd83c6daac5dcabf19fcc8bcea700e38b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 Oct 2022 14:54:34 -0600 Subject: [PATCH 129/152] chore(deps): bump google-auth-library-oauth2-http in /classroom/snippets (#356) Bumps google-auth-library-oauth2-http from 1.10.0 to 1.11.0. --- updated-dependencies: - dependency-name: com.google.auth:google-auth-library-oauth2-http dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- classroom/snippets/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/classroom/snippets/build.gradle b/classroom/snippets/build.gradle index b0776149..6971123c 100644 --- a/classroom/snippets/build.gradle +++ b/classroom/snippets/build.gradle @@ -7,7 +7,7 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' - implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' + implementation 'com.google.auth:google-auth-library-oauth2-http:1.11.0' implementation 'com.google.apis:google-api-services-classroom:v1-rev20220323-2.0.0' testImplementation 'junit:junit:4.13.2' } From 0c821edb4af057f96261c629228a4f6a6bdd6bea Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 Oct 2022 14:54:46 -0600 Subject: [PATCH 130/152] chore(deps): bump google-auth-library-oauth2-http in /sheets/snippets (#355) Bumps google-auth-library-oauth2-http from 1.10.0 to 1.11.0. --- updated-dependencies: - dependency-name: com.google.auth:google-auth-library-oauth2-http dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- sheets/snippets/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sheets/snippets/build.gradle b/sheets/snippets/build.gradle index cda0250f..22610657 100644 --- a/sheets/snippets/build.gradle +++ b/sheets/snippets/build.gradle @@ -5,7 +5,7 @@ repositories { } dependencies { - implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' + implementation 'com.google.auth:google-auth-library-oauth2-http:1.11.0' implementation 'com.google.apis:google-api-services-drive:v3-rev20220815-2.0.0' implementation 'com.google.apis:google-api-services-sheets:v4-rev20220927-2.0.0' testImplementation 'junit:junit:4.13.2' From 3bf6700b91695e1e2c466aaa2d3d03ad9a279465 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 Oct 2022 14:55:12 -0600 Subject: [PATCH 131/152] chore(deps): bump google-auth-library-oauth2-http (#354) Bumps google-auth-library-oauth2-http from 1.10.0 to 1.11.0. --- updated-dependencies: - dependency-name: com.google.auth:google-auth-library-oauth2-http dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- drive/snippets/drive_v2/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drive/snippets/drive_v2/build.gradle b/drive/snippets/drive_v2/build.gradle index 13db3ac6..df0967a5 100644 --- a/drive/snippets/drive_v2/build.gradle +++ b/drive/snippets/drive_v2/build.gradle @@ -7,7 +7,7 @@ repositories { dependencies { implementation 'com.google.apis:google-api-services-drive:v2-rev20220815-2.0.0' implementation 'com.google.api-client:google-api-client:1.23.0' - implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.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.code.gson:gson:2.9.1' testImplementation 'junit:junit:4.13.2' From def6803eb45d52a9d2e449302d4bb6d2b1a5f84c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 Oct 2022 14:55:33 -0600 Subject: [PATCH 132/152] chore(deps): bump google-auth-library-oauth2-http (#353) Bumps google-auth-library-oauth2-http from 1.10.0 to 1.11.0. --- updated-dependencies: - dependency-name: com.google.auth:google-auth-library-oauth2-http dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- drive/snippets/drive_v3/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drive/snippets/drive_v3/build.gradle b/drive/snippets/drive_v3/build.gradle index b7c50196..9f0dc9f7 100644 --- a/drive/snippets/drive_v3/build.gradle +++ b/drive/snippets/drive_v3/build.gradle @@ -6,7 +6,7 @@ repositories { dependencies { implementation 'com.google.apis:google-api-services-drive:v3-rev20220815-2.0.0' implementation 'com.google.api-client:google-api-client:2.0.0' - implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' + implementation 'com.google.auth:google-auth-library-oauth2-http:1.11.0' implementation 'com.google.code.gson:gson:2.9.1' testImplementation 'junit:junit:4.13.2' } From 3d4bca36c298a7d229a97f20c8318a813d45864e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 Oct 2022 14:56:02 -0600 Subject: [PATCH 133/152] chore(deps): bump google-auth-library-oauth2-http (#352) Bumps google-auth-library-oauth2-http from 1.10.0 to 1.11.0. --- updated-dependencies: - dependency-name: com.google.auth:google-auth-library-oauth2-http dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- adminSDK/alertcenter/quickstart/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adminSDK/alertcenter/quickstart/build.gradle b/adminSDK/alertcenter/quickstart/build.gradle index b448253b..2e7e184c 100644 --- a/adminSDK/alertcenter/quickstart/build.gradle +++ b/adminSDK/alertcenter/quickstart/build.gradle @@ -13,6 +13,6 @@ repositories { dependencies { implementation 'com.google.api-client:google-api-client:2.0.0' - implementation 'com.google.auth:google-auth-library-oauth2-http:1.10.0' + implementation 'com.google.auth:google-auth-library-oauth2-http:1.11.0' implementation 'com.google.apis:google-api-services-alertcenter:v1beta1-rev20220718-2.0.0' } \ No newline at end of file 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 134/152] =?UTF-8?q?feat:=20added=20Java=20code=20snippets?= =?UTF-8?q?=20for=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 135/152] 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 136/152] 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 137/152] 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 138/152] 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 139/152] 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 140/152] 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 141/152] 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 142/152] 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 143/152] 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 144/152] 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 145/152] 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 146/152] 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 147/152] 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 148/152] 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 149/152] 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 150/152] 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 151/152] 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 152/152] 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]