Example usage for android.accounts AccountManager invalidateAuthToken

List of usage examples for android.accounts AccountManager invalidateAuthToken

Introduction

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

Prototype

public void invalidateAuthToken(final String accountType, final String authToken) 

Source Link

Document

Removes an auth token from the AccountManager's cache.

Usage

From source file:org.klnusbaum.udj.MusicSearchLoader.java

private MusicSearchResult attemptSearch(boolean attemptReauth) {
    AccountManager am = AccountManager.get(getContext());
    String authToken = "";
    try {//from  www .j ava 2  s.  com
        authToken = am.blockingGetAuthToken(account, "", true);
    } catch (IOException e) {
        //TODO this might actually be an auth error
        return new MusicSearchResult(null, MusicSearchError.AUTHENTICATION_ERROR);
    } catch (AuthenticatorException e) {
        return new MusicSearchResult(null, MusicSearchError.AUTHENTICATION_ERROR);
    } catch (OperationCanceledException e) {
        return new MusicSearchResult(null, MusicSearchError.AUTHENTICATION_ERROR);
    }

    try {
        String playerId = am.getUserData(account, Constants.LAST_PLAYER_ID_DATA);
        return doSearch(playerId, authToken);
    } catch (JSONException e) {
        return new MusicSearchResult(null, MusicSearchError.SERVER_ERROR);
    } catch (ParseException e) {
        return new MusicSearchResult(null, MusicSearchError.SERVER_ERROR);
    } catch (IOException e) {
        return new MusicSearchResult(null, MusicSearchError.SERVER_ERROR);
    } catch (AuthenticationException e) {
        if (attemptReauth) {
            Log.d(TAG, "soft auth failure");
            am.invalidateAuthToken(Constants.ACCOUNT_TYPE, authToken);
            return attemptSearch(false);
        } else {
            Log.d(TAG, "hard auth failure");
            return new MusicSearchResult(null, MusicSearchError.AUTHENTICATION_ERROR);
        }
    } catch (PlayerInactiveException e) {
        return new MusicSearchResult(null, MusicSearchError.PLAYER_INACTIVE_ERROR);
    } catch (NoLongerInPlayerException e) {
        return new MusicSearchResult(null, MusicSearchError.NO_LONGER_IN_PLAYER_ERROR);
    } catch (KickedException e) {
        return new MusicSearchResult(null, MusicSearchError.KICKED_ERROR);
    }
}

From source file:org.klnusbaum.udj.PlaylistLoader.java

private PlaylistResult attemptLoad(boolean attemptReauth) {
    AccountManager am = AccountManager.get(getContext());
    String authToken = "";
    try {/*from  ww  w  . j a v a2 s  . c o  m*/
        authToken = am.blockingGetAuthToken(account, "", true);
    } catch (IOException e) {
        //TODO this might actually be an auth error
        return new PlaylistResult(null, PlaylistLoadError.AUTHENTICATION_ERROR);
    } catch (AuthenticatorException e) {
        return new PlaylistResult(null, PlaylistLoadError.AUTHENTICATION_ERROR);
    } catch (OperationCanceledException e) {
        return new PlaylistResult(null, PlaylistLoadError.AUTHENTICATION_ERROR);
    }

    try {
        String playerId = am.getUserData(account, Constants.LAST_PLAYER_ID_DATA);
        JSONObject serverResult = ServerConnection.getActivePlaylist(playerId, authToken);
        List<ActivePlaylistEntry> toReturn = RESTProcessor.processActivePlaylist(serverResult, am, account,
                context);
        return new PlaylistResult(toReturn);
    } catch (JSONException e) {
        return new PlaylistResult(null, PlaylistLoadError.SERVER_ERROR);
    } catch (ParseException e) {
        return new PlaylistResult(null, PlaylistLoadError.SERVER_ERROR);
    } catch (IOException e) {
        return new PlaylistResult(null, PlaylistLoadError.SERVER_ERROR);
    } catch (AuthenticationException e) {
        if (attemptReauth) {
            Log.d(TAG, "soft auth failure");
            am.invalidateAuthToken(Constants.ACCOUNT_TYPE, authToken);
            return attemptLoad(false);
        } else {
            Log.d(TAG, "hard auth failure");
            return new PlaylistResult(null, PlaylistLoadError.AUTHENTICATION_ERROR);
        }
    } catch (PlayerInactiveException e) {
        return new PlaylistResult(null, PlaylistLoadError.PLAYER_INACTIVE_ERROR);
    } catch (NoLongerInPlayerException e) {
        return new PlaylistResult(null, PlaylistLoadError.NO_LONGER_IN_PLAYER_ERROR);
    } catch (KickedException e) {
        return new PlaylistResult(null, PlaylistLoadError.KICKED_ERROR);
    }
}

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 {//  ww w  .j a va 2s  . co m
        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:com.example.jumpnote.android.jsonrpc.AuthenticatedJsonRpcJavaClient.java

public void blockingAuthenticateAccount(final Account account, final int needAuthAction,
        boolean forceReauthenticate) throws AuthenticationException, OperationCanceledException,
        RequestedUserAuthenticationException, InvalidAuthTokenException {

    String existingToken = mTokenStoreHelper.getToken(account);
    if (!forceReauthenticate && existingToken != null) {
        BasicClientCookie c = new BasicClientCookie("ACSID", existingToken);
        try {/*from   w  w  w . j ava 2 s .  c o  m*/
            c.setDomain(new URI(Config.SERVER_BASE_URL).getHost());
            mHttpClient.getCookieStore().addCookie(c);
            return;
        } catch (URISyntaxException e) {
        }
    }

    // Get an auth token for this account.
    AccountManager am = AccountManager.get(mContext);
    Bundle authBundle = null;
    String authToken = null;

    // Block on getting the auth token result.
    try {
        authBundle = am.getAuthToken(account, APPENGINE_SERVICE_NAME, needAuthAction == NEED_AUTH_NOTIFICATION,
                null, null).getResult();
    } catch (IOException e) {
        throw new AuthenticationException("IOException while getting auth token.", e);
    } catch (AuthenticatorException e) {
        throw new AuthenticationException("AuthenticatorException while getting auth token.", e);
    }

    if (authBundle.containsKey(AccountManager.KEY_INTENT) && needAuthAction == NEED_AUTH_INTENT) {
        Intent authRequestIntent = (Intent) authBundle.get(AccountManager.KEY_INTENT);
        mContext.startActivity(authRequestIntent);
        throw new RequestedUserAuthenticationException();
    } else if (authBundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
        authToken = authBundle.getString(AccountManager.KEY_AUTHTOKEN);
    }

    if (authToken == null) {
        throw new AuthenticationException("Retrieved auth token was null.");
    }

    try {
        blockingAuthenticateWithToken(account, authToken);
    } catch (InvalidAuthTokenException e) {
        am.invalidateAuthToken(account.type, authToken);
        throw e;
    }
}

From source file:vn.mbm.phimp.me.gallery3d.picasa.PicasaApi.java

public int getAlbums(AccountManager accountManager, SyncResult syncResult, UserEntry user,
        GDataParser.EntryHandler handler) {
    // Construct the query URL for user albums.
    StringBuilder builder = new StringBuilder(BASE_URL);
    builder.append("user/");
    builder.append(Uri.encode(mAuth.user));
    builder.append(BASE_QUERY_STRING);/*  w w w.j a  v a2 s .c  o  m*/
    builder.append("&kind=album");
    try {
        // Send the request.
        synchronized (mOperation) {
            GDataClient.Operation operation = mOperation;
            operation.inOutEtag = user.albumsEtag;
            boolean retry = false;
            int numRetries = 1;
            do {
                retry = false;
                synchronized (mClient) {
                    mClient.get(builder.toString(), operation);
                }
                switch (operation.outStatus) {
                case HttpStatus.SC_OK:
                    break;
                case HttpStatus.SC_NOT_MODIFIED:
                    return RESULT_NOT_MODIFIED;
                case HttpStatus.SC_FORBIDDEN:
                case HttpStatus.SC_UNAUTHORIZED:
                    if (!retry) {
                        accountManager.invalidateAuthToken(PicasaService.ACCOUNT_TYPE, mAuth.authToken);
                        retry = true;
                    }
                    if (numRetries == 0) {
                        ++syncResult.stats.numAuthExceptions;
                    }
                default:
                    Log.i(TAG, "getAlbums uri " + builder.toString());
                    Log.e(TAG, "getAlbums: unexpected status code " + operation.outStatus + " data: "
                            + operation.outBody.toString());
                    ++syncResult.stats.numIoExceptions;
                    return RESULT_ERROR;
                }
                --numRetries;
            } while (retry && numRetries >= 0);

            // Store the new ETag for the user/albums feed.
            user.albumsEtag = operation.inOutEtag;

            // Parse the response.
            synchronized (mParser) {
                GDataParser parser = mParser;
                parser.setEntry(mAlbumInstance);
                parser.setHandler(handler);
                try {
                    Xml.parse(operation.outBody, Xml.Encoding.UTF_8, parser);
                } catch (SocketException e) {
                    Log.e(TAG, "getAlbumPhotos: " + e);
                    ++syncResult.stats.numIoExceptions;
                    e.printStackTrace();
                    return RESULT_ERROR;
                }
            }
        }
        return RESULT_OK;
    } catch (IOException e) {
        Log.e(TAG, "getAlbums: " + e);
        ++syncResult.stats.numIoExceptions;
    } catch (SAXException e) {
        Log.e(TAG, "getAlbums: " + e);
        ++syncResult.stats.numParseExceptions;
    }
    return RESULT_ERROR;
}

From source file:com.ocp.picasa.PicasaApi.java

public int getAlbums(AccountManager accountManager, SyncResult syncResult, UserEntry user,
        GDataParser.EntryHandler handler) {
    // Construct the query URL for user albums.
    StringBuilder builder = new StringBuilder(BASE_URL);
    builder.append("user/");
    builder.append(Uri.encode(mAuth.user));
    builder.append(BASE_QUERY_STRING);//from   www.j  a va2 s .c  o  m
    builder.append("&kind=album");
    try {
        // Send the request.
        synchronized (mOperation) {
            GDataClient.Operation operation = mOperation;
            operation.inOutEtag = user.albumsEtag;
            boolean retry = false;
            int numRetries = 1;
            do {
                retry = false;
                synchronized (mClient) {
                    mClient.get(builder.toString(), operation);
                }
                switch (operation.outStatus) {
                case HttpStatus.SC_OK:
                    break;
                case HttpStatus.SC_NOT_MODIFIED:
                    return RESULT_NOT_MODIFIED;
                case HttpStatus.SC_FORBIDDEN:
                case HttpStatus.SC_UNAUTHORIZED:
                    if (!retry) {
                        accountManager.invalidateAuthToken(PicasaService.ACCOUNT_TYPE, mAuth.authToken);
                        retry = true;
                    }
                    if (numRetries == 0) {
                        ++syncResult.stats.numAuthExceptions;
                    }
                default:
                    Log.i(Gallery.TAG, TAG + ": " + "getAlbums uri " + builder.toString());
                    Log.e(Gallery.TAG, TAG + ": " + "getAlbums: unexpected status code " + operation.outStatus
                            + " data: " + operation.outBody.toString());
                    ++syncResult.stats.numIoExceptions;
                    return RESULT_ERROR;
                }
                --numRetries;
            } while (retry && numRetries >= 0);

            // Store the new ETag for the user/albums feed.
            user.albumsEtag = operation.inOutEtag;

            // Parse the response.
            synchronized (mParser) {
                GDataParser parser = mParser;
                parser.setEntry(mAlbumInstance);
                parser.setHandler(handler);
                try {
                    Xml.parse(operation.outBody, Xml.Encoding.UTF_8, parser);
                } catch (SocketException e) {
                    Log.e(Gallery.TAG, TAG + ": " + "getAlbumPhotos: " + e);
                    ++syncResult.stats.numIoExceptions;
                    e.printStackTrace();
                    return RESULT_ERROR;
                }
            }
        }
        return RESULT_OK;
    } catch (IOException e) {
        Log.e(Gallery.TAG, TAG + ": " + "getAlbums: " + e);
        ++syncResult.stats.numIoExceptions;
    } catch (SAXException e) {
        Log.e(Gallery.TAG, TAG + ": " + "getAlbums: " + e);
        ++syncResult.stats.numParseExceptions;
    }
    return RESULT_ERROR;
}

From source file:com.pindroid.client.PinboardApi.java

/**
 * Performs an api call to Pinboard's http based api methods.
 * /* ww w  .j a v  a  2 s  . c o m*/
 * @param url URL of the api method to call.
 * @param params Extra parameters included in the api call, as specified by different methods.
 * @param account The account being synced.
 * @param context The current application context.
 * @return A String containing the response from the server.
 * @throws IOException If a server error was encountered.
 * @throws AuthenticationException If an authentication error was encountered.
 * @throws TooManyRequestsException 
 * @throws PinboardException 
 */
private static InputStream PinboardApiCall(String url, TreeMap<String, String> params, Account account,
        Context context)
        throws IOException, AuthenticationException, TooManyRequestsException, PinboardException {

    final AccountManager am = AccountManager.get(context);

    if (account == null)
        throw new AuthenticationException();

    final String username = account.name;
    String authtoken = "00000000000000000000"; // need to provide a sane default value, since a token that is too short causes a 500 error instead of 401

    try {
        String tempAuthtoken = am.blockingGetAuthToken(account, Constants.AUTHTOKEN_TYPE, true);
        if (tempAuthtoken != null)
            authtoken = tempAuthtoken;
    } catch (Exception e) {
        e.printStackTrace();
        throw new AuthenticationException("Error getting auth token");
    }

    params.put("auth_token", username + ":" + authtoken);

    final Uri.Builder builder = new Uri.Builder();
    builder.scheme(SCHEME);
    builder.authority(PINBOARD_AUTHORITY);
    builder.appendEncodedPath(url);
    for (String key : params.keySet()) {
        builder.appendQueryParameter(key, params.get(key));
    }

    String apiCallUrl = builder.build().toString();

    Log.d("apiCallUrl", apiCallUrl);
    final HttpGet post = new HttpGet(apiCallUrl);

    post.setHeader("User-Agent", "PinDroid");
    post.setHeader("Accept-Encoding", "gzip");

    final DefaultHttpClient client = (DefaultHttpClient) HttpClientFactory.getThreadSafeClient();

    final HttpResponse resp = client.execute(post);

    final int statusCode = resp.getStatusLine().getStatusCode();

    if (statusCode == HttpStatus.SC_OK) {

        final HttpEntity entity = resp.getEntity();

        InputStream instream = entity.getContent();

        final Header encoding = entity.getContentEncoding();

        if (encoding != null && encoding.getValue().equalsIgnoreCase("gzip")) {
            instream = new GZIPInputStream(instream);
        }

        return instream;
    } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
        am.invalidateAuthToken(Constants.AUTHTOKEN_TYPE, authtoken);

        try {
            authtoken = am.blockingGetAuthToken(account, Constants.AUTHTOKEN_TYPE, true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AuthenticationException("Invalid auth token");
        }

        throw new AuthenticationException();
    } else if (statusCode == Constants.HTTP_STATUS_TOO_MANY_REQUESTS) {
        throw new TooManyRequestsException(300);
    } else if (statusCode == HttpStatus.SC_REQUEST_URI_TOO_LONG) {
        throw new PinboardException();
    } else {
        throw new IOException();
    }
}

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   ww w.ja  va 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;
    }

    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:cn.code.notes.gtask.remote.GTaskClient.java

private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
    String authToken;//  w  w w.  j a  va  2s .  c  o  m
    AccountManager accountManager = AccountManager.get(activity);
    Account[] accounts = accountManager.getAccountsByType("com.google");

    if (accounts.length == 0) {
        Log.e(TAG, "there is no available google account");
        return null;
    }

    String accountName = SystemEditActivity.getSyncAccountName(activity);
    Account account = null;
    for (Account a : accounts) {
        if (a.name.equals(accountName)) {
            account = a;
            break;
        }
    }
    if (account != null) {
        mAccount = account;
    } else {
        Log.e(TAG, "unable to get an account with the same name in the settings");
        return null;
    }

    // get the token now
    AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account, "goanna_mobile",
            null, activity, null, null);
    try {
        Bundle authTokenBundle = accountManagerFuture.getResult();
        authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
        if (invalidateToken) {
            accountManager.invalidateAuthToken("com.google", authToken);
            loginGoogleAccount(activity, false);
        }
    } catch (Exception e) {
        Log.e(TAG, "get auth token failed");
        authToken = null;
    }

    return authToken;
}