private void syncLogon4LetvPhone() { new Thread() { public void run() { try { String blockingGetAuthToken = LogonManager.this.accountManager.blockingGetAuthToken(LogonManager.this.accounts[0], LogonManager.this.AUTH_TOKEN_TYPE_LETV, true); LemallPlatform.getInstance().setSsoToken(blockingGetAuthToken); LogonManager.this.syncToken4Logon(blockingGetAuthToken, (IWebviewListener) LogonManager.this.context); } catch (OperationCanceledException e) { e.printStackTrace(); } catch (AuthenticatorException e2) { e2.printStackTrace(); } catch (IOException e3) { e3.printStackTrace(); } } }.start(); }
protected Bundle doInBackground(Void... params) { try { return this.this$0.tryAddXiaomiAccount(this.val$activity); } catch (SecurityException e) { e.printStackTrace(); this.retryWebViewWay = true; return null; } catch (OperationCanceledException e2) { e2.printStackTrace(); return null; } catch (AuthenticatorException e3) { e3.printStackTrace(); this.retryWebViewWay = true; return null; } catch (IOException e4) { e4.printStackTrace(); return null; } }
private void addNewAccount() { mAccountManager.addAccount(EnlightnsAccountAuthenticator.ACCOUNT_TYPE, EnlightnsAccountAuthenticator.AUTH_TOKEN_TYPE, null, null, this, new AccountManagerCallback<Bundle>() { @Override public void run(AccountManagerFuture<Bundle> future) { try { Bundle bnd = future.getResult(); showMessage(getString(R.string.successful_login_toast)); new GetUserRecordsTask().execute(); Log.d(TAG, "AddNewAccount Bundle is " + bnd); } catch (OperationCanceledException oce) { Log.d(TAG, "Operation cancelled, no account available, exiting...", oce); finish(); } catch (Exception e) { Log.w(TAG, "Exception", e); showMessage(getString(R.string.login_error)); } } }, null); }
@Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { try { String username = mAccountManager.blockingGetAuthToken(account, AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS, true); SyncServerInterface serverInterface = new SyncServerInterface(getContext()); User user = serverInterface.getUserInfo(username); UserContentHelper.clearUsers(getContext()); if (user != null) { UserContentHelper.addUser(getContext(), user); } } catch (OperationCanceledException | IOException | AuthenticatorException e) { e.printStackTrace(); syncResult.stats.numParseExceptions++; } }
public Account[] a(String paramString, String[] paramArrayOfString) { try { Account[] arrayOfAccount = (Account[])AccountManager.get(this.a).getAccountsByTypeAndFeatures(paramString, paramArrayOfString, null, null).getResult(b, TimeUnit.MILLISECONDS); return arrayOfAccount; } catch (AuthenticatorException localAuthenticatorException) { throw new fpv(localAuthenticatorException); } catch (OperationCanceledException localOperationCanceledException) { throw new IOException(localOperationCanceledException); } }
public void run(AccountManagerFuture<Bundle> result) { Bundle bundle; try { bundle = result.getResult(); Intent intent = (Intent)bundle.get(AccountManager.KEY_INTENT); if(intent != null) { // User input required context.startActivity(intent); } else { AccountManager.get(context).invalidateAuthToken(bundle.getString(AccountManager.KEY_ACCOUNT_TYPE), bundle.getString(AccountManager.KEY_AUTHTOKEN)); AccountManager.get(context).invalidateAuthToken("ah", bundle.getString(AccountManager.KEY_AUTHTOKEN)); onGetAuthToken(bundle); } } catch (OperationCanceledException | AuthenticatorException | IOException e) { //notifyUser(context.getString(R.string.flowzr_sync_error_no_network), 100); //showErrorPopup(FlowzrSyncActivity.this, R.string.flowzr_sync_error_no_network); //context.setReady(); e.printStackTrace(); } }
@Override public AndroidToken getToken(Account account, AndroidTokenType type) throws AuthenticationCanceledException { try { AndroidToken token; Activity activity = activityManager.getActivity(); if (account == null) { token = createAccountAndGetToken(activity, type); } else { token = getToken(activity, account, type); } if (token == null) { throw new AuthenticationCanceledException("user canceled the login!"); } return token; } catch (AuthenticatorException | OperationCanceledException | IOException e) { throw new AuthenticationCanceledException(e); } }
private AndroidToken createAccountAndGetToken(@Nullable Activity activity, @NonNull AndroidTokenType type) throws AuthenticatorException, OperationCanceledException, IOException { AccountManagerFuture<Bundle> future = accountManager .addAccount(type.accountType, type.tokenType, null, null, activity, null, null); Bundle result = future.getResult(); String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME); if (accountName != null) { Account account = new Account(result.getString(AccountManager.KEY_ACCOUNT_NAME), result.getString(AccountManager.KEY_ACCOUNT_TYPE)); String token = accountManager.peekAuthToken(account, type.tokenType); String refreshToken = accountManager.peekAuthToken(account, getRefreshTokenType(type)); if (token != null) return new AndroidToken(token, refreshToken); } return null; }
@Override protected Token getToken() throws AuthFailureError { String tokenStr; try { // NOTE: We pass true for notifyAuthFailure for clarity, but our authenticator always // assumes it is true, because AccountManager#KEY_NOTIFY_ON_FAILURE is a hidden API. tokenStr = mAccountManager.blockingGetAuthToken( mAccount, AccountAuthenticator.TOKEN_TYPE_OAUTH, true /* notifyAuthFailure */); } catch (AuthenticatorException | OperationCanceledException | IOException e) { throw new AuthFailureError("Unable to obtain auth token", e); } mToken = WireUtil.decodeFromString(tokenStr, Token.class); if (mToken == null) { throw new AuthFailureError("Error decoding token string"); } return mToken; }
@Override public OwnCloudClient getClientFor(OwnCloudAccount account, Context context) throws AccountNotFoundException, OperationCanceledException, AuthenticatorException, IOException { Log_OC.d(TAG, "getClientFor(OwnCloudAccount ... : "); OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient( account.getBaseUri(), context.getApplicationContext(), true); Log_OC.v(TAG, " new client {" + (account.getName() != null ? account.getName() : AccountUtils.buildAccountName(account.getBaseUri(), "") ) + ", " + client.hashCode() + "}"); if (account.getCredentials() == null) { account.loadCredentials(context); } client.setCredentials(account.getCredentials()); return client; }
@Override public void saveAllClients(Context context, String accountType) throws AccountNotFoundException, AuthenticatorException, IOException, OperationCanceledException { if (Log.isLoggable(TAG, Log.DEBUG)) { Log_OC.d(TAG, "Saving sessions... "); } Iterator<String> accountNames = mClientsWithKnownUsername.keySet().iterator(); String accountName = null; Account account = null; while (accountNames.hasNext()) { accountName = accountNames.next(); account = new Account(accountName, accountType); AccountUtils.saveClient( mClientsWithKnownUsername.get(accountName), account, context); } if (Log.isLoggable(TAG, Log.DEBUG)) { Log_OC.d(TAG, "All sessions saved"); } }
public JSONObject getQuestions(QuestionsGetRequest request) throws IOException, JSONException, InvalidAccessTokenException, AuthenticatorException, OperationCanceledException, ServerErrorException { UrlParams params = new UrlParams(); params.add("first_question_id", request.getFirstQuestionId()); params.add("limit", request.getLimit()); params.add("offset", request.getOffset()); params.add("tab", request.getContentSection().toString().toLowerCase()); for (int category : request.getCategories()) { params.add("categories[]", category); } HttpResponse response = makeProtectedGetCall(resolveApiUrl(request.getPath()), params); if (response == null || response.getBody() == null) { return null; } return new JSONObject(response.getBody()); }
public JSONObject uploadImage(ImageUploadRequest request) throws JSONException, IOException, InvalidAccessTokenException, AuthenticatorException, OperationCanceledException, ServerErrorException { UrlParams params = new UrlParams(); ImageData image = request.getImage(); ImageParamFacade imageParamFacade = new ImageParamFacade(image); try { imageParamFacade.write(params, "image", "preview"); HttpResponse response = makeProtectedMultipartPostCall(resolveApiUrl(request.getPath()), params); if (response == null || response.getBody() == null) { return null; } return new JSONObject(response.getBody()); } finally { imageParamFacade.close(); } }
@Override public void run(AccountManagerFuture<Bundle> bundleAccountManagerFuture) { try { Bundle result = bundleAccountManagerFuture.getResult(); Intent intent = (Intent) result.get(AccountManager.KEY_INTENT); if (intent == null) { String authToken = result.getString(AccountManager.KEY_AUTHTOKEN); GutenbergApplication app = GutenbergApplication.from(BaseActivity.this); app.setAuthToken(authToken); app.requestSync(false); } else { startActivityForResult(intent, REQUEST_AUTHENTICATE); } } catch (OperationCanceledException | IOException | AuthenticatorException e) { Log.e(TAG, "Error authenticating.", e); } }
private void addAccount(String accountName) { AccountManager accountManager = AccountManager.get(this); Bundle bundle = new Bundle(); if (!TextUtils.isEmpty(accountName)) { bundle.putString(AccountManager.KEY_ACCOUNT_NAME, accountName); } accountManager.addAccount(GOOGLE_ACCOUNT_TYPE, null, null, bundle, this, accountManagerFuture -> { try { Bundle result = accountManagerFuture.getResult(); String accountNameAdded = result.getString(AccountManager.KEY_ACCOUNT_NAME); Log.d(TAG, "addAccount - accountNameAdded: " + accountNameAdded); if (mNextActivityIntent != null) { startActivity(mNextActivityIntent); } finish(); } catch (OperationCanceledException | AuthenticatorException | IOException e) { Log.e(TAG, "addAccount - failed", e); Toast.makeText(AddAccountActivity.this, R.string.fail_to_add_account, Toast.LENGTH_LONG).show(); } }, null); }
private static String retryAuthentification(int retryCount, AccountManager accountManager, String authtoken, String accountName, HttpResponse response) throws AuthenticationException, OperationCanceledException, NetworkErrorException, ServerException { accountManager.invalidateAuthToken(Constants.ACCOUNT_TYPE, authtoken); String newToken = null; if (retryCount == 0) { newToken = blockingGetAuthToken(accountManager, new Account( accountName, Constants.ACCOUNT_TYPE), null); } if (newToken == null) { throw new AuthenticationException(response.getStatusLine() .toString()); } return newToken; }
public static String getAccountAuthToken(Context context, Account account) { if (account == null) { return null; } AccountManager am = AccountManager.get(context); AccountManagerFuture<Bundle> response = am.getAuthToken(account, KusssAuthenticator.AUTHTOKEN_TYPE_READ_ONLY, null, true, null, null); if (response == null) return null; try { return response.getResult().getString(AccountManager.KEY_AUTHTOKEN); } catch (OperationCanceledException | AuthenticatorException | IOException e) { Log.e(TAG, "getAccountAuthToken", e); return null; } }
public synchronized void queryGmailLabels() { // Get the account list, and pick the user specified address AccountManager.get(mContext).getAccountsByTypeAndFeatures(ACCOUNT_TYPE_GOOGLE, FEATURES_MAIL, new AccountManagerCallback<Account[]>() { @Override public void run(AccountManagerFuture<Account[]> future) { Account[] accounts = null; try { accounts = future.getResult(); } catch (OperationCanceledException oce) { Logs.e(TAG, "Got OperationCanceledException: "+oce.toString()); } catch (IOException ioe) { Logs.e(TAG, "Got OperationCanceledException: "+ioe.toString()); } catch (AuthenticatorException ae) { Logs.e(TAG, "Got OperationCanceledException: "+ae.toString()); } mGmailUnreadCount = onAccountResults(accounts); addGmailToContentList(mGmailUnreadCount); Logs.d(TAG, "# Gmail unread count = "+ mGmailUnreadCount); } }, null /* handler */); }
protected void getToken() throws OperationCanceledException, AuthenticatorException, IOException { // activity.token = null; Account account = new Account(toDoFragment.userName, GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE); AccountManagerFuture<Bundle> accountManagerFuture = AccountManager.get( toDoFragment.getActivity()).getAuthToken(account, "oauth2:" + TasksScopes.TASKS, null, toDoFragment.getActivity(), null, null); toDoFragment.token = accountManagerFuture.getResult().getString( AccountManager.KEY_AUTHTOKEN); // Users user = activity.userDataSource.selectUser(activity.userName); // user.setPwd(activity.token); if (toDoFragment.token != null && !toDoFragment.token.isEmpty()) { // activity.userDataSource.updateUsers(user); toDoFragment.credential = (new GoogleCredential()) .setAccessToken(toDoFragment.token); } }
/** * 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 OperationCanceledException) { message = ((OperationCanceledException) t.getCause()).getMessage(); } else if (t.getCause() instanceof GoogleAuthException) { message = ((GoogleAuthException) t.getCause()).getMessage(); } else if (t instanceof IOException) { if (t.getMessage() == null) { message = "IOException"; } } Log.d(tag, message); ToastHelper.showErrorToast(activity, activity.getResources().getString(R.string.error)); }
private void handleException(String authtoken, Exception e, SyncResult syncResult) { if (e instanceof AuthenticatorException) { syncResult.stats.numParseExceptions++; Log.e("SyncAdapter", "AuthenticatorException", e); } else if (e instanceof OperationCanceledException) { Log.e("SyncAdapter", "OperationCanceledExcepion", e); } else if (e instanceof IOException) { Log.e("SyncAdapter", "IOException", e); syncResult.stats.numIoExceptions++; } else if (e instanceof AuthenticationException) { accountManager.invalidateAuthToken(Authenticator.ACCOUNT_TYPE, authtoken); syncResult.stats.numIoExceptions++; if (authtoken != null) Log.e("SyncAdapter", "Auth failed, invalidating token: " + authtoken); Log.e("SyncAdapter", "AuthenticationException", e); } else if (e instanceof ParseException) { syncResult.stats.numParseExceptions++; Log.e("SyncAdapter", "ParseException", e); } else if (e instanceof JsonParseException) { syncResult.stats.numParseExceptions++; Log.e("SyncAdapter", "JSONException", e); } else if (e instanceof ServerUrlPreferenceNotSetException) { Log.e("SyncAdapter", "ServerUrlPreferenceNotSetException", e); } }
private ContentValues getAnswerContentValues(JSONObject answer) throws AuthenticationException, ParseException, OperationCanceledException, AuthenticatorException, JSONException, IOException { ContentValues values = new ContentValues(); values.put(AnswersEntry.COLUMN_TIMESTAMP, answer.optString("LastChangedTime")); values.put(AnswersEntry.COLUMN_ANSWER, answer.optString("Content")); values.put(AnswersEntry.COLUMN_DATE, SyncHelper.getUnixMillisecondsFromJsonDate(answer.optString("Date"))); values.put(AnswersEntry.COLUMN_ANSWERSTATE, getAnswerStateForId(answer.optInt("answerState")).toString());//TODO String backendid = answer.optString("Id"); if (backendid != null) { values.put(AnswersEntry.COLUMN_BACKEND_ID, SyncHelper.getIdFromURI(backendid)); } String answerer = answer.optString("Answerer"); if (answerer != null && !answerer.equals("null") && answerer.length() > 0) { values.put(AnswersEntry.COLUMN_ANSWERER_ID, SyncHelper.getRealIdForObjectURI(answerer, context)); } return values; }
private void initAuthCookie(Activity source, ServerPreferences conf) throws OperationCanceledException, AuthenticatorException, IOException { Account account = conf.getAccount(); if (account == null) { return; } String authToken = buildToken(source, account); HttpURLConnection tempGet = (HttpURLConnection) new URL( conf.getServerURL() + "_ah/login?continue=http://localhost/&auth=" + URLEncoder.encode(authToken)).openConnection(); int responseCode = tempGet.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_MOVED_TEMP) { throw new AuthenticatorException( "Could not exchange token for cookie, code: " + responseCode); } }
@Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { try { ContactsSyncAdapterService.performSync(mContext, account, extras, authority, provider, syncResult); } catch (OperationCanceledException e) { FileLog.e("tmessages", e); } }
@Override public void run(AccountManagerFuture<Bundle> future) { Bundle result; try { result = future.getResult(); } catch (OperationCanceledException | AuthenticatorException | IOException e) { Log.w(TAG, "ERR_UNEXPECTED: Error while attempting to obtain a token.", e); nativeSetResult(mRequestData.nativeResultObject, NetError.ERR_UNEXPECTED, null); return; } if (result.containsKey(AccountManager.KEY_INTENT)) { final Context appContext = ContextUtils.getApplicationContext(); // We wait for a broadcast that should be sent once the user is done interacting // with the notification // TODO(dgn) We currently hang around if the notification is swiped away, until // a LOGIN_ACCOUNTS_CHANGED_ACTION filter is received. It might be for something // unrelated then we would wait again here. Maybe we should limit the number of // retries in some way? BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { appContext.unregisterReceiver(this); mRequestData.accountManager.getAuthToken(mRequestData.account, mRequestData.authTokenType, mRequestData.options, true /* notifyAuthFailure */, new GetTokenCallback(mRequestData), null); } }; appContext.registerReceiver(broadcastReceiver, new IntentFilter(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION)); } else { processResult(result, mRequestData); } }
/** * Test of callback called when getting the auth token completes. */ @Test public void testAccountManagerCallbackRun() { HttpNegotiateAuthenticator authenticator = createWithoutNative("Dummy_Account"); Robolectric.buildActivity(Activity.class).create().start().resume().visible(); // Call getNextAuthToken to get the callback authenticator.getNextAuthToken(1234, "test_principal", "", true); verify(sMockAccountManager) .getAuthTokenByFeatures(anyString(), anyString(), any(String[].class), any(Activity.class), any(Bundle.class), any(Bundle.class), mBundleCallbackCaptor.capture(), any(Handler.class)); Bundle resultBundle = new Bundle(); Bundle context = new Bundle(); context.putString("String", "test_context"); resultBundle.putInt(HttpNegotiateConstants.KEY_SPNEGO_RESULT, HttpNegotiateConstants.OK); resultBundle.putBundle(HttpNegotiateConstants.KEY_SPNEGO_CONTEXT, context); resultBundle.putString(AccountManager.KEY_AUTHTOKEN, "output_token"); mBundleCallbackCaptor.getValue().run(makeFuture(resultBundle)); verify(authenticator).nativeSetResult(1234, 0, "output_token"); // Check that the next call to getNextAuthToken uses the correct context authenticator.getNextAuthToken(5678, "test_principal", "", true); verify(sMockAccountManager, times(2)) .getAuthTokenByFeatures(anyString(), anyString(), any(String[].class), any(Activity.class), any(Bundle.class), mBundleCaptor.capture(), mBundleCallbackCaptor.capture(), any(Handler.class)); assertThat("The spnego context is preserved between calls", mBundleCaptor.getValue().getBundle(HttpNegotiateConstants.KEY_SPNEGO_CONTEXT), equalTo(context)); // Test exception path mBundleCallbackCaptor.getValue().run( this.<Bundle>makeFuture(new OperationCanceledException())); verify(authenticator).nativeSetResult(5678, NetError.ERR_UNEXPECTED, null); }
/** * Returns a future that successfully returns the provided result. * Hides mocking related annoyances: compiler warnings and irrelevant catch clauses. */ private <T> AccountManagerFuture<T> makeFuture(T result) { // Avoid warning when creating mock accountManagerFuture, can't take .class of an // instantiated generic type, yet compiler complains if I leave it uninstantiated. @SuppressWarnings("unchecked") AccountManagerFuture<T> accountManagerFuture = mock(AccountManagerFuture.class); try { when(accountManagerFuture.getResult()).thenReturn(result); } catch (OperationCanceledException | AuthenticatorException | IOException e) { // Can never happen - artifact of Mockito. fail(); } return accountManagerFuture; }
/** * Returns a future that fails with the provided exception when trying to get its result. * Hides mocking related annoyances: compiler warnings and irrelevant catch clauses. */ private <T> AccountManagerFuture<T> makeFuture(Exception ex) { // Avoid warning when creating mock accountManagerFuture, can't take .class of an // instantiated generic type, yet compiler complains if I leave it uninstantiated. @SuppressWarnings("unchecked") AccountManagerFuture<T> accountManagerFuture = mock(AccountManagerFuture.class); try { when(accountManagerFuture.getResult()).thenThrow(ex); } catch (OperationCanceledException | AuthenticatorException | IOException e) { // Can never happen - artifact of Mockito. fail(); } return accountManagerFuture; }
public void run(AccountManagerFuture<Bundle> arg0) { try { Bundle result = (Bundle) arg0.getResult(); if (result != null) { LemallPlatform.getInstance().setSsoToken(result.getString("authtoken")); } } catch (OperationCanceledException e) { e.printStackTrace(); } catch (AuthenticatorException e2) { e2.printStackTrace(); } catch (IOException e3) { e3.printStackTrace(); } }
@Override public Bundle getResult() throws OperationCanceledException, IOException, AuthenticatorException { Bundle bundle = mFuture.getResult(); String accountName = bundle.getString(AccountManager.KEY_ACCOUNT_NAME); String accountType = bundle.getString(AccountManager.KEY_ACCOUNT_TYPE); if (isAccountAllowed(accountName, accountType, mUid)) return bundle; else throw new OperationCanceledException("XPrivacy"); }
@Override public Bundle getResult(long timeout, TimeUnit unit) throws OperationCanceledException, IOException, AuthenticatorException { Bundle bundle = mFuture.getResult(timeout, unit); String accountName = bundle.getString(AccountManager.KEY_ACCOUNT_NAME); String accountType = bundle.getString(AccountManager.KEY_ACCOUNT_TYPE); if (isAccountAllowed(accountName, accountType, mUid)) return bundle; else throw new OperationCanceledException("XPrivacy"); }
/** * Makes a GET request and parses the received JSON string as a Map. */ public static Map getJson(OIDCAccountManager accountManager, String url, Account account, AccountManagerCallback<Bundle> callback) throws IOException, UserNotAuthenticatedWrapperException, AuthenticatorException, OperationCanceledException { String jsonString = makeRequest(accountManager, HttpRequest.METHOD_GET, url, account, callback); Log.i("APIUtility", jsonString); return new Gson().fromJson(jsonString, Map.class); }
public static List<JSONObject> getJsonList(OIDCAccountManager accountManager, String url, Account account, AccountManagerCallback<Bundle> callback) throws IOException, UserNotAuthenticatedWrapperException, AuthenticatorException, OperationCanceledException { String jsonString = makeRequest(accountManager, HttpRequest.METHOD_GET, url, account, callback); Log.i("APIUtility", jsonString); return new Gson().fromJson(jsonString, List.class); }
/** * Makes an arbitrary HTTP request using the provided account. * * If the request doesn't execute successfully on the first try, the tokens will be refreshed * and the request will be retried. If the second try fails, an exception will be raised. */ public static String makeRequest(OIDCAccountManager accountManager, String method, String url, Account account, AccountManagerCallback<Bundle> callback) throws IOException, UserNotAuthenticatedWrapperException, AuthenticatorException, OperationCanceledException { return makeRequest(accountManager, method, url, "", account, true, callback); }
private static String makeRequest(OIDCAccountManager accountManager, String method, String url, String body, Account account, boolean doRetry, AccountManagerCallback<Bundle> callback) throws IOException, UserNotAuthenticatedWrapperException, AuthenticatorException, OperationCanceledException { String accessToken = accountManager.getAccessToken(account, callback); String cookies = accountManager.getCookies(account, callback); // Prepare an API request using the accessToken HttpRequest request = new HttpRequest(url, method); request = prepareApiRequest(request, accessToken, cookies); if (body != "") { request.send(body); } if (request.ok()) { return request.body(); } else { int code = request.code(); String requestContent = "empty body"; try { requestContent = request.body(); } catch (HttpRequest.HttpRequestException e) { //Nothing to do, the response has no body or couldn't fetch it e.printStackTrace(); } if (doRetry && (code == HTTP_UNAUTHORIZED || code == HTTP_FORBIDDEN || (code == HTTP_BAD_REQUEST && (requestContent.contains("invalid_grant") || requestContent.contains("Access Token not valid"))))) { // We're being denied access on the first try, let's renew the token and retry accountManager.invalidateAuthTokens(account); return makeRequest(accountManager, method, url, body, account, false, callback); } else { // An unrecoverable error or the renewed token didn't work either throw new IOException(request.code() + " " + request.message() + " " + requestContent); } } }
public static String getAuthToken(Context ctx) { String token = null; try { token = getAccountManager(ctx).blockingGetAuthToken(getAccount(ctx), "Bearer", false); } catch (OperationCanceledException | IOException | AuthenticatorException e) { e.printStackTrace(); } return "Bearer " + token; }
private boolean removeAccount(Account account) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { return mAccountManager.removeAccountExplicitly(account); } else { //noinspection deprecation AccountManagerFuture<Boolean> feature = mAccountManager.removeAccount(account, null, null); try { return feature.getResult(); } catch (OperationCanceledException | IOException | AuthenticatorException e) { e.printStackTrace(); return false; } } }