当前位置: 首页>>代码示例>>Java>>正文


Java Drive类代码示例

本文整理汇总了Java中com.google.api.services.drive.Drive的典型用法代码示例。如果您正苦于以下问题:Java Drive类的具体用法?Java Drive怎么用?Java Drive使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Drive类属于com.google.api.services.drive包,在下文中一共展示了Drive类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: authorize

import com.google.api.services.drive.Drive; //导入依赖的package包/类
/**
 * 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();

}
 
开发者ID:MrStahlfelge,项目名称:gdx-gamesvcs,代码行数:29,代码来源:GApiGateway.java

示例2: uploadFile

import com.google.api.services.drive.Drive; //导入依赖的package包/类
@Override
public void uploadFile(String path, byte[] data, boolean writeTransactional)
		throws Exception {
	logDebug("upload file...");		
	try
	{
		ByteArrayContent content = new ByteArrayContent(null, data);
		GDrivePath gdrivePath = new GDrivePath(path);
		Drive driveService = getDriveService(gdrivePath.getAccount());
		
		File driveFile = getFileForPath(gdrivePath, driveService);
		getDriveService(gdrivePath.getAccount()).files()
				.update(driveFile.getId(), driveFile, content).execute();
		logDebug("upload file ok.");
	}
	catch (Exception e)
	{
		throw convertException(e);
	}

}
 
开发者ID:PhilippC,项目名称:keepass2android,代码行数:22,代码来源:GoogleDriveFileStorage.java

示例3: mkdir

import com.google.api.services.drive.Drive; //导入依赖的package包/类
@Override
public Path mkdir(final Path folder, final String region, final TransferStatus status) throws BackgroundException {
    try {
        // 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(new DriveFileidProvider(session).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 PathAttributes(folder.attributes()));
    }
    catch(IOException e) {
        throw new DriveExceptionMappingService().map("Cannot create folder {0}", e, folder);
    }
}
 
开发者ID:iterate-ch,项目名称:cyberduck,代码行数:17,代码来源:DriveDirectoryFeature.java

示例4: downloadFile

import com.google.api.services.drive.Drive; //导入依赖的package包/类
public static void downloadFile(String name, String type) {
    try {
        Drive service = getDriveService();
        String destination = Config.getDestination();

        File parentFolder = getFolder(destination);
        File childFolder = getFolder(type, parentFolder);
        File backupToDownload = getFile(name, childFolder);

        java.io.File dirFile = new java.io.File("downloads/" + type);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        OutputStream out = new FileOutputStream("downloads/" + type + "/" + name);

        Drive.Files.Get request = service.files().get(backupToDownload.getId());
        request.executeMediaAndDownloadTo(out);
        MessageUtil.sendConsoleMessage("Done downloading '" + name + "' from google drive");
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
开发者ID:Ratismal,项目名称:DriveBackup,代码行数:24,代码来源:GoogleUploader.java

示例5: openFileForRead

import com.google.api.services.drive.Drive; //导入依赖的package包/类
@Override
public InputStream openFileForRead(String path) throws Exception {

	logDebug("openFileForRead...");
	GDrivePath gdrivePath = new GDrivePath(path);
	Drive driveService = getDriveService(gdrivePath.getAccount());

	try
	{
		File file = getFileForPath(gdrivePath, driveService);
		InputStream res =  getFileContent(file, driveService);
		logDebug("openFileForRead ok.");
		return res;
	}
	catch (Exception e)
	{
		throw convertException(e);
	}
}
 
开发者ID:PhilippC,项目名称:keepass2android,代码行数:20,代码来源:GoogleDriveFileStorage.java

示例6: getBackupFileId

import com.google.api.services.drive.Drive; //导入依赖的package包/类
public static String getBackupFileId(Drive service, String folderId) throws IOException {
    if (folderId == null) {
        return null;
    }

    FileList jsonFile = service.files().list()
            .setQ("\'" + folderId + "\' in parents and name = \'" + BACKUP_DB_FILE_NAME + "\'")
            .setPageSize(1)
            .setFields("files(id)")
            .execute();

    if (jsonFile.getFiles() == null) {
        return null;
    } else if (jsonFile.getFiles().size() != 1) {
        Log.e(LOG_TAG, "There are more files " + BACKUP_DB_FILE_NAME + " in your FuelUp folder on Google Drive.");
        // TODO handle this with message
        return null;
    }
    return jsonFile.getFiles().get(0).getId();
}
 
开发者ID:piskula,项目名称:FuelUp,代码行数:21,代码来源:DriveBackupFileUtil.java

示例7: getBackupFolderId

import com.google.api.services.drive.Drive; //导入依赖的package包/类
public static String getBackupFolderId(Drive service) throws IOException {
    FileList fuelUpFolder = service.files().list()
            .setQ("\'root\' in parents and name = \'"+ BACKUP_DB_FOLDER +"\'")
            .setPageSize(1)
            .setFields("files(id)")
            .execute();
    if (fuelUpFolder.getFiles() == null) {
        return null;
    } else if (fuelUpFolder.getFiles().size() != 1) {
        Log.e(LOG_TAG, "There are more folders " + BACKUP_DB_FOLDER + " on your Google Drive Account.");
        // TODO handle this with message
        return null;
    }

    return fuelUpFolder.getFiles().get(0).getId();
}
 
开发者ID:piskula,项目名称:FuelUp,代码行数:17,代码来源:DriveBackupFileUtil.java

示例8: touch

import com.google.api.services.drive.Drive; //导入依赖的package包/类
@Override
public Path touch(final Path file, final TransferStatus status) throws BackgroundException {
    try {
        final Drive.Files.Create insert = session.getClient().files().create(new File()
                .setName(file.getName())
                .setMimeType(status.getMime())
                .setParents(Collections.singletonList(new DriveFileidProvider(session).getFileid(file.getParent(), new DisabledListProgressListener()))));
        final File execute = insert.
            setSupportsTeamDrives(PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable")).execute();
        return new Path(file.getParent(), file.getName(), file.getType(),
                new PathAttributes(file.attributes()).withVersionId(execute.getId()));
    }
    catch(IOException e) {
        throw new DriveExceptionMappingService().map("Cannot create file {0}", e, file);
    }
}
 
开发者ID:iterate-ch,项目名称:cyberduck,代码行数:17,代码来源:DriveTouchFeature.java

示例9: connect

import com.google.api.services.drive.Drive; //导入依赖的package包/类
@Override
protected Drive connect(final HostKeyCallback callback, final LoginCallback prompt) {
    authorizationService = new OAuth2RequestInterceptor(builder.build(this, prompt).build(), host.getProtocol())
        .withRedirectUri(host.getProtocol().getOAuthRedirectUrl());
    final HttpClientBuilder configuration = builder.build(this, prompt);
    configuration.addInterceptorLast(authorizationService);
    configuration.setServiceUnavailableRetryStrategy(new OAuth2ErrorResponseInterceptor(authorizationService));
    this.transport = new ApacheHttpTransport(configuration.build());
    return new Drive.Builder(transport, json, new HttpRequestInitializer() {
        @Override
        public void initialize(HttpRequest request) throws IOException {
            request.setSuppressUserAgentSuffix(true);
            // OAuth Bearer added in interceptor
        }
    })
        .setApplicationName(useragent.get())
        .build();
}
 
开发者ID:iterate-ch,项目名称:cyberduck,代码行数:19,代码来源:DriveSession.java

示例10: getOrCreateDriveFolder

import com.google.api.services.drive.Drive; //导入依赖的package包/类
public static String getOrCreateDriveFolder(Drive drive, String targetFolder) throws IOException {
    String folderId = null;
    FileList folders = drive.files().list().setQ("mimeType='application/vnd.google-apps.folder'").execute();
    for (com.google.api.services.drive.model.File f : folders.getItems()) {
        if (f.getTitle().equals(targetFolder)) {
            folderId = f.getId();
        }
    }
    //if not found create it
    if (folderId == null) {
        com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File();
        body.setTitle(targetFolder);
        body.setMimeType("application/vnd.google-apps.folder");
        com.google.api.services.drive.model.File file = drive.files().insert(body).execute();
        folderId = file.getId();
    }
    return folderId;
}
 
开发者ID:tiberiusteng,项目名称:financisto1-holo,代码行数:19,代码来源:GoogleDriveClient.java

示例11: setPermission

import com.google.api.services.drive.Drive; //导入依赖的package包/类
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;
}
 
开发者ID:Plonk42,项目名称:mytracks,代码行数:23,代码来源:SendFusionTablesAsyncTask.java

示例12: searchSpreadsheets

import com.google.api.services.drive.Drive; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:Plonk42,项目名称:mytracks,代码行数:26,代码来源:GoogleUtils.java

示例13: setUpForSyncTest

import com.google.api.services.drive.Drive; //导入依赖的package包/类
/**
 * Sets up sync tests.
 * 
 * @param instrumentation the instrumentation is used for test
 * @param trackListActivity the startup activity
 * @return a Google Drive object
 */
public static Drive setUpForSyncTest(Instrumentation instrumentation,
    TrackListActivity trackListActivity) throws IOException, GoogleAuthException {
  if (!isCheckedRunSyncTest || RunConfiguration.getInstance().getRunSyncTest()) {
    EndToEndTestUtils.setupForAllTest(instrumentation, trackListActivity);
  }
  if (!isCheckedRunSyncTest) {
    isCheckedRunSyncTest = true;
  }
  if (RunConfiguration.getInstance().getRunSyncTest()) {
    enableSync(GoogleUtils.ACCOUNT_1);
    Drive drive1 = getGoogleDrive(EndToEndTestUtils.trackListActivity.getApplicationContext());
    removeKMLFiles(drive1);
    EndToEndTestUtils.deleteAllTracks();
    enableSync(GoogleUtils.ACCOUNT_2);
    Drive drive2 = getGoogleDrive(EndToEndTestUtils.trackListActivity.getApplicationContext());
    removeKMLFiles(drive2);
    EndToEndTestUtils.deleteAllTracks();
    return drive2;
  }
  return null;
}
 
开发者ID:Plonk42,项目名称:mytracks,代码行数:29,代码来源:SyncTestUtils.java

示例14: checkFilesNumber

import com.google.api.services.drive.Drive; //导入依赖的package包/类
/**
 * 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);
}
 
开发者ID:Plonk42,项目名称:mytracks,代码行数:29,代码来源:SyncTestUtils.java

示例15: downloadFile

import com.google.api.services.drive.Drive; //导入依赖的package包/类
private String downloadFile(String resourceId) throws Exception {
    Log.d(TAG, String.format("Downloading resource: %s ...", resourceId));

    Drive.Files.Get getFile = mService.files().get(resourceId);
    File fileDrive = getFile.execute();
    Log.d(TAG, "\tfilename: " + fileDrive.getName());

    if(fileDrive.getName().endsWith(QUICKTIME_NON_SUPPORTED_FORMAT)){
        throw new IllegalStateException(String.format("%s format not supported in Android",fileDrive.getName()));
    }

    java.io.File localFile = new java.io.File(DashboardActivity.dashboardActivity.getFilesDir(), fileDrive.getName());
    FileOutputStream fileOutputStream = new FileOutputStream(localFile);
    getFile.executeMediaAndDownloadTo(fileOutputStream);
    fileOutputStream.close();
    return localFile.getAbsolutePath();
}
 
开发者ID:EyeSeeTea,项目名称:EDSApp,代码行数:18,代码来源:DownloadMediaTask.java


注:本文中的com.google.api.services.drive.Drive类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。