Skip to content

Instantly share code, notes, and snippets.

@kota65535
Last active July 5, 2023 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kota65535/08c6eb103b110a8f2a36f89c335678ec to your computer and use it in GitHub Desktop.
Save kota65535/08c6eb103b110a8f2a36f89c335678ec to your computer and use it in GitHub Desktop.
GoogleDriveUploader
@Data
public class DriveConfig {
@NotNull
private String credentials;
@NotNull
private String driveId;
@NotNull
private String folderId;
}
public class GoogleDriveUploader {
private final DriveConfig config;
private final Drive drive;
public GoogleDriveUploader(AppConfig appConfig) throws IOException, GeneralSecurityException {
config = appConfig.getDrive();
GoogleCredentials credentials = ServiceAccountCredentials
.fromStream(new ByteArrayInputStream(config.getCredentials().getBytes()))
.createScoped(DriveScopes.all());
drive = new Drive.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
new GsonFactory(),
new HttpCredentialsAdapter(credentials))
.setApplicationName("Google Drive Sandbox")
.build();
}
public List<File> list() throws IOException {
FileList result = drive.files().list()
.setCorpora("drive")
.setDriveId(config.getDriveId())
.setQ("'%s' in parents".formatted(config.getFolderId()))
.setSupportsTeamDrives(true)
.setIncludeItemsFromAllDrives(true)
.execute();
return result.getFiles();
}
public void upload(String filename, String content, String charset) throws IOException {
File fileMeta = new File();
fileMeta.setName(filename);
fileMeta.setParents(List.of(config.getFolderId()));
File f = drive.files()
.create(fileMeta,
new InputStreamContent("text/plain", new ByteArrayInputStream(content.getBytes(charset))))
.setSupportsTeamDrives(true)
.execute();
System.out.print(f.getId());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment