com.google.android.gms.auth.GoogleAuthException Java Examples

The following examples show how to use com.google.android.gms.auth.GoogleAuthException. 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: 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 #2
Source File: GoogleAccountCredential.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an OAuth 2.0 access token.
 *
 * <p>
 * Must be run from a background thread, not the main UI thread.
 * </p>
 */
public String getToken() throws IOException, GoogleAuthException {
  if (backOff != null) {
    backOff.reset();
  }

  while (true) {
    try {
      return GoogleAuthUtil.getToken(context, accountName, scope);
    } catch (IOException e) {
      // network or server error, so retry using back-off policy
      try {
        if (backOff == null || !BackOffUtils.next(sleeper, backOff)) {
          throw e;
        }
      } catch (InterruptedException e2) {
        // ignore
      }
    }
  }
}
 
Example #3
Source File: SyncTestUtils.java    From mytracks with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #4
Source File: MainActivity.java    From SyncManagerAndroid-DemoGoogleTasks with MIT License 6 votes vote down vote up
/**
 * Gets an authentication token from Google and handles any
 * GoogleAuthException that may occur.
 */
protected String fetchToken() throws IOException {
    try {
        return GoogleAuthUtil.getToken(MainActivity.this, mEmailText, mScope);
    } catch (UserRecoverableAuthException userRecoverableException) {
        // GooglePlayServices.apk is either old, disabled, or not present
        // so we need to show the user some UI in the activity to recover.
        //mActivity.handleException(userRecoverableException);
    	//Log.e(TAG, userRecoverableException.getMessage(), userRecoverableException);
    	
    	mException = userRecoverableException;
    } catch (GoogleAuthException fatalException) {
        // Some other type of unrecoverable exception has occurred.
        // Report and log the error as appropriate for your app.
    	Log.e(TAG, fatalException.getMessage(), fatalException);
    }
    return null;
}
 
Example #5
Source File: TaskSyncAdapter.java    From SyncManagerAndroid-DemoGoogleTasks with MIT License 6 votes vote down vote up
private String getGoogleAuthToken() throws IOException {
	String googleUserName = PrefsUtil.retrieveGoogleTasksUser(mContext);
	
	String token = "";
	try {
		Log.d(TAG, "getGoogleAuthToken... "+googleUserName);
		token = GoogleAuthUtil.getTokenWithNotification(mContext,
				googleUserName, GoogleTaskApiService.SCOPE, null);
	} catch (UserRecoverableNotifiedException userNotifiedException) {
		// Notification has already been pushed.
		// Continue without token or stop background task.
	} catch (GoogleAuthException authEx) {
		// This is likely unrecoverable.
		Log.e(TAG,
				"Unrecoverable authentication exception: "
						+ authEx.getMessage(), authEx);
	}
	return token;
}
 
Example #6
Source File: Utils.java    From SimplePomodoro-android with MIT License 5 votes vote down vote up
/**
 * Logs the given throwable and shows an error alert dialog with its message.
 * 
 * @param activity activity
 * @param tag log tag to use
 * @param t throwable to log and show
 */
public static void logAndShow(Activity activity, String tag, Throwable t) {
  Log.e(tag, "Error", t);
  String message = t.getMessage();
  if (t instanceof GoogleJsonResponseException) {
    GoogleJsonError details = ((GoogleJsonResponseException) t).getDetails();
    if (details != null) {
      message = details.getMessage();
    }
  } else if (t.getCause() instanceof GoogleAuthException) {
    message = ((GoogleAuthException) t.getCause()).getMessage();
  }
  showError(activity, message);
}
 
Example #7
Source File: GoogleAccountCredential.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
@Override
public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry)
    throws IOException {
  try {
    if (response.getStatusCode() == 401 && !received401) {
      received401 = true;
      GoogleAuthUtil.clearToken(context, token);
      return true;
    }
  } catch (GoogleAuthException e) {
    throw new GoogleAuthIOException(e);
  }
  return false;
}
 
Example #8
Source File: MainActivity.java    From apps-script-mobile-addons with Apache License 2.0 5 votes vote down vote up
/**
 * Given a script function and a list of parameter objects, create a
 * request and run it with the API.
 * @param functionName script function name to call
 * @param params parameters needed by that function; may be null
 * @return Object returned from a successful execution; may be null
 * @throws IOException
 * @throws GoogleAuthException
 */
protected Object executeCall(String functionName, List<Object> params)
        throws IOException, GoogleAuthException {
    // Create execution request.
    ExecutionRequest request = new ExecutionRequest()
            .setFunction(functionName)
            .setSessionState(mState);
    if (params != null) {
        request.setParameters(params);
    }

    // Call the API and return the results (as an Operation object).
    Operation op = mService.scripts().run(SCRIPT_ID, request).execute();

    // If the response from the API contains an error, throw an
    // exception to display it.
    if (op.getError() != null) {
        throw new IOException(getScriptError(op));
    }

    // Return null if the API didn't yield a result.
    if (op.getResponse() == null ||
            op.getResponse().get("result") == null) {
        return null;
    }

    return op.getResponse().get("result");
}
 
Example #9
Source File: SendToGoogleUtils.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the google account credential.
 * 
 * @param context the context
 * @param accountName the account name
 * @param scope the scope
 */
public static GoogleAccountCredential getGoogleAccountCredential(
    Context context, String accountName, String scope) throws IOException, GoogleAuthException {
  GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(context, scope);
  credential.setSelectedAccountName(accountName);
  credential.getToken();
  return credential;
}
 
Example #10
Source File: SyncTestUtils.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * Gets drive object of Google Drive.
 * 
 * @param context the context of application
 * @return a Google Drive object
 */
public static Drive getGoogleDrive(Context context) throws IOException, GoogleAuthException {
  String googleAccount = PreferencesUtils.getString(context, R.string.google_account_key,
      PreferencesUtils.GOOGLE_ACCOUNT_DEFAULT);
  GoogleAccountCredential credential = SendToGoogleUtils.getGoogleAccountCredential(context,
      googleAccount, SendToGoogleUtils.DRIVE_SCOPE);
  return SyncUtils.getDriveService(credential);
}
 
Example #11
Source File: RNGoogleSigninModule.java    From google-signin with MIT License 5 votes vote down vote up
private void insertAccessTokenIntoUserProperties(RNGoogleSigninModule moduleInstance, WritableMap userProperties) throws IOException, GoogleAuthException {
    String mail = userProperties.getMap("user").getString("email");
    String token = GoogleAuthUtil.getToken(moduleInstance.getReactApplicationContext(),
            new Account(mail, "com.google"),
            scopesToString(userProperties.getArray("scopes")));

    userProperties.putString("accessToken", token);
}
 
Example #12
Source File: GoogleAuthHelper.java    From ribot-app-android with Apache License 2.0 5 votes vote down vote up
public String retrieveAuthToken(Account account)
        throws GoogleAuthException, IOException {

    String token = GoogleAuthUtil.getToken(mContext, account, SCOPE);
    // Token needs to be clear so we make sure next time we get a brand new one. Otherwise this
    // may return a token that has already been used by the API and because it's a one time
    // token it won't work.
    GoogleAuthUtil.clearToken(mContext, token);
    return token;
}
 
Example #13
Source File: GoogleOauth2.java    From edx-app-android with Apache License 2.0 5 votes vote down vote up
/**
 * Gets an authentication token from Google and handles any
 * GoogleAuthException that may occur.
 */
protected String fetchToken() throws IOException {
    if ( activity == null )
        return null;
    try {
        logger.debug("Fetching google oauth2 token ...");
        return GoogleAuthUtil.getToken(activity, mEmail, mScope);
    } catch (UserRecoverableAuthException userRecoverableException) {
        // GooglePlayServices.apk is either old, disabled, or not present
        // so we need to show the user some UI in the activity to recover.
        logger.debug("User recoverable error occurred");
        logger.error(userRecoverableException);
        
        // Requesting an authorization code will always throw
          // UserRecoverableAuthException on the first call to GoogleAuthUtil.getToken
          // because the user must consent to offline access to their data.  After
          // consent is granted control is returned to your activity in onActivityResult
          // and the second call to GoogleAuthUtil.getToken will succeed.
        if (activity != null && userRecoverableException.getIntent() != null) {
            activity.startActivityForResult(userRecoverableException.getIntent(), REQUEST_AUTHORIZATION);
        }
    } catch (GoogleAuthException fatalException) {
        logger.warn("google auth error occurred");
        // Some other type of unrecoverable exception has occurred.
        // Report and log the error as appropriate for your app.
        logger.error(fatalException);
    }
    return null;
}
 
Example #14
Source File: GoogleAccountsService.java    From narrate-android with Apache License 2.0 4 votes vote down vote up
public static boolean invalidateToken(String token) throws IOException, GoogleAuthException {
    GoogleAuthUtil.clearToken(GlobalApplication.getAppContext(), token);
    return true;
}
 
