You need to retrieve your Google Drive documents (folders and files) for your Server to Server Application ? Google Drive API v3 will help you accomplish that in a few steps. Let’s see how to easily share a Google Drive folder with your application.
1- Creation of a service account
You’ll need a service account that will interact on behalf of your application with the Google Drive API v3:
a- Create the service account on the Google Cloud Platform
By using the Google Drive API v3, you will be able to retrieve the documents’ metadata: the file’s id, name, created time… The complete list is available here.
public class GoogleDriveApplication { private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); private static final String CREDENTIALS_FILE_PATH = "/googleddrive-XXXXXXXXX.json"; private static final String SERVICE_ACCOUNT = "serviceAccountName@projectName.iam.gserviceaccount.com"; private static final String APPLICATION_NAME = "projectName"; private static final List<String> SCOPES = Arrays.asList(DriveScopes.DRIVE); private static final String ROOT_FOLDER = "xxxxxxxxxxxxxxxxxx"; private static final String projection = "files(name, id, parents, createdTime, modifiedTime, …)"; private static Drive driveService;
public static void main(String... args) throws IOException, GeneralSecurityException { buildApiService(); List<File> files = getChildren(ROOT_FOLDER); ... } // CREATE THE CONNEXION TO THE API public static void buildApiService() throws IOException, GeneralSecurityException { final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); InputStream resourceAsStream = GoogleDriveApplication.class.getResourceAsStream(CREDENTIALS_FILE_PATH); HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( ServiceAccountCredentials.fromStream(resourceAsStream).createScoped(SCOPES).createDelegated(SERVICE_ACCOUNT)); driveService = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer).setApplicationName(APPLICATION_NAME).build(); }
// GET THE METADATA OF THE FILES STORED IN YOUR GOOGLE DRIVE public static List<File> getChildren(String id) throws IOException { String query = "'" + id + "'" + " in parents"; FileList directChildren = driveService.files().list().setQ(query).setFields(projection).execute(); List<File> files = directChildren.getFiles(); … // Here your treatment... return files; }}
c- Retrieving the file’s binary
In your Google Drive, you can store different kinds of documents: Google Drive mimetypes, Google Drive extensions (draw.io, Adobe Acrobat – PDF and e-signature tools, …) or any other mimetypes. Hereafter are precisions about the availability of the binary and the size for the most encountered mimetypes.
Is the binaryavailable ?
Are download/export available ?
Is the size available ?
gsheet, gdoc, gslides, gdraw
yes
yes
no
gform, gmap
no
no
no
Google Drive extensions
only some of them have
no
yes
pdf
yes
yes
yes
doc, docx
yes
yes
yes
xls, xlsx
yes
yes
yes
ppt, pptx
yes
yes
yes
jpg, jpeg, png
yes
yes
yes
odp, odt, ods
no
yes
yes
txt
no
yes
yes
xml
no
yes
yes
dcm
no
yes
yes
bin
no
yes
yes
wav, mp3, ogg, aiff
no
yes
yes
mp4
no
yes
yes
The JAVA code:
The retrieving of the binary requires a different method depending on these extensions:
public static void getOutputStream(File file, OutputStream outputStream) throws IOException { try { // YOU CAN DOWNLOAD GOOGLE DRIVE FILES IN PDF FOR EXAMPLE if (file.getMimeType().contains("application/vnd.google-apps.")) { driveService.files().export(file.getId(), "application/pdf").executeMediaAndDownloadTo(outputStream); // OTHER FILES ARE RETRIEVED IN THEIR ORIGINAL MIME TYPE } else { driveService.files().get(file.getId()).executeMediaAndDownloadTo(outputStream); } } catch (IOException e) { throw new IOException("Error getting outputStream for file:" + file + " - error: " + e); } } }
To provide the best experiences, we use technologies such as cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent may adversely affect certain features and functions.
Functional
Always active
The storage or technical access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Préférences
Le stockage ou l’accès technique est nécessaire dans la finalité d’intérêt légitime de stocker des préférences qui ne sont pas demandées par l’abonné ou l’utilisateur.
Statistics
Storage or technical access exclusively used for statistical purposes.Le stockage ou l’accès technique qui est utilisé exclusivement dans des finalités statistiques anonymes. En l’absence d’une assignation à comparaître, d’une conformité volontaire de la part de votre fournisseur d’accès à internet ou d’enregistrements supplémentaires provenant d’une tierce partie, les informations stockées ou extraites à cette seule fin ne peuvent généralement pas être utilisées pour vous identifier.
Marketing
Le stockage ou l’accès technique est nécessaire pour créer des profils d’utilisateurs afin d’envoyer des publicités, ou pour suivre l’utilisateur sur un site web ou sur plusieurs sites web ayant des finalités marketing similaires.