protected InputStream doGetInputStream() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); driveService.files().get( id ).executeMediaAndDownloadTo( out ); ByteArrayInputStream in = new ByteArrayInputStream( out.toByteArray() ); return in; }
@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); } } }
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]); }
@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));
@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; }
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(); }
@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)); }
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);
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(); }
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; } }
@Override public VersionId call(final AbstractHttpEntity entity) throws BackgroundException { try { final String base = session.getClient().getRootUrl();
@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); } }
@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; }
@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)); }
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);
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);
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())));
protected void doDelete() throws Exception { driveService.files().delete( id ).execute(); id = null; mimeType = null; }
@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; }
@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)); }