diff --git a/drive/snippets/drive_v2/src/main/java/DownloadFile.java b/drive/snippets/drive_v2/src/main/java/DownloadFile.java new file mode 100644 index 00000000..8cf14a80 --- /dev/null +++ b/drive/snippets/drive_v2/src/main/java/DownloadFile.java @@ -0,0 +1,69 @@ +/* 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.*/ + +// [START drive_download_file] + +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.drive.Drive; +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; +import java.util.Arrays; + +/* 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. + */ + private 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); + + // 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(); + + 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; + } + } +} +// [END drive_download_file]