本文整理了Java中com.google.api.services.drive.Drive
类的一些代码示例,展示了Drive
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Drive
类的具体详情如下:
包路径:com.google.api.services.drive.Drive
类名称:Drive
[英]Service definition for Drive (v3).
Manages files in Drive including uploading, downloading, searching, detecting changes, and updating sharing permissions.
For more information about this service, see the API Documentation
This service uses DriveRequestInitializer to initialize global parameters via its Builder.
[中]驱动器(v3)的服务定义。
管理驱动器中的文件,包括上载、下载、搜索、检测更改和更新共享权限。
有关此服务的更多信息,请参阅API Documentation
此服务使用DriveRequestInitializer通过其生成器初始化全局参数。
代码示例来源:origin: pentaho/pentaho-kettle
protected InputStream doGetInputStream() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
driveService.files().get( id ).executeMediaAndDownloadTo( out );
ByteArrayInputStream in = new ByteArrayInputStream( out.toByteArray() );
return in;
}
代码示例来源:origin: iterate-ch/cyberduck
@Override
public void delete(final List<Path> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
for(Path file : files) {
if(file.getType().contains(Path.Type.placeholder)) {
continue;
}
callback.delete(file);
try {
if(DriveHomeFinderService.TEAM_DRIVES_NAME.equals(file.getParent())) {
session.getClient().teamdrives().delete(fileid.getFileid(file, new DisabledListProgressListener())).execute();
}
else {
if(PreferencesFactory.get().getBoolean("googledrive.delete.trash")) {
final File properties = new File();
properties.setTrashed(true);
session.getClient().files().update(fileid.getFileid(file, new DisabledListProgressListener()), properties)
.setSupportsTeamDrives(PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable")).execute();
}
else {
session.getClient().files().delete(fileid.getFileid(file, new DisabledListProgressListener()))
.setSupportsTeamDrives(PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable")).execute();
}
}
}
catch(IOException e) {
throw new DriveExceptionMappingService().map("Cannot delete {0}", e, file);
}
}
}
代码示例来源:origin: siom79/jdrivesync
public InputStream downloadFile(SyncItem syncItem) {
Drive drive = driveFactory.getDrive(this.credential);
try {
File remoteFile = syncItem.getRemoteFile().get();
GenericUrl genericUrl = null;
if(isGoogleAppsDocumentforExport(remoteFile)){
Optional<String> exportMimeType = supportedGooglMimeType.get(remoteFile.getMimeType());
Export export = drive.files().export(remoteFile.getId(), exportMimeType.get());
genericUrl = export.buildHttpRequestUrl();
}else{
genericUrl = drive.files().get(remoteFile.getId()).set("alt", "media").buildHttpRequestUrl();
}
if (genericUrl != null) {
HttpRequest httpRequest = drive.getRequestFactory().buildGetRequest(genericUrl);
LOGGER.log(Level.FINE, "Downloading file " + remoteFile.getId() + ".");
if (!options.isDryRun()) {
HttpResponse httpResponse = executeWithRetry(options, () -> httpRequest.execute());
return httpResponse.getContent();
}
} else {
LOGGER.log(Level.SEVERE, "No download URL for file " + remoteFile);
}
} catch (Exception e) {
throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to download file: " + e.getMessage(), e);
}
return new ByteArrayInputStream(new byte[0]);
}
代码示例来源:origin: iterate-ch/cyberduck
@Override
public void delete(final List<Path> files, final PasswordCallback prompt, final Callback callback) throws BackgroundException {
final BatchRequest batch = session.getClient().batch();
final List<BackgroundException> failures = new ArrayList<>();
for(Path file : files) {
try {
if(DriveHomeFinderService.TEAM_DRIVES_NAME.equals(file.getParent())) {
session.getClient().teamdrives().delete(fileid.getFileid(file, new DisabledListProgressListener()))
.queue(batch, new DeleteBatchCallback<Void>(file, failures, callback));
final File properties = new File();
properties.setTrashed(true);
session.getClient().files().update(fileid.getFileid(file, new DisabledListProgressListener()), properties)
.setSupportsTeamDrives(PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable"))
.queue(batch, new DeleteBatchCallback<File>(file, failures, callback));
session.getClient().files().delete(fileid.getFileid(file, new DisabledListProgressListener()))
.setSupportsTeamDrives(PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable"))
.queue(batch, new DeleteBatchCallback<Void>(file, failures, callback));
代码示例来源:origin: org.talend.components/components-googledrive-runtime
@Override
public ValidationResult validate(RuntimeContainer container) {
ValidationResult vr = new ValidationResultMutable(Result.OK);
// check for Connection attributes
if (StringUtils.isEmpty(serviceAccountFile)) {
vr = new ValidationResultMutable(Result.ERROR).setMessage("Service Account JSON File cannot be empty.");
return vr;
}
try {
// make a dummy call to check drive's connection..
User u = getDriveService().about().get().setFields("user").execute().getUser();
LOG.debug("[validate] Testing User Properties: {}.", u);
} catch (Exception ex) {
LOG.error("[validate] {}.", ex.getMessage());
vr = new ValidationResultMutable(Result.ERROR).setMessage(ex.getMessage());
return vr;
}
return ValidationResult.OK;
}
代码示例来源:origin: io.github.aktoluna/slnarch-common
public void shareFile(File file, String to) throws IOException {
BatchRequest batch = drive.batch();
Permission userPermission = new Permission()
.setType("user")
.setRole("writer")
.setValue(to);
drive.permissions().insert(file.getId(), userPermission)
.setSendNotificationEmails(true)
.setFields("id")
.queue(batch, callback);
batch.execute();
}
代码示例来源:origin: com.google.apis/google-api-services-drive
@Override
public com.google.api.client.http.GenericUrl buildHttpRequestUrl() {
java.lang.String baseUrl = ("media".equals(get("alt")) && getMediaHttpUploader() == null)
? getRootUrl() + "download/" + getServicePath() : getBaseUrl();
return new com.google.api.client.http.GenericUrl(
com.google.api.client.http.UriTemplate.expand(baseUrl, getUriTemplate(), this, true));
}
代码示例来源:origin: siom79/jdrivesync
LOGGER.log(Level.FINE, "Session initiation request returned upload location: " + location);
GenericUrl putUrl = new GenericUrl(location);
HttpRequest putRequest = drive.getRequestFactory().buildPutRequest(putUrl, fileContent);
LOGGER.log(Level.FINE, "Executing upload request to URL " + putUrl);
HttpResponse putResponse = putRequest.execute();
statusCode = putResponse.getStatusCode();
if (statusCode == HttpStatusCodes.STATUS_CODE_OK) {
putRequest.setParser(drive.getObjectParser());
return putResponse.parseAs(File.class);
代码示例来源:origin: siom79/jdrivesync
private HttpResponse executeSessionInitiationRequest(Drive drive, File remoteFile) throws IOException {
GenericUrl url = new GenericUrl("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable");
JsonHttpContent metadataContent = new JsonHttpContent(drive.getJsonFactory(), remoteFile);
HttpRequest httpRequest = drive.getRequestFactory().buildPostRequest(url, metadataContent);
LOGGER.log(Level.FINE, "Executing session initiation request to URL " + url);
return httpRequest.execute();
}
代码示例来源:origin: lime-ime/limeime
private static InputStream downloadFile(Drive service, com.google.api.services.drive.model.File file) {
if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
try {
HttpResponse resp =
service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl()))
.execute();
return resp.getContent();
} catch (IOException e) {
// An error occurred.
e.printStackTrace();
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
}
代码示例来源:origin: iterate-ch/cyberduck
@Override
public VersionId call(final AbstractHttpEntity entity) throws BackgroundException {
try {
final String base = session.getClient().getRootUrl();
代码示例来源:origin: iterate-ch/cyberduck
@Override
public Path mkdir(final Path folder, final String region, final TransferStatus status) throws BackgroundException {
try {
if(DriveHomeFinderService.TEAM_DRIVES_NAME.equals(folder.getParent())) {
final TeamDrive execute = session.getClient().teamdrives().create(
new UUIDRandomStringService().random(), new TeamDrive().setName(folder.getName())
).execute();
return new Path(folder.getParent(), folder.getName(), folder.getType(),
new PathAttributes(folder.attributes()).withVersionId(execute.getId()));
}
else {
// Identified by the special folder MIME type application/vnd.google-apps.folder
final Drive.Files.Create insert = session.getClient().files().create(new File()
.setName(folder.getName())
.setMimeType("application/vnd.google-apps.folder")
.setParents(Collections.singletonList(fileid.getFileid(folder.getParent(), new DisabledListProgressListener()))));
final File execute = insert
.setSupportsTeamDrives(PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable")).execute();
return new Path(folder.getParent(), folder.getName(), folder.getType(),
new DriveAttributesFinderFeature(session, fileid).toAttributes(execute));
}
}
catch(IOException e) {
throw new DriveExceptionMappingService().map("Cannot create folder {0}", e, folder);
}
}
代码示例来源:origin: Talend/components
@Override
public ValidationResult validate(RuntimeContainer container) {
ValidationResult vr = new ValidationResultMutable(Result.OK);
// check for Connection attributes
if (StringUtils.isEmpty(serviceAccountFile)) {
vr = new ValidationResultMutable(Result.ERROR).setMessage("Service Account JSON File cannot be empty.");
return vr;
}
try {
// make a dummy call to check drive's connection..
User u = getDriveService().about().get().setFields("user").execute().getUser();
LOG.debug("[validate] Testing User Properties: {}.", u);
} catch (Exception ex) {
LOG.error("[validate] {}.", ex.getMessage());
vr = new ValidationResultMutable(Result.ERROR).setMessage(ex.getMessage());
return vr;
}
return ValidationResult.OK;
}
代码示例来源:origin: com.google.apis/google-api-services-drive
@Override
public com.google.api.client.http.GenericUrl buildHttpRequestUrl() {
java.lang.String baseUrl = ("media".equals(get("alt")) && getMediaHttpUploader() == null)
? getRootUrl() + "download/" + getServicePath() : getBaseUrl();
return new com.google.api.client.http.GenericUrl(
com.google.api.client.http.UriTemplate.expand(baseUrl, getUriTemplate(), this, true));
}
代码示例来源:origin: siom79/jdrivesync
int resume = 0;
while (currentChunkEnd <= fileEnd) {
HttpRequest putRequest = drive.getRequestFactory().buildPutRequest(putUrl, new ChunkedHttpContent(localFile, determineMimeType(localFile), currentChunkStart, currentChunkEnd));
if (resume == 0) {
long contentLength = currentChunkEnd - currentChunkStart + 1;
putRequest = drive.getRequestFactory().buildPutRequest(putUrl, new EmptyContent());
long contentLength = 0;
putRequest.getHeaders().setContentLength(contentLength);
LOGGER.log(Level.FINE, "Upload request returned status code " + putResponseStatusCode + " and status message " + putResponse.getStatusMessage());
if (putResponseStatusCode == HttpStatusCodes.STATUS_CODE_OK || putResponseStatusCode == 201) {
putRequest.setParser(drive.getObjectParser());
return putResponse.parseAs(File.class);
代码示例来源:origin: siom79/jdrivesync
public void upload(Drive drive, final File fileToUpload, String mimeType, com.google.api.services.drive.model.File remoteFile) throws IOException {
HttpRequestFactory requestFactory = drive.getRequestFactory();
String uploadLocation = executeWithRetry(options, () -> requestUploadLocation(fileToUpload, mimeType, requestFactory, remoteFile));
GenericUrl uploadUrl = new GenericUrl(uploadLocation);
代码示例来源:origin: iterate-ch/cyberduck
final String base = session.getClient().getRootUrl();
final HttpUriRequest request = new HttpGet(String.format(String.format("%%s/drive/v3/files/%%s?alt=media&supportsTeamDrives=%s", PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable")), base,
fileid.getFileid(file, new DisabledListProgressListener())));
代码示例来源:origin: pentaho/pentaho-kettle
protected void doDelete() throws Exception {
driveService.files().delete( id ).execute();
id = null;
mimeType = null;
}
代码示例来源:origin: qaprosoft/zafira
@Override
@SuppressWarnings("all")
public boolean isConnected()
{
boolean result = false;
try
{
File file = new File(CLIENT_SECRET_JSON);
if(file.exists())
{
driveAuthService.getService(getContext().getCredsFile()).about();
sheetsAuthService.getService(getContext().getCredsFile()).spreadsheets();
result = true;
}
} catch(Exception e)
{
}
return result;
}
代码示例来源:origin: com.google.apis/google-api-services-drive
@Override
public com.google.api.client.http.GenericUrl buildHttpRequestUrl() {
java.lang.String baseUrl = ("media".equals(get("alt")) && getMediaHttpUploader() == null)
? getRootUrl() + "download/" + getServicePath() : getBaseUrl();
return new com.google.api.client.http.GenericUrl(
com.google.api.client.http.UriTemplate.expand(baseUrl, getUriTemplate(), this, true));
}
内容来源于网络,如有侵权,请联系作者删除!