Drive API Client Library for Javaで遊ぶ

Drive API Client Library for Javaで遊んだのでまとめます。

環境
- Java 11
- Spring Boot 2.4.4
- Google Auth Library 0.25.2
- Drive API Client Library for Java v3-rev20210315-1.31.0

GCPコンソール側の設定

google drive の Quickstart(サービスアカウント編) を参考にさせていただきました。 GCPコンソールでの設定は上記の記事をみてください。

依存関係の追加

Google Auth LibraryとDrive API Client Library for Javaを依存関係に追加します。

dependencies {
  ...
    implementation "com.google.apis:google-api-services-drive:$googleApiServicesDriveVersion"
    implementation "com.google.auth:google-auth-library-oauth2-http:$googleAuthLibraryOAuth2HttpVersion"
  ...
}

Credentialの作成

Google Drive APIにリクエストするときにクレデンシャル情報を渡す必要があります。GCPコンソールからダウンロードしたサービスアカウントキーファイル(JSON)からインスタンスを作成します。

GoogleCredentials credentials;
try (InputStream inputStream = new ClassPathResource(CREDENTIALS_FILE_PATH).getInputStream()) {
    credentials = ServiceAccountCredentials.fromStream(inputStream).createScoped(SCOPES);
}

Google Driveで遊ぶ

ディレクトリにあるファイル一覧取得、ファイルのアップロード、ファイルのダウンロードを行なっています。

@Service
public class FileServiceImpl implements FileService {

    private static final Logger LOG = LoggerFactory.getLogger(FileServiceImpl.class);

    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

    private final GDriveProperties gDriveProperties;

    public FileServiceImpl(GDriveProperties gDriveProperties) {
        this.gDriveProperties = gDriveProperties;
    }

    @Override
    public void list(GoogleCredentials credentials) throws IOException, GeneralSecurityException {
        HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
        Drive service = new Drive.Builder(GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, requestInitializer)
                .setApplicationName("Google Drive Sandbox")
                .build();

        FileList result = service.files().list().setPageSize(10).execute();
        List<File> files = result.getFiles();
        if (CollectionUtils.isEmpty(files)) {
            LOG.info("No files found.");
            return;
        }
        LOG.info("Files:");
        files.forEach(file -> LOG.info("file name: {}, id: {}\n", file.getName(), file.getId()));
    }

    @Override
    public void upload(GoogleCredentials credentials) throws IOException, GeneralSecurityException {
        HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
        Drive service = new Drive.Builder(GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, requestInitializer)
                .setApplicationName("Google Drive Sandbox")
                .build();

        File fileMetadata = new File();
        fileMetadata.setName("create.txt");
        fileMetadata.setParents(Collections.singletonList(gDriveProperties.getParentDirId()));
        FileContent mediaContent = new FileContent("text/plain", new ClassPathResource("/static/create.txt").getFile());
        File file = service.files().create(fileMetadata, mediaContent)
                .setFields("id, parents")
                .execute();

        LOG.info("Uploaded: file id: {}\n", file.getId());
    }

    @Override
    public void download(GoogleCredentials credentials) throws IOException, GeneralSecurityException {
        HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
        Drive service = new Drive.Builder(GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, requestInitializer)
                .setApplicationName("Google Drive Sandbox")
                .build();

        File file = service.files().get(gDriveProperties.getDownloadFileId()).execute();
        LOG.info("Downloaded: file id: {}, file name: {}", file.getId(), file.getName());
    }
}

ほぼ各ライブラリのREADME.mdを見ながら実装したのでそこまで解説することはないです。詳しくはGitHubレポジトリ を見てください。

実行結果

正常に動いているようです。

.   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/  ___)| |_)| | | | | || (_| |  ) ) ) )
'  |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot ::                (v2.4.4)

2021-04-02 17:38:16.412  INFO 8930 --- [           main] c.b.googledrivesandbox.Application       : Starting Application using Java 11.0.2
2021-04-02 17:38:16.414  INFO 8930 --- [           main] c.b.googledrivesandbox.Application       : No active profile set, falling back to default profiles: default
2021-04-02 17:38:16.798  INFO 8930 --- [           main] c.b.googledrivesandbox.Application       : Started Application in 0.672 seconds (JVM running for 1.172)
2021-04-02 17:38:17.548  INFO 8930 --- [           main] c.b.g.service.impl.FileServiceImpl       : Files:
2021-04-02 17:38:17.548  INFO 8930 --- [           main] c.b.g.service.impl.FileServiceImpl       : file name: create2.txt, id: 1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx2

2021-04-02 17:38:17.549  INFO 8930 --- [           main] c.b.g.service.impl.FileServiceImpl       : file name: create1.txt, id: 1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx1

2021-04-02 17:38:17.549  INFO 8930 --- [           main] c.b.g.service.impl.FileServiceImpl       : file name: create.txt, id: 1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx0

2021-04-02 17:38:17.823  INFO 8930 --- [           main] c.b.g.service.impl.FileServiceImpl       : Downloaded: file id: 1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx2, file name: create2.txt
2021-04-02 17:38:18.185  INFO 8930 --- [           main] c.b.g.service.impl.FileServiceImpl       : Files:
2021-04-02 17:38:18.185  INFO 8930 --- [           main] c.b.g.service.impl.FileServiceImpl       : file name: create2.txt, id: 1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx2

2021-04-02 17:38:18.185  INFO 8930 --- [           main] c.b.g.service.impl.FileServiceImpl       : file name: create1.txt, id: 1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx1

2021-04-02 17:38:18.185  INFO 8930 --- [           main] c.b.g.service.impl.FileServiceImpl       : file name: create.txt, id: 1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx0