Using Google Drive API with Java

Using Google Drive API V3 with a Java application

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

  • go to the Service Account page
  • connect with the gmail account you want to retrieve the documents from
  • create a project
  • in your project, create a service account: it’s email address is generated
  • add a key for your service account and download it with the JSON format

b- Add access to the project for the service account

  • go to the IAM administration
  • click on “Add” at the top of the page
  • paste the service account email address, select the “Viewer” role and save

c- Activate the APIs 

  • the Google Drive API here
  • the Cloud SQL Admin API here

d- Share the folder you want to retrieve with the service account email

Documentation : Using OAuth 2.0 for Server to Server Applications 

2- Your JAVA application

a- Dependencies

In order to use the Google Drive Api v3, you’ll have to add the following dependencies in your pom.xml:

        <dependency>
            <groupId>com.google.api-client</groupId>
            <artifactId>google-api-client</artifactId>
            <version>1.31.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.auth</groupId>
            <artifactId>google-auth-library-oauth2-http</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.google.apis</groupId>
            <artifactId>google-api-services-drive</artifactId>
            <version>v3-rev20201130-1.31.0</version>
        </dependency>

b- Retrieving the document’s metadata 

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 binary available ?Are download/export available ?Is the size available ?
gsheet, gdoc, gslides, gdrawyesyesno
gform, gmapnonono
Google Drive extensions only some of them havenoyes
pdfyesyesyes
doc, docxyesyesyes
xls, xlsxyesyesyes
ppt, pptxyesyesyes
jpg, jpeg, pngyesyesyes
odp, odt, odsnoyesyes
txtnoyesyes
xmlnoyesyes
dcmnoyesyes
binnoyesyes
wav, mp3, ogg, aiffnoyesyes
mp4noyesyes
  • 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);
        }
    }
}

Categories: