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

The following examples show how to use com.google.api.services.drive.DriveScopes. 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: 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 #2
Source File: BaseMainDbActivity.java    From dbsync with Apache License 2.0 6 votes vote down vote up
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, Arrays.asList(DriveScopes.DRIVE_FILE, DriveScopes.DRIVE_METADATA, DriveScopes.DRIVE_READONLY,
                                        DriveScopes.DRIVE_METADATA_READONLY, DriveScopes.DRIVE_PHOTOS_READONLY));
                credential.setSelectedAccount(googleAccount.getAccount());

                googleDriveService =
                        new com.google.api.services.drive.Drive.Builder(
                                AndroidHttp.newCompatibleTransport(),
                                new GsonFactory(),
                                credential)
                                .setApplicationName("Drive API DBSync")
                                .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 #3
Source File: BaseMainDbActivity.java    From dbsync with Apache License 2.0 6 votes vote down vote up
private void handleSignInONRecnnect() {
    GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);

    if  (account != null ){
        Log.d(TAG, "Signed in as " + account.getEmail());

        // Use the authenticated account to sign in to the Drive service.
        GoogleAccountCredential credential =
                GoogleAccountCredential.usingOAuth2(
                        this, Collections.singleton(DriveScopes.DRIVE_FILE));
        credential.setSelectedAccount(account.getAccount());

        googleDriveService =
                new com.google.api.services.drive.Drive.Builder(
                        AndroidHttp.newCompatibleTransport(),
                        new GsonFactory(),
                        credential)
                        .setApplicationName("Drive API DBSync")
                        .build();
    }
}
 
Example #4
Source File: TGDriveBrowserLogin.java    From tuxguitar with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void process() {
	this.authRequestResultHandler = this.createAuthRequestResultHandler();
	this.accountRequestResultHandler = this.createAccountRequestResultHandler();
	
	this.activity.getResultManager().addHandler(this.authRequestCode, this.authRequestResultHandler);
   	this.activity.getResultManager().addHandler(this.accountRequestCode, this.accountRequestResultHandler);
   	
	this.credential = GoogleAccountCredential.usingOAuth2(this.activity, Collections.singleton(DriveScopes.DRIVE));
	if(!this.settings.isDefaultAccount()) {
		this.credential.setSelectedAccountName(this.settings.getAccount());
	} else {
		String defaultAccount = this.getDefaultAccount();
		if( defaultAccount != null ) {
			this.credential.setSelectedAccountName(defaultAccount);
		}
	}
	this.createTokenAsyncTask().execute((Void) null);
}
 
Example #5
Source File: GoogleDriveFactory.java    From google-drive-ftp-adapter with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Authorizes the installed application to access user's protected data.
 */
private Credential authorize() throws Exception {
    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
            new InputStreamReader(GFile.class.getResourceAsStream("/client_secrets.json")));
    if (clientSecrets.getDetails().getClientId().startsWith("Enter")
            || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
        System.out.println("Overwrite the src/main/resources/client_secrets.json file with the client secrets file "
                + "you downloaded from the Quickstart tool or manually enter your Client ID and Secret "
                + "from https://code.google.com/apis/console/?api=drive#project:275751503302 "
                + "into src/main/resources/client_secrets.json");
        System.exit(1);
    }
    // set up authorization code flow
    Set<String> scopes = new HashSet<>();
    scopes.add(DriveScopes.DRIVE);
    scopes.add(DriveScopes.DRIVE_METADATA);

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY, clientSecrets, scopes)
            .setDataStoreFactory(dataStoreFactory).build();
    // authorize
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver.Builder().setPort(authPort).build()).authorize("user");
}
 
Example #6
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 #7
Source File: BaseMainDbActivity.java    From dbsync with Apache License 2.0 5 votes vote down vote up
/**
 * Build a Google SignIn client.
 */
