-
-
Save b1a9id/a6ea2fa08b0db18a9f5cb0135ce801c3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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