Example #15
Source File: GoogleDriveTransport.java    From CameraV with GNU General Public License v3.0 4 votes vote down vote up
public void doAuth () throws OperationCanceledException, AuthenticatorException, IOException, UserRecoverableNotifiedException, GoogleAuthException
{
	
	Bundle bund = new Bundle();
	token = GoogleAuthUtil.getTokenWithNotification(InformaService.getInstance().getApplicationContext(), account.name, Models.ITransportStub.GoogleDrive.SCOPE,bund);
	
	if (bund.containsKey(AccountManager.KEY_AUTHTOKEN))	
		token = bund.getString(AccountManager.KEY_AUTHTOKEN);

	/**
	if (token != null)
		am.invalidateAuthToken(Models.ITransportStub.GoogleDrive.SCOPE, token);

	
	AccountManagerFuture<Bundle> response = am.getAuthToken(account, Models.ITransportStub.GoogleDrive.SCOPE, true, new AccountManagerCallback<Bundle> () {

		@Override
		public void run(AccountManagerFuture<Bundle> result) {
            try {
				token = result.getResult().getString(AccountManager.KEY_AUTHTOKEN);
            	
			} catch (OperationCanceledException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (AuthenticatorException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		
	}, null);
	
	Bundle b;
	b = response.getResult();
	token = b.getString(AccountManager.KEY_AUTHTOKEN);
		
				*/
	
}
 
Example #16
Source File: GoogleAuthIOException.java    From google-api-java-client with Apache License 2.0 4 votes vote down vote up
@Override
public GoogleAuthException getCause() {
  return (GoogleAuthException) super.getCause();
}
 
Example #17
Source File: AccountIdProvider.java    From 365browser with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a stable id for the account associated with the given email address.
 * If an account with the given email address is not installed on the device
 * then null is returned.
 *
 * This method will throw IllegalStateException if called on the main thread.
 *
 * @param accountName The email address of a Google account.
 */
public String getAccountId(String accountName) {
    try {
        return GoogleAuthUtil.getAccountId(ContextUtils.getApplicationContext(), accountName);
    } catch (IOException | GoogleAuthException ex) {
        Log.e("cr.AccountIdProvider", "AccountIdProvider.getAccountId", ex);
        return null;
    }
}
 
Example #18
Source File: SendToGoogleUtils.java    From mytracks with Apache License 2.0 3 votes vote down vote up
/**
 * Gets the OAuth2 token.
 * 
 * @param context the context
 * @param accountName the account name
 * @param scope the scope
 */
public static String getToken(Context context, String accountName, String scope)
    throws IOException, GoogleAuthException {
  GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(context, scope);
  credential.setSelectedAccountName(accountName);
  return credential.getToken();
}
 
Example #19
Source File: AccountIdProvider.java    From AndroidChromium with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a stable id for the account associated with the given email address.
 * If an account with the given email address is not installed on the device
 * then null is returned.
 *
 * This method will throw IllegalStateException if called on the main thread.
 *
 * @param accountName The email address of a Google account.
 */
public String getAccountId(Context ctx, String accountName) {
    try {
        return GoogleAuthUtil.getAccountId(ctx, accountName);
    } catch (IOException | GoogleAuthException ex) {
        Log.e("cr.AccountIdProvider", "AccountIdProvider.getAccountId", ex);
        return null;
    }
}
 
Example #20
Source File: AccountIdProvider.java    From delion with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a stable id for the account associated with the given email address.
 * If an account with the given email address is not installed on the device
 * then null is returned.
 *
 * This method will throw IllegalStateException if called on the main thread.
 *
 * @param accountName The email address of a Google account.
 */
public String getAccountId(Context ctx, String accountName) {
    try {
        return GoogleAuthUtil.getAccountId(ctx, accountName);
    } catch (IOException | GoogleAuthException ex) {
        Log.e("cr.AccountIdProvider", "AccountIdProvider.getAccountId", ex);
        return null;
    }
}
 
Example #21
Source File: GoogleAuthIOException.java    From google-api-java-client with Apache License 2.0 2 votes vote down vote up
/**
 * @param wrapped wrapped {@link GoogleAuthException}
 * @since 1.21.0
 */
public GoogleAuthIOException(GoogleAuthException wrapped) {
  initCause(Preconditions.checkNotNull(wrapped));
}
 
Example #22
Source File: GoogleAccountsService.java    From narrate-android with Apache License 2.0 2 votes vote down vote up
/**
 * This method is used to retrieve an Oauth2 token to authenticate with Google's REST APIs.
 * For some reason, using Google Play Service's
 *
 * @param scope This is the Authorization scope that defines the permissions for the Oauth token.
 *              For more info on the scopes for Google Drive, see:
 *              https://developers.google.com/drive/v3/web/about-auth
 *
 * @return Oauth2 token that can be used as a Bearer to authenticate with Google's REST APIs
 */
public static String getAuthToken(String scope) throws MissingGoogleAccountException, PermissionsException, IOException, GoogleAuthException {
    Account acc = getAccount();
    String token = GoogleAuthUtil.getToken(GlobalApplication.getAppContext(), acc, "oauth2:" + scope);
    return token;
}