private GoogleSignInClient buildGoogleSignInClient() {
    GoogleSignInOptions signInOptions =
            new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestScopes(new Scope(DriveScopes.DRIVE))
                    .requestScopes(new Scope(DriveScopes.DRIVE_FILE))
                    .requestScopes(new Scope(DriveScopes.DRIVE_METADATA))
                    .requestScopes(new Scope(DriveScopes.DRIVE_READONLY))
                    .requestScopes(new Scope(DriveScopes.DRIVE_METADATA_READONLY))
                    .requestScopes(new Scope(DriveScopes.DRIVE_PHOTOS_READONLY))
                    .requestEmail()
                    .build();
    return GoogleSignIn.getClient(this, signInOptions);
}
 
Example #8
Source File: DriveSyncService.java    From narrate-android with Apache License 2.0 5 votes vote down vote up
public DriveSyncService() throws UserRecoverableAuthException {
    super(SyncService.GoogleDrive);

    try {
        HttpTransport httpTransport = new NetHttpTransport();
        JsonFactory jsonFactory = new JacksonFactory();

        String token = GoogleAuthUtil.getToken(GlobalApplication.getAppContext(), Settings.getEmail(), "oauth2:" + DriveScopes.DRIVE_APPDATA);

        if (SettingsUtil.shouldRefreshGDriveToken()) {
            GoogleAuthUtil.clearToken(GlobalApplication.getAppContext(), token);
            token = GoogleAuthUtil.getToken(GlobalApplication.getAppContext(), Settings.getEmail(), "oauth2:" + DriveScopes.DRIVE_APPDATA);
            SettingsUtil.refreshGDriveToken();
        }

        if (BuildConfig.DEBUG)
            LogUtil.log(getClass().getSimpleName(), "Access Token: " + token);

        GoogleCredential credential = new GoogleCredential().setAccessToken(token);
        service = new Drive.Builder(httpTransport, jsonFactory, credential).setApplicationName("Narrate").build();

    } catch (UserRecoverableAuthException ue) {
        throw ue;
    } catch (Exception e) {
        LogUtil.log(getClass().getSimpleName(), "Exception in creation: " + e);
        if (!BuildConfig.DEBUG) Crashlytics.logException(e);
    }

    if (CLEAR_FOLDER_CONTENTS) {
        deleteEverything();
    }
}
 
Example #9
Source File: GoogleAuth.java    From oncokb with GNU Affero General Public License v3.0 5 votes vote down vote up
private static List<String> getScopes() {
    List<String> scopes = new ArrayList<String>();

    scopes.add("https://spreadsheets.google.com/feeds");
    scopes.add("https://www.googleapis.com/auth/gmail.compose");

    scopes.addAll(DriveScopes.all());
    return scopes;
}
 
Example #10
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 #11
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 #12
Source File: MainActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Starts a sign-in activity using {@link #REQUEST_CODE_SIGN_IN}.
 */
private void requestSignIn() {
    Log.d(TAG, "Requesting sign-in");

    GoogleSignInOptions signInOptions =
            new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestEmail()
                    .requestScopes(new Scope(DriveScopes.DRIVE_FILE))
                    .build();
    GoogleSignInClient client = GoogleSignIn.getClient(this, signInOptions);

    // The result of the sign-in Intent is handled in onActivityResult.
    startActivityForResult(client.getSignInIntent(), REQUEST_CODE_SIGN_IN);
}
 
Example #13
Source File: BaseTest.java    From java-samples with Apache License 2.0 4 votes vote down vote up
public GoogleCredential getCredential() throws IOException {
    return GoogleCredential.getApplicationDefault()
            .createScoped(Arrays.asList(DriveScopes.DRIVE));
}
 
Example #14
Source File: BaseTest.java    From java-samples with Apache License 2.0 4 votes vote down vote up
public GoogleCredential getCredential() throws IOException {
  return GoogleCredential.getApplicationDefault()
      .createScoped(Arrays.asList(DriveScopes.DRIVE));
}