Skip to content

Instantly share code, notes, and snippets.

@b1a9id
Last active April 2, 2021 08:39
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 b1a9id/a6ea2fa08b0db18a9f5cb0135ce801c3 to your computer and use it in GitHub Desktop.
Save b1a9id/a6ea2fa08b0db18a9f5cb0135ce801c3 to your computer and use it in GitHub Desktop.
@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());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment