Example usage for android.accounts AccountManager blockingGetAuthToken

List of usage examples for android.accounts AccountManager blockingGetAuthToken

Introduction

In this page you can find the example usage for android.accounts AccountManager blockingGetAuthToken.

Prototype

public String blockingGetAuthToken(Account account, String authTokenType, boolean notifyAuthFailure)
        throws OperationCanceledException, IOException, AuthenticatorException 

Source Link

Document

This convenience helper synchronously gets an auth token with #getAuthToken(Account,String,boolean,AccountManagerCallback,Handler) .

Usage

From source file:org.klnusbaum.udj.network.PlaylistSyncService.java

private void voteOnSong(Account account, String playerId, String libId, int voteWeight, boolean attemptReauth) {
    AccountManager am = AccountManager.get(this);
    String authToken = "";
    try {/* w  w  w . j  a  v a2  s  .  c  om*/
        authToken = am.blockingGetAuthToken(account, "", true);
    } catch (IOException e) {
        Log.e(TAG, "IO exception when voting on playist");
    } catch (AuthenticatorException e) {
        Log.e(TAG, "Authentication exception when voting playist");
    } catch (OperationCanceledException e) {
        Log.e(TAG, "Op Canceled exception when voting playist");
    }

    try {
        ServerConnection.voteOnSong(playerId, libId, voteWeight, authToken);
        Intent voteCompleteBroadcast = new Intent(Constants.BROADCAST_VOTE_COMPLETED);
        this.sendBroadcast(voteCompleteBroadcast);
    } catch (ParseException e) {
        Log.e(TAG, "Parse exception when retreiving playist");
    } catch (IOException e) {
        Log.e(TAG, "IO exception when retreiving playist");
    } catch (AuthenticationException e) {
        if (attemptReauth) {
            Log.e(TAG, "Soft Authentication exception when retreiving playist");
            am.invalidateAuthToken(Constants.ACCOUNT_TYPE, authToken);
            voteOnSong(account, playerId, libId, voteWeight, false);
        } else {
            Log.e(TAG, "Hard Authentication exception when retreiving playist");
        }
    } catch (PlayerInactiveException e) {
        Log.e(TAG, "Event over exception when retreiving playlist");
        Utils.handleInactivePlayer(this, account);
    } catch (NoLongerInPlayerException e) {
        Utils.handleNoLongerInPlayer(this, account);
    } catch (KickedException e) {
        Utils.handleKickedFromPlayer(this, account);
    }
}

From source file:org.klnusbaum.udj.network.PlaylistSyncService.java

private void setPlaybackState(Intent intent, Account account, String playerId, boolean attemptReauth) {
    AccountManager am = AccountManager.get(this);
    String authToken = "";
    try {//from   w  ww .j  a  v a2  s. com
        authToken = am.blockingGetAuthToken(account, "", true);
    } catch (OperationCanceledException e) {
        //TODO do something here?
        Log.e(TAG, "Operation canceled exception in set playback");
        return;
    } catch (AuthenticatorException e) {
        //TODO do something here?
        Log.e(TAG, "Authenticator exception in set playback");
        return;
    } catch (IOException e) {
        //TODO do something here?
        Log.e(TAG, "IO exception in set playback");
        return;
    }

    int desiredPlaybackState = intent.getIntExtra(Constants.PLAYBACK_STATE_EXTRA, 0);
    try {
        ServerConnection.setPlaybackState(playerId, desiredPlaybackState, authToken);
    } catch (IOException e) {
        Log.e(TAG, "IO exception in set playback");
        alertSetPlaybackException(account, intent);
        return;
    } catch (AuthenticationException e) {
        if (attemptReauth) {
            Log.d(TAG, "Soft Authentication exception when setting playback state");
            am.invalidateAuthToken(Constants.ACCOUNT_TYPE, authToken);
            setPlaybackState(intent, account, playerId, false);
        } else {
            Log.e(TAG, "Hard Authentication exception when setting playback state");
            //TODO do something here?
        }
    } catch (PlayerInactiveException e) {
        Log.e(TAG, "Player inactive exception in set playback");
        Utils.handleInactivePlayer(this, account);
        return;
    } catch (NoLongerInPlayerException e) {
        Utils.handleNoLongerInPlayer(this, account);
        return;
    } catch (KickedException e) {
        Utils.handleKickedFromPlayer(this, account);
    }
}

From source file:org.klnusbaum.udj.network.EventCommService.java

private void leaveEvent(AccountManager am, Account account, boolean attemptReauth) {
    Log.d(TAG, "In leave event");

    if (account == null) {
        //TODO handle error
        return;/*from w w w.  java 2s  .c  om*/
    }

    long userId;
    String authToken;
    try {
        userId = Long.valueOf(am.getUserData(account, Constants.USER_ID_DATA));
        //TODO handle if event id isn't provided
        authToken = am.blockingGetAuthToken(account, "", true);
    } catch (OperationCanceledException e) {
        Log.e(TAG, "Operation canceled exception in EventCommService");
        return;
    } catch (AuthenticatorException e) {
        Log.e(TAG, "Authenticator exception in EventCommService");
        return;
    } catch (IOException e) {
        Log.e(TAG, "IO exception in EventCommService");
        return;
    }

    try {
        long eventId = Long.valueOf(am.getUserData(account, Constants.LAST_EVENT_ID_DATA));
        if (eventId != Constants.NO_EVENT_ID) {
            ServerConnection.leaveEvent(eventId, Long.valueOf(userId), authToken);
            setNotInEvent(account);
            Intent leftEventIntent = new Intent(Constants.LEFT_EVENT_ACTION);
            sendBroadcast(leftEventIntent);
        }
    } catch (IOException e) {
        Log.e(TAG, "IO exception in EventCommService: " + e.getMessage());
    } catch (AuthenticationException e) {
        if (attemptReauth) {
            Log.e(TAG, "Soft Authentication exception in EventCommService");
            am.invalidateAuthToken(Constants.ACCOUNT_TYPE, authToken);
            leaveEvent(am, account, false);
        } else {
            Log.e(TAG, "HARD Authentication exception in EventCommService");
        }
    } finally {
        //TODO potential this get's repeated because it's already called once
        //above. I'll deal with that fact later.
        setNotInEvent(account);
    }
    //TODO need to implement exponential back off when log out fails.
    // 1. This is just nice to the server
    // 2. If we don't log out, there could be problems on the next event joined
}

From source file:org.klnusbaum.udj.network.EventCommService.java

private void enterEvent(Intent intent, AccountManager am, Account account, boolean attemptReauth) {
    if (!Utils.isNetworkAvailable(this)) {
        doLoginFail(am, account, EventJoinError.NO_NETWORK_ERROR);
        return;/*from  ww w.  ja  v  a  2  s  .c  o  m*/
    }

    long userId, eventId;
    String authToken;
    //TODO hanle error if account isn't provided
    try {
        userId = Long.valueOf(am.getUserData(account, Constants.USER_ID_DATA));
        //TODO handle if event id isn't provided
        authToken = am.blockingGetAuthToken(account, "", true);
        eventId = intent.getLongExtra(Constants.EVENT_ID_EXTRA, Constants.NO_EVENT_ID);
    } catch (OperationCanceledException e) {
        Log.e(TAG, "Operation canceled exception in EventCommService");
        doLoginFail(am, account, EventJoinError.AUTHENTICATION_ERROR);
        return;
    } catch (AuthenticatorException e) {
        Log.e(TAG, "Authenticator exception in EventCommService");
        doLoginFail(am, account, EventJoinError.AUTHENTICATION_ERROR);
        return;
    } catch (IOException e) {
        Log.e(TAG, "IO exception in EventCommService");
        doLoginFail(am, account, EventJoinError.AUTHENTICATION_ERROR);
        return;
    }

    try {
        ServerConnection.joinEvent(eventId, userId, authToken);
        setEventData(intent, am, account);
        ContentResolver cr = getContentResolver();
        UDJEventProvider.eventCleanup(cr);
        HashMap<Long, Long> previousRequests = ServerConnection.getAddRequests(userId, eventId, authToken);
        UDJEventProvider.setPreviousAddRequests(cr, previousRequests);
        JSONObject previousVotes = ServerConnection.getVoteRequests(userId, eventId, authToken);
        UDJEventProvider.setPreviousVoteRequests(cr, previousVotes);
        Intent joinedEventIntent = new Intent(Constants.JOINED_EVENT_ACTION);
        am.setUserData(account, Constants.LAST_EVENT_ID_DATA, String.valueOf(eventId));
        am.setUserData(account, Constants.EVENT_STATE_DATA, String.valueOf(Constants.IN_EVENT));
        sendBroadcast(joinedEventIntent);
    } catch (IOException e) {
        Log.e(TAG, "IO exception when joining event");
        Log.e(TAG, e.getMessage());
        doLoginFail(am, account, EventJoinError.SERVER_ERROR);
    } catch (JSONException e) {
        Log.e(TAG, "JSON exception when joining event");
        Log.e(TAG, e.getMessage());
        doLoginFail(am, account, EventJoinError.SERVER_ERROR);
    } catch (AuthenticationException e) {
        handleLoginAuthException(intent, am, account, authToken, attemptReauth);
    } catch (EventOverException e) {
        Log.e(TAG, "Event Over Exception when joining event");
        //Log.e(TAG, e.getMessage());
        doLoginFail(am, account, EventJoinError.EVENT_OVER_ERROR);
    } catch (AlreadyInEventException e) {
        Log.e(TAG, "Already In Event Exception when joining event");
        try {
            ServerConnection.leaveEvent(e.getEventId(), userId, authToken);
            enterEvent(intent, am, account, true);
        } catch (AuthenticationException f) {
            handleLoginAuthException(intent, am, account, authToken, attemptReauth);
        } catch (IOException f) {
            Log.e(TAG, "IO exception when attempting to leave one event before " + "joining another");
            Log.e(TAG, f.getMessage());
            doLoginFail(am, account, EventJoinError.SERVER_ERROR);
        }
    }
}

From source file:org.klnusbaum.udj.network.PlaylistSyncService.java

private void setPlayerVolume(Intent intent, Account account, String playerId, boolean attemptReauth) {
    AccountManager am = AccountManager.get(this);
    int desiredVolume = intent.getIntExtra(Constants.PLAYER_VOLUME_EXTRA, 0);
    Log.d(TAG, "proceeding to set volume of player to: " + String.valueOf(desiredVolume) + " on server");

    String authToken = "";
    try {/*from   w ww .  ja  v  a 2 s.c o m*/
        authToken = am.blockingGetAuthToken(account, "", true);
    } catch (OperationCanceledException e) {
        //TODO do something here?
        Log.e(TAG, "Operation canceled exception in set playback");
        return;
    } catch (AuthenticatorException e) {
        //TODO do something here?
        Log.e(TAG, "Authenticator exception in set playback");
        return;
    } catch (IOException e) {
        //TODO do something here?
        Log.e(TAG, "IO exception in set playback");
        return;
    }

    try {
        ServerConnection.setPlayerVolume(playerId, desiredVolume, authToken);
    } catch (IOException e) {
        Log.e(TAG, "IO exception in set volume");
        alertSetVolumeException(account, intent);
        return;
    } catch (AuthenticationException e) {
        if (attemptReauth) {
            Log.d(TAG, "Soft Authentication exception when setting volume");
            am.invalidateAuthToken(Constants.ACCOUNT_TYPE, authToken);
            setPlayerVolume(intent, account, playerId, false);
        } else {
            Log.e(TAG, "Hard Authentication exception when setting volume");
            //TODO do something here?
        }
    } catch (PlayerInactiveException e) {
        Log.e(TAG, "Player inactive exception in set volume");
        Utils.handleInactivePlayer(this, account);
        return;
    } catch (NoLongerInPlayerException e) {
        Utils.handleNoLongerInPlayer(this, account);
        return;
    } catch (KickedException e) {
        Utils.handleKickedFromPlayer(this, account);
    }
}

From source file:org.klnusbaum.udj.network.PlayerCommService.java

