com.google.api.services.drive.Drive Java Examples

The following examples show how to use com.google.api.services.drive.Drive. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AndroidGoogleDrive.java    From QtAndroidTools with MIT License 9 votes vote down vote up
public boolean authenticate(String AppName, String ScopeName)
{
    final GoogleSignInAccount SignInAccount = GoogleSignIn.getLastSignedInAccount(mActivityInstance);

    if(SignInAccount != null)
    {
        GoogleAccountCredential AccountCredential;
        Drive.Builder DriveBuilder;

        AccountCredential = GoogleAccountCredential.usingOAuth2(mActivityInstance, Collections.singleton(ScopeName));
        AccountCredential.setSelectedAccount(SignInAccount.getAccount());

        DriveBuilder = new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), AccountCredential);
        DriveBuilder.setApplicationName(AppName);
        mDriveService = DriveBuilder.build();

        return true;
    }

    Log.d(TAG, "You have to signin by select account before use this call!");
    return false;
}
 
Example #2
Source File: SendFusionTablesAsyncTask.java    From mytracks with Apache License 2.0 7 votes vote down vote up
private boolean setPermission(Track track, String tableId) throws IOException, GoogleAuthException {
  boolean defaultTablePublic = PreferencesUtils.getBoolean(context,
      R.string.export_google_fusion_tables_public_key,
      PreferencesUtils.EXPORT_GOOGLE_FUSION_TABLES_PUBLIC_DEFAULT);
  if (!defaultTablePublic) {
    return true;
  }
  GoogleAccountCredential driveCredential = SendToGoogleUtils.getGoogleAccountCredential(
      context, account.name, SendToGoogleUtils.DRIVE_SCOPE);
  if (driveCredential == null) {
    return false;
  }
  Drive drive = SyncUtils.getDriveService(driveCredential);
  Permission permission = new Permission();
  permission.setRole("reader");
  permission.setType("anyone");
  permission.setValue("");   
  drive.permissions().insert(tableId, permission).execute();
  
  shareUrl = SendFusionTablesUtils.getMapUrl(track, tableId);
  return true;
}
 
Example #3
Source File: TGDriveBrowser.java    From tuxguitar with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void open(final TGBrowserCallBack<Object> cb){
	try {
		this.drive = null;
		this.folder = null;
		this.httpTransport = AndroidHttp.newCompatibleTransport();
		
		TGDriveBrowserLogin login = new TGDriveBrowserLogin(this.findActivity(), this.settings, new TGBrowserCallBack<GoogleAccountCredential>() {
			public void onSuccess(GoogleAccountCredential credential) {
				Drive.Builder builder = new Drive.Builder(TGDriveBrowser.this.httpTransport, GsonFactory.getDefaultInstance(), credential);
				builder.setApplicationName(findActivity().getString(R.string.gdrive_application_name));
				TGDriveBrowser.this.drive = builder.build();
				
				cb.onSuccess(null);
			}
			
			public void handleError(Throwable throwable) {
				cb.handleError(throwable);
			}
		});
		login.process();
	} catch (Throwable e) {
		cb.handleError(e);
	}
}
 
Example #4
Source File: GoogleBloggerImporter.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private String createAlbumFolder(Drive driveInterface) throws IOException {
  File fileMetadata = new File();
  LocalDate localDate = LocalDate.now();
  fileMetadata.setName("(Public)Imported Images on: " + localDate.toString());
  fileMetadata.setMimeType("application/vnd.google-apps.folder");
  File folder = driveInterface.files().create(fileMetadata).setFields("id").execute();
  driveInterface
      .permissions()
      .create(
          folder.getId(),
          // Set link sharing on, see:
          // https://developers.google.com/drive/api/v3/reference/permissions/create
          new Permission().setRole("reader").setType("anyone").setAllowFileDiscovery(false))
      .execute();
  return folder.getId();
}
 
Example #5
Source File: GApiGateway.java    From gdx-gamesvcs with Apache License 2.0 6 votes vote down vote up
/**
 * Authorizes the installed application to access user's protected data.
 */
public static void authorize(String userID, boolean driveAPI) throws IOException {
    // load client secrets

    // set up authorization code flow
    Collection<String> scopes = new ArrayList<String>();
    scopes.add(GamesScopes.GAMES);
    if (driveAPI)
        scopes.add(DriveScopes.DRIVE_APPDATA);

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY,
            clientSecrets, scopes).setDataStoreFactory(dataStoreFactory).build();
    // authorize
    Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()) {
        // Override open browser not working well on Linux and maybe other
        // OS.
        protected void onAuthorization(AuthorizationCodeRequestUrl authorizationUrl) throws java.io.IOException {
            Gdx.net.openURI(authorizationUrl.build());
        }
    }.authorize(userID);

    games = new Games.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(applicationName).build();
    if (driveAPI)
        drive = new Drive.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(applicationName).build();

}
 
Example #6
Source File: GoogleBloggerImporter.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private String uploadImage(ASObject imageObject, Drive driveService, String parentFolderId)
    throws IOException {
  String url;
  String description = null;
  // The image property can either be an object, or just a URL, handle both cases.
  if ("Image".equalsIgnoreCase(imageObject.objectTypeString())) {
    url = imageObject.firstUrl().toString();
    if (imageObject.displayName() != null) {
      description = imageObject.displayNameString();
    }
  } else {
    url = imageObject.toString();
  }
  if (description == null) {
    description = "Imported photo from: " + url;
  }
  HttpURLConnection conn = imageStreamProvider.getConnection(url);
  InputStream inputStream = conn.getInputStream();
  File driveFile = new File().setName(description).setParents(ImmutableList.of(parentFolderId));
  InputStreamContent content = new InputStreamContent(null, inputStream);
  File newFile = driveService.files().create(driveFile, content).setFields("id").execute();

  return "https://drive.google.com/thumbnail?id=" + newFile.getId();
}
 
Example #7
Source File: RemoteGoogleDriveConnector.java    From cloudsync with GNU General Public License v2.0 6 votes vote down vote up
public void initService(Handler handler) throws CloudsyncException
{

	if (service != null) return;

	final HttpTransport httpTransport = new NetHttpTransport();
	final JsonFactory jsonFactory = new JacksonFactory();
	service = new Drive.Builder(httpTransport, jsonFactory, null)
		.setApplicationName("Backup")
		.setHttpRequestInitializer(credential)
		.build();
	if (StringUtils.isEmpty(credential.getServiceAccountId())) {
		credential.setExpiresInSeconds(MIN_TOKEN_REFRESH_TIMEOUT);
	}
	try
	{
		refreshCredential();
	}
	catch (IOException e)
	{
		throw new CloudsyncException("couldn't refresh google drive token");
	}
	handler.getRootItem().setRemoteIdentifier(_getBackupFolder().getId());
}
 
Example #8
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
public void updateFile(SyncItem syncItem) {
	Drive drive = driveFactory.getDrive(this.credential);
	try {
		java.io.File localFile = syncItem.getLocalFile().get();
		File remoteFile = syncItem.getRemoteFile().get();
		BasicFileAttributes attr = Files.readAttributes(localFile.toPath(), BasicFileAttributes.class);
		remoteFile.setModifiedTime(new DateTime(attr.lastModifiedTime().toMillis()));
		if (isGoogleAppsDocument(remoteFile)) {
			return;
		}
		LOGGER.log(Level.INFO, "Updating file " + remoteFile.getId() + " (" + syncItem.getPath() + ").");
		if (!options.isDryRun()) {
			Drive.Files.Update updateRequest = drive.files().update(remoteFile.getId(), remoteFile, new FileContent(determineMimeType(localFile), localFile));
			//updateRequest.setModifiedDate(true);
			File updatedFile = executeWithRetry(options, () -> updateRequest.execute());
			syncItem.setRemoteFile(Optional.of(updatedFile));
		}
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to update file: " + e.getMessage(), e);
	}
}
 
Example #9
Source File: DriveImporter.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private String importSingleFile(
    UUID jobId, Drive driveInterface, DigitalDocumentWrapper file, String parentId)
    throws IOException {
  InputStreamContent content =
      new InputStreamContent(
          null, jobStore.getStream(jobId, file.getCachedContentId()).getStream());
  DtpDigitalDocument dtpDigitalDocument = file.getDtpDigitalDocument();
  File driveFile = new File().setName(dtpDigitalDocument.getName());
  if (!Strings.isNullOrEmpty(parentId)) {
    driveFile.setParents(ImmutableList.of(parentId));
  }
  if (!Strings.isNullOrEmpty(dtpDigitalDocument.getDateModified())) {
    driveFile.setModifiedTime(DateTime.parseRfc3339(dtpDigitalDocument.getDateModified()));
  }
  if (!Strings.isNullOrEmpty(file.getOriginalEncodingFormat())
      && file.getOriginalEncodingFormat().startsWith("application/vnd.google-apps.")) {
    driveFile.setMimeType(file.getOriginalEncodingFormat());
  }
  return driveInterface.files().create(driveFile, content).execute().getId();
}
 
Example #10
Source File: AndroidGoogleDrive.java    From QtAndroidTools with MIT License 6 votes vote down vote up
public boolean downloadFile(String FileId, String LocalFilePath)
{
    if(mDriveService != null)
    {
        try
        {
            Drive.Files.Get FileDownloadRequest = mDriveService.files().get(FileId);
            FileDownloadRequest.getMediaHttpDownloader().setProgressListener(new FileDownloadProgressListener());
            FileDownloadRequest.executeMediaAndDownloadTo(new FileOutputStream(LocalFilePath));
        }
        catch(IOException e)
        {
            Log.d(TAG, e.toString());
            return false;
        }

        return true;
    }

    return false;
}
 
Example #11
Source File: GoogleDriveAdapterTest.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
@Test
public void testChunkedUpload() {
	Credential credentials = mock(Credential.class);
	Options options = new Options();
	DriveFactory driveFactory = mock(DriveFactory.class);
	Drive drive = mock(Drive.class);
	when(driveFactory.getDrive(anyObject())).thenReturn(drive);
	HttpRequestFactory requestFactory = mock(HttpRequestFactory.class);
	when(drive.getRequestFactory()).thenReturn(requestFactory);
	GoogleDriveAdapter googleDriveAdapter = new GoogleDriveAdapter(credentials, options, driveFactory);
}
 
Example #12
Source File: GoogleDriveApiImpl.java    From science-journal with Apache License 2.0 6 votes vote down vote up
@Override
public DriveApi init(
    HttpTransport transport,
    JsonFactory jsonFactory,
    AppAccount appAccount,
    Context applicationContext) {

  List<String> scopeList = Arrays.asList(SCOPES);
  GoogleAccountCredential credential =
      GoogleAccountCredential.usingOAuth2(applicationContext, scopeList)
          .setBackOff(new ExponentialBackOff())
          .setSelectedAccount(appAccount.getAccount());

  this.driveApi =
      new Drive.Builder(transport, jsonFactory, credential)
          .setApplicationName(applicationContext.getPackageName())
          .build();

  return this;
}
 
Example #13
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
public List<File> listChildren(String parentId) {
	List<File> resultList = new LinkedList<File>();
	Drive drive = driveFactory.getDrive(this.credential);
	try {
		Drive.Files.List request = drive.files().list().setFields("nextPageToken, files");
		request.setQ("trashed = false and '" + parentId + "' in parents");
		request.setPageSize(1000);
		LOGGER.log(Level.FINE, "Listing children of folder " + parentId + ".");
		do {
			FileList fileList = executeWithRetry(options, () -> request.execute());
			List<File> items = fileList.getFiles();
			resultList.addAll(items);
			request.setPageToken(fileList.getNextPageToken());
		} while (request.getPageToken() != null && request.getPageToken().length() > 0);
		if (LOGGER.isLoggable(Level.FINE)) {
			for (File file : resultList) {
				LOGGER.log(Level.FINE, "Child of " + parentId + ": " + file.getId() + ";" + file.getName() + ";" + file.getMimeType());
			}
		}
		removeDuplicates(resultList);
		return resultList;
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to execute list request: " + e.getMessage(), e);
	}
}
 
Example #14
Source File: GoogleDriveSource.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize file system helper at most once for this instance.
 * {@inheritDoc}
 * @see org.apache.gobblin.source.extractor.filebased.FileBasedSource#initFileSystemHelper(org.apache.gobblin.configuration.State)
 */
@Override
public synchronized void initFileSystemHelper(State state) throws FileBasedHelperException {
  if (fsHelper == null) {
    Credential credential = new GoogleCommon.CredentialBuilder(state.getProp(SOURCE_CONN_PRIVATE_KEY), state.getPropAsList(API_SCOPES))
                                            .fileSystemUri(state.getProp(PRIVATE_KEY_FILESYSTEM_URI))
                                            .proxyUrl(state.getProp(SOURCE_CONN_USE_PROXY_URL))
                                            .port(state.getProp(SOURCE_CONN_USE_PROXY_PORT))
                                            .serviceAccountId(state.getProp(SOURCE_CONN_USERNAME))
                                            .build();

    Drive driveClient = new Drive.Builder(credential.getTransport(),
                                          GoogleCommon.getJsonFactory(),
                                          credential)
                                 .setApplicationName(Preconditions.checkNotNull(state.getProp(APPLICATION_NAME), "ApplicationName is required"))
                                 .build();
    this.fsHelper = closer.register(new GoogleDriveFsHelper(state, driveClient));
  }
}
 
Example #15
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
public void updateMetadata(SyncItem syncItem) {
	Drive drive = driveFactory.getDrive(this.credential);
	try {
		java.io.File localFile = syncItem.getLocalFile().get();
		File remoteFile = syncItem.getRemoteFile().get();
		BasicFileAttributes attr = Files.readAttributes(localFile.toPath(), BasicFileAttributes.class);
		if (isGoogleAppsDocument(remoteFile)) {
			return;
		}
		LOGGER.log(Level.FINE, "Updating metadata of remote file " + remoteFile.getId() + " (" + syncItem.getPath() + ").");
		if (!options.isDryRun()) {
			File newRemoteFile = new File();
			newRemoteFile.setModifiedTime(new DateTime(attr.lastModifiedTime().toMillis()));
			Drive.Files.Update updateRequest = drive.files().update(remoteFile.getId(), newRemoteFile).setFields("modifiedTime");
			File updatedFile = executeWithRetry(options, () -> updateRequest.execute());
			syncItem.setRemoteFile(Optional.of(updatedFile));
		}
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to update file: " + e.getMessage(), e);
	}
}
 
Example #16
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
public void store(SyncDirectory syncDirectory) {
	Drive drive = driveFactory.getDrive(this.credential);
	try {
		java.io.File localFile = syncDirectory.getLocalFile().get();
		File remoteFile = new File();
		remoteFile.setName(localFile.getName());
		remoteFile.setMimeType(MIME_TYPE_FOLDER);
		remoteFile.setParents(createParentReferenceList(syncDirectory));
		BasicFileAttributes attr = Files.readAttributes(localFile.toPath(), BasicFileAttributes.class);
		remoteFile.setModifiedTime(new DateTime(attr.lastModifiedTime().toMillis()));
		LOGGER.log(Level.FINE, "Inserting new directory '" + syncDirectory.getPath() + "'.");
		if (!options.isDryRun()) {
			File insertedFile = executeWithRetry(options, () -> drive.files().create(remoteFile).execute());
			syncDirectory.setRemoteFile(Optional.of(insertedFile));
		}
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to update file: " + e.getMessage(), e);
	}
}
 
Example #17
Source File: GoogleDriveDataSourceTest.java    From components with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidate() throws Exception {
    inputProperties.getDatasetProperties().getDatastoreProperties().serviceAccountJSONFile.setValue("");
    dataSource.initialize(container, inputProperties);
    assertEquals(Result.ERROR, dataSource.validate(container).getStatus());

    dataSource = spy(dataSource);
    Drive drive = mock(Drive.class, RETURNS_DEEP_STUBS);
    GoogleDriveUtils utils = mock(GoogleDriveUtils.class, RETURNS_DEEP_STUBS);
    doReturn(drive).when(dataSource).getDriveService();
    doReturn(utils).when(dataSource).getDriveUtils();
    inputProperties.getDatasetProperties().getDatastoreProperties().serviceAccountJSONFile.setValue("service.json");
    dataSource.initialize(container, inputProperties);

    About about = new About();
    User user = new User();
    user.setEmailAddress("[email protected]");
    about.setUser(user);
    when(drive.about().get().setFields(anyString()).execute()).thenReturn(about);
    assertEquals(Result.OK, dataSource.validate(container).getStatus());
}
 
Example #18
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
public void updateFile(SyncItem syncItem) {
	Drive drive = driveFactory.getDrive(this.credential);
	try {
		java.io.File localFile = syncItem.getLocalFile().get();
		File remoteFile = syncItem.getRemoteFile().get();
		BasicFileAttributes attr = Files.readAttributes(localFile.toPath(), BasicFileAttributes.class);
		remoteFile.setModifiedTime(new DateTime(attr.lastModifiedTime().toMillis()));
		if (isGoogleAppsDocument(remoteFile)) {
			return;
		}
		LOGGER.log(Level.INFO, "Updating file " + remoteFile.getId() + " (" + syncItem.getPath() + ").");
		if (!options.isDryRun()) {
			Drive.Files.Update updateRequest = drive.files().update(remoteFile.getId(), remoteFile, new FileContent(determineMimeType(localFile), localFile));
			//updateRequest.setModifiedDate(true);
			File updatedFile = executeWithRetry(options, () -> updateRequest.execute());
			syncItem.setRemoteFile(Optional.of(updatedFile));
		}
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to update file: " + e.getMessage(), e);
	}
}
 
Example #19
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
public List<File> listChildren(String parentId) {
	List<File> resultList = new LinkedList<File>();
	Drive drive = driveFactory.getDrive(this.credential);
	try {
		Drive.Files.List request = drive.files().list().setFields("nextPageToken, files");
		request.setQ("trashed = false and '" + parentId + "' in parents");
		request.setPageSize(1000);
		LOGGER.log(Level.FINE, "Listing children of folder " + parentId + ".");
		do {
			FileList fileList = executeWithRetry(options, () -> request.execute());
			List<File> items = fileList.getFiles();
			resultList.addAll(items);
			request.setPageToken(fileList.getNextPageToken());
		} while (request.getPageToken() != null && request.getPageToken().length() > 0);
		if (LOGGER.isLoggable(Level.FINE)) {
			for (File file : resultList) {
				LOGGER.log(Level.FINE, "Child of " + parentId + ": " + file.getId() + ";" + file.getName() + ";" + file.getMimeType());
			}
		}
		removeDuplicates(resultList);
		return resultList;
	} catch (IOException e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to execute list request: " + e.getMessage(), e);
	}
}
 
Example #20
Source File: GoogleDriveDatasetRuntimeTest.java    From components with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSample() throws Exception {
    rt = spy(rt);
    Drive drive = mock(Drive.class, RETURNS_DEEP_STUBS);
    GoogleDriveUtils utils = mock(GoogleDriveUtils.class, RETURNS_DEEP_STUBS);
    GoogleDriveDataSource source = mock(GoogleDriveDataSource.class);
    GoogleDriveInputReader reader = mock(GoogleDriveInputReader.class);
    //
    doReturn(source).when(rt).createDataSource(any());
    doReturn(reader).when(source).createReader(any());
    doReturn(drive).when(source).getDriveService();
    doReturn(utils).when(source).getDriveUtils();
    //
    rt.initialize(container, ds);
    rt.getSample(20, new Consumer<IndexedRecord>() {

        @Override
        public void accept(IndexedRecord indexedRecord) {
            assertNotNull(indexedRecord);
        }
    });
}
 
Example #21
Source File: GoogleDriveUtil.java    From algorithms-sedgewick-wayne with MIT License 6 votes vote down vote up
public static void updateWebPage(String webPageId, List<String> data) {
    try {
        Drive.Files driveFiles = driveService.files();

        File currentFile = driveFiles.get(webPageId).execute();
        String fileName = currentFile.getName();

        // Create file in staging area
        String filePath = STAGING_AREA_DIRECTORY_PATH + fileName;
        FileUtil.writeFile(filePath, data);

        java.io.File fileInStagingArea = new java.io.File(STAGING_AREA_DIRECTORY_PATH + fileName);
        FileContent fileContent = new FileContent(TEXT_PLAIN_TYPE, fileInStagingArea);

        driveFiles.update(webPageId, new File(), fileContent).execute();

        // Delete file from staging area
        FileUtil.deleteFile(filePath);
    } catch (IOException exception) {
        StdOut.println("There was an error when trying to update the web page with id " + webPageId + ".");
    }
}
 
Example #22
Source File: MainActivity.java    From android-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Handles the {@code result} of a completed sign-in activity initiated from {@link
 * #requestSignIn()}.
 */
private void handleSignInResult(Intent result) {
    GoogleSignIn.getSignedInAccountFromIntent(result)
            .addOnSuccessListener(googleAccount -> {
                    Log.d(TAG, "Signed in as " + googleAccount.getEmail());

                    // Use the authenticated account to sign in to the Drive service.
                    GoogleAccountCredential credential =
                        GoogleAccountCredential.usingOAuth2(
                                this, Collections.singleton(DriveScopes.DRIVE_FILE));
                    credential.setSelectedAccount(googleAccount.getAccount());
                    Drive googleDriveService =
                        new Drive.Builder(
                                AndroidHttp.newCompatibleTransport(),
                                new GsonFactory(),
                                credential)
                           .setApplicationName("Drive API Migration")
                           .build();

                    // The DriveServiceHelper encapsulates all REST API and SAF functionality.
                    // Its instantiation is required before handling any onClick actions.
                    mDriveServiceHelper = new DriveServiceHelper(googleDriveService);
                })
            .addOnFailureListener(exception -> Log.e(TAG, "Unable to sign in.", exception));
}
 
Example #23
Source File: SyncTestUtils.java    From mytracks with Apache License 2.0 6 votes vote down vote up
/**
 * Checks the files number on Google Drive
 * 
 * @param drive a Google Drive object
 * @throws IOException
 */
public static void checkFilesNumber(Drive drive) throws IOException {
  EndToEndTestUtils.instrumentation.waitForIdleSync();
  long startTime = System.currentTimeMillis();
  int trackNumber = EndToEndTestUtils.SOLO.getCurrentViews(ListView.class).get(0).getCount();
  List<File> files = getDriveFiles(EndToEndTestUtils.trackListActivity.getApplicationContext(),
      drive);
  while (System.currentTimeMillis() - startTime < MAX_TIME_TO_WAIT_SYNC) {
    try {
      if (files.size() == trackNumber) {
        return;
      }
      trackNumber = EndToEndTestUtils.SOLO.getCurrentViews(ListView.class).get(0).getCount();
      files = getDriveFiles(EndToEndTestUtils.trackListActivity.getApplicationContext(), drive);
      EndToEndTestUtils.sleep(EndToEndTestUtils.SHORT_WAIT_TIME);
      EndToEndTestUtils.findMenuItem(
          EndToEndTestUtils.trackListActivity.getString(R.string.menu_sync_now), true);
    } catch (GoogleJsonResponseException e) {
      Log.e(TAG, e.getMessage(), e);
    }
  }
  Assert.assertEquals(files.size(), trackNumber);
}
 
Example #24
Source File: GoogleUtils.java    From mytracks with Apache License 2.0 6 votes vote down vote up
/**
 * Searches Google Spreadsheets.
 * 
 * @param context the context
 * @param accountName the account name
 * @return the list of spreadsheets matching the title. Null if unable to
 *         search.
 */
public static List<File> searchSpreadsheets(Context context, String accountName) {
  try {
    GoogleAccountCredential googleAccountCredential = SendToGoogleUtils
        .getGoogleAccountCredential(context, accountName, SendToGoogleUtils.DRIVE_SCOPE);
    if (googleAccountCredential == null) {
      return null;
    }

    Drive drive = SyncUtils.getDriveService(googleAccountCredential);
    com.google.api.services.drive.Drive.Files.List list = drive.files().list().setQ(String.format(
        Locale.US, SendSpreadsheetsAsyncTask.GET_SPREADSHEET_QUERY, SPREADSHEETS_NAME));
    return list.execute().getItems();
  } catch (Exception e) {
    Log.e(TAG, "Unable to search spreadsheets.", e);
  }
  return null;
}
 
Example #25
Source File: GoogleDriveServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public boolean token(String userId, String code) {
	if (!isConfigured()) {
		return false;
	}

	try {
		GoogleTokenResponse googleResponse = flow.newTokenRequest(code)
				.setRedirectUri(redirectUri)
				.execute();
		Credential cred = flow.createAndStoreCredential(googleResponse, userId);

		service = new Drive.Builder(httpTransport, jsonFactory, cred)
			.setApplicationName(GOOGLEDRIVE_APP_NAME)
			.build();

		Drive.About about = service.about();
		Drive.About.Get get = about.get().setFields("user(displayName, emailAddress, permissionId)");
		About ab = get.execute();			
		log.debug("About : {}", ab.toString());
		
		GoogleDriveUser du = getGoogleDriveUser(userId);
		du.setGoogleDriveUserId(ab.getUser().getPermissionId());
		du.setGoogleDriveName(ab.getUser().getEmailAddress());
		googledriveRepo.update(du);
		return true;

	} catch(Exception e) {
		log.warn("GoogleDrive: Error while retrieving or saving the credentials for user {} : {}", userId, e.getMessage());
		revokeGoogleDriveConfiguration(userId);
	}
	return false;
}
 
Example #26
Source File: GoogleDriveServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void init() {
	log.debug("GoogleDriveServiceImpl init");
	OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	
	clientId = serverConfigurationService.getString(GOOGLEDRIVE_PREFIX + GOOGLEDRIVE_CLIENT_ID, null);
	clientSecret = serverConfigurationService.getString(GOOGLEDRIVE_PREFIX + GOOGLEDRIVE_CLIENT_SECRET, null);
	redirectUri = serverConfigurationService.getString(GOOGLEDRIVE_PREFIX + GOOGLEDRIVE_REDIRECT_URI, "http://localhost:8080/sakai-googledrive-tool");

	try {
		JsonNode rootNode = OBJECT_MAPPER.createObjectNode();
		JsonNode webInfo = OBJECT_MAPPER.createObjectNode();
		((ObjectNode) webInfo).put("client_id", clientId);
		//((ObjectNode) webInfo).put("project_id", "algebraic-creek-243007");
		((ObjectNode) webInfo).put("auth_uri", ENDPOINT_AUTH);
		((ObjectNode) webInfo).put("token_uri", ENDPOINT_TOKEN);
		((ObjectNode) webInfo).put("auth_provider_x509_cert_url", ENDPOINT_CERTS);
		((ObjectNode) webInfo).put("client_secret", clientSecret);
		((ObjectNode) rootNode).set("web", webInfo);
		InputStream isJson = IOUtils.toInputStream(rootNode.toString());
		isJson.close();//?

		httpTransport = GoogleNetHttpTransport.newTrustedTransport();
		jsonFactory = JacksonFactory.getDefaultInstance();
		clientSecrets = GoogleClientSecrets.load(jsonFactory, new InputStreamReader(isJson));

		DataStoreFactory dataStore = new JPADataStoreFactory(googledriveRepo);			
		flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, clientSecrets, Collections.singleton(DriveScopes.DRIVE))
				.setDataStoreFactory(dataStore)
				.setApprovalPrompt("force")
				.setAccessType("offline")
				.build();
	} catch(Exception e) {
		log.error("Error while trying to init Google Drive configuration");
	}

	driveRootItemsCache = memoryService.<String, List<GoogleDriveItem>>getCache("org.sakaiproject.googledrive.service.driveRootItemsCache");
	driveChildrenItemsCache = memoryService.<String, List<GoogleDriveItem>>getCache("org.sakaiproject.googledrive.service.driveChildrenItemsCache");
	googledriveUserCache = memoryService.<String, Drive>getCache("org.sakaiproject.googledrive.service.googledriveUserCache");
	driveItemsCache = memoryService.<String, GoogleDriveItem>getCache("org.sakaiproject.googledrive.service.driveItemsCache");
}
 
Example #27
Source File: GoogleDriveInputReaderTest.java    From components with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetLimit() throws Exception {
    dataSource = spy(dataSource);
    Drive drive = mock(Drive.class, RETURNS_DEEP_STUBS);
    GoogleDriveUtils utils = mock(GoogleDriveUtils.class, RETURNS_DEEP_STUBS);
    doReturn(drive).when(dataSource).getDriveService();
    doReturn(utils).when(dataSource).getDriveUtils();

    dataSource.initialize(container, inputProperties);
    reader = (GoogleDriveInputReader) dataSource.createReader(container);
    reader.setLimit(30);
    assertEquals(30, reader.getLimit());
}
 
Example #28
Source File: GoogleAuth.java    From oncokb with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void createDriveService() throws GeneralSecurityException,
    IOException, URISyntaxException {
    HttpTransport httpTransport = new NetHttpTransport();
    JacksonFactory jsonFactory = new JacksonFactory();
    DRIVE_SERVICE = new Drive.Builder(httpTransport, jsonFactory, null)
        .setApplicationName("Oncoreport")
        .setHttpRequestInitializer(CREDENTIAL).build();
}
 
Example #29
Source File: DriveImporter.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
private String importSingleFolder(Drive driveInterface, String folderName, String parentId)
    throws IOException {
  File newFolder = new File().setName(folderName).setMimeType(DriveExporter.FOLDER_MIME_TYPE);
  if (!Strings.isNullOrEmpty(parentId)) {
    newFolder.setParents(ImmutableList.of(parentId));
  }
  File resultFolder = driveInterface.files().create(newFolder).execute();
  return resultFolder.getId();
}
 
Example #30
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 5 votes vote down vote up
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]);
}