Skip to content

Instantly share code, notes, and snippets.

@b1a9id

b1a9id/FileServiceImpl.java Secret

Last active Apr 2, 2021
Embed
What would you like to do?
@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