private void joinPlayer(Intent intent, AccountManager am, Account account, boolean attemptReauth) {
    if (!Utils.isNetworkAvailable(this)) {
        doLoginFail(am, account, PlayerJoinError.NO_NETWORK_ERROR);
        return;/*from w ww.ja va2 s  .c o  m*/
    }

    String userId = am.getUserData(account, Constants.USER_ID_DATA);
    String playerId = intent.getStringExtra(Constants.PLAYER_ID_EXTRA);
    String ownerId = intent.getStringExtra(Constants.PLAYER_OWNER_ID_EXTRA);
    if (userId.equals(ownerId)) {
        setLoggedInToPlayer(intent, am, account, playerId);
        return;
    }

    String authToken;
    String password = "";
    boolean hasPassword = false;
    //TODO hanle error if account isn't provided
    try {
        //TODO handle if player id isn't provided
        authToken = am.blockingGetAuthToken(account, "", true);
        if (intent.hasExtra(Constants.PLAYER_PASSWORD_EXTRA)) {
            Log.d(TAG, "password given for player");
            hasPassword = true;
            password = intent.getStringExtra(Constants.PLAYER_PASSWORD_EXTRA);
        } else {
            Log.d(TAG, "No password given for player");
        }
    } catch (OperationCanceledException e) {
        Log.e(TAG, "Operation canceled exception");
        doLoginFail(am, account, PlayerJoinError.AUTHENTICATION_ERROR);
        return;
    } catch (AuthenticatorException e) {
        Log.e(TAG, "Authenticator exception");
        doLoginFail(am, account, PlayerJoinError.AUTHENTICATION_ERROR);
        return;
    } catch (IOException e) {
        Log.e(TAG, "IO exception");
        doLoginFail(am, account, PlayerJoinError.AUTHENTICATION_ERROR);
        return;
    }

    try {
        if (!hasPassword) {
            ServerConnection.joinPlayer(playerId, authToken);
        } else {
            ServerConnection.joinPlayer(playerId, password, authToken);
        }
        setLoggedInToPlayer(intent, am, account, playerId);
    } catch (IOException e) {
        Log.e(TAG, "IO exception when joining player");
        Log.e(TAG, e.getMessage());
        doLoginFail(am, account, PlayerJoinError.SERVER_ERROR);
    } catch (JSONException e) {
        Log.e(TAG, "JSON exception when joining player");
        Log.e(TAG, e.getMessage());
        doLoginFail(am, account, PlayerJoinError.SERVER_ERROR);
    } catch (AuthenticationException e) {
        handleLoginAuthException(intent, am, account, authToken, attemptReauth);
    } catch (PlayerInactiveException e) {
        Log.e(TAG, "Player inactive Exception when joining player");
        doLoginFail(am, account, PlayerJoinError.PLAYER_INACTIVE_ERROR);
    } catch (ParseException e) {
        e.printStackTrace();
        doLoginFail(am, account, PlayerJoinError.SERVER_ERROR);
    } catch (PlayerPasswordException e) {
        Log.e(TAG, "Player Password Exception");
        e.printStackTrace();
        doLoginFail(am, account, PlayerJoinError.PLAYER_PASSWORD_ERROR);
    } catch (PlayerFullException e) {
        Log.e(TAG, "Player Password Exception");
        e.printStackTrace();
        doLoginFail(am, account, PlayerJoinError.PLAYER_FULL_ERROR);
    } catch (BannedException e) {
        Log.e(TAG, "Player Password Exception");
        e.printStackTrace();
        doLoginFail(am, account, PlayerJoinError.BANNED_ERROR);
    }
}

From source file:org.hfoss.posit.android.sync.Communicator.java

public static String getAuthKey(Context context) {
    AccountManager accountManager = AccountManager.get(context);

    // TODO: again just picking the first account here.. how are you
    // supposed to handle this?
    Account[] accounts = accountManager.getAccountsByType(SyncAdapter.ACCOUNT_TYPE);

    if (accounts.length == 0)
        return null;

    String authKey = null;/* w  w  w .j ava2s.  com*/
    try {
        authKey = accountManager.blockingGetAuthToken(accounts[0], SyncAdapter.AUTHTOKEN_TYPE,
                true /* notifyAuthFailure */);
    } catch (OperationCanceledException e) {
        Log.e(TAG, "getAuthKey(), cancelled during request: " + e.getMessage());
        e.printStackTrace();
    } catch (AuthenticatorException e) {
        Log.e(TAG, "getAuthKey(), authentication exception: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        Log.e(TAG, "getAuthKey() IOException" + e.getMessage());
        e.printStackTrace();
    } catch (IllegalStateException e) {
        Log.e(TAG, "getAuthKey() IllegalStateException" + e.getMessage());
        e.printStackTrace();
    }
    return authKey;
}

From source file:org.opendatakit.services.sync.service.logic.HttpRestProtocolWrapper.java

private String updateAccessToken() throws InvalidAuthTokenException {
    try {/*ww  w  .j  a v  a2 s. c  o  m*/
        AccountManager accountManager = sc.getAccountManager();
        Account account = sc.getAccount();
        this.accessToken = accountManager.blockingGetAuthToken(account, authString, true);
        return accessToken;
    } catch (Exception e) {
        e.printStackTrace();
        throw new InvalidAuthTokenException("unable to update access token -- please re-authorize");
    }
}

From source file:org.jorge.lolin1.func.chat.ChatIntentService.java

private Boolean login(String upperCaseRealm) {
    ChatServer chatServer;/* w  ww .ja  v a  2 s  . c o m*/
    switch (upperCaseRealm) {
    case "NA":
        chatServer = ChatServer.NA;
        break;
    case "EUW":
        chatServer = ChatServer.EUW;
        break;
    case "EUNE":
        chatServer = ChatServer.EUNE;
        break;
    case "TR":
        chatServer = ChatServer.TR;
        break;
    case "BR":
        chatServer = ChatServer.BR;
        break;
    case "OCE":
        chatServer = ChatServer.OCE;
        break;
    case "LAN":
        chatServer = ChatServer.LAN;
        break;
    case "LAS":
        chatServer = ChatServer.LAS;
        break;
    case "KR":
        chatServer = ChatServer.KR;
        break;
    case "RU":
        chatServer = ChatServer.RU;
        break;
    default:
        throw new IllegalArgumentException("Region " + upperCaseRealm + " not yet implemented");
    }
    try {
        logString("debug", "Assigning api...");
        api = new LoLChat(chatServer, Boolean.FALSE);
    } catch (IOException e) {
        logString("debug", "Exception when constructing the object!");
        e.printStackTrace(System.err);
        if (!(e instanceof SSLException)) {
            launchBroadcastLoginUnsuccessful();
        }
        return Boolean.FALSE;
    }
    final AccountManager accountManager = AccountManager.get(getApplicationContext());
    Account[] accounts = accountManager
            .getAccountsByType(LoLin1Utils.getString(getApplicationContext(), "account_type", null));
    Account thisRealmAccount = null;
    for (Account acc : accounts) {
        if (acc.name.contentEquals(upperCaseRealm)) {
            thisRealmAccount = acc;
            break;
        }
    }
    if (thisRealmAccount == null) {
        return Boolean.FALSE;//There's no account associated to this realm
    }
    AsyncTask<Account, Void, String[]> credentialsTask = new AsyncTask<Account, Void, String[]>() {
        @Override
        protected String[] doInBackground(Account... params) {
            String[] processedAuthToken = null;
            try {
                processedAuthToken = accountManager.blockingGetAuthToken(params[0], "none", Boolean.TRUE)
                        .split(AccountAuthenticator.TOKEN_GENERATION_JOINT);
            } catch (OperationCanceledException | IOException | AuthenticatorException e) {
                Crashlytics.logException(e);
            }
            return processedAuthToken;
        }
    };
    //It's necessary to run the task in an executor because the main one is already full and if we add this one a livelock will occur
    ExecutorService loginExecutor = Executors.newFixedThreadPool(1);
    credentialsTask.executeOnExecutor(loginExecutor, thisRealmAccount);
    String[] processedAuthToken = new String[0];
    try {
        processedAuthToken = credentialsTask.get();
    } catch (InterruptedException | ExecutionException e) {
        Crashlytics.logException(e);
    }
    Boolean loginSuccess = Boolean.FALSE;
    try {
        loginSuccess = api.login(processedAuthToken[0], processedAuthToken[1]);
    } catch (IOException e) {
        Crashlytics.logException(e);
    }
    if (loginSuccess) {
        api.reloadRoster();
        isConnected = Boolean.TRUE;
        return Boolean.TRUE;
    } else {
        isConnected = Boolean.FALSE;
        return Boolean.FALSE;
    }
}