Example usage for android.accounts OperationCanceledException OperationCanceledException

List of usage examples for android.accounts OperationCanceledException OperationCanceledException

Introduction

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

Prototype

public OperationCanceledException() 

Source Link

Usage

From source file:com.hemou.android.account.AccountUtils.java

/**
 * Get account used for authentication//from w w w  .j a  v  a 2 s .  co  m
 * 
 * @param manager
 * @param act
 * @return account
 * @throws IOException
 * @throws AccountsException
 */
public static Account getAccount(final AccountManager manager, final Activity act)
        throws IOException, AccountsException {
    final String SUB_TAG = "acnt_get";
    final boolean loggable = Log.isLoggable(SUB_TAG, DEBUG);
    if (loggable)
        Log.d(SUB_TAG, "Getting account");

    if (act == null)
        throw new IllegalArgumentException("Activity cannot be null");

    if (act.isFinishing()) {
        Log.v(SUB_TAG, act.getClass().getName()
                + "--->?finish()OperationCanceledException...");
        throw new OperationCanceledException();
    }

    Account[] accounts;
    try {
        if (!hasAuthenticator(manager)) {
            Log.e(SUB_TAG, "Current user is not under the authenticated environment....");
            throw new AuthenticatorConflictException();
        }

        while ((accounts = getAccounts(manager)).length == 0) {
            Bundle result = manager.addAccount(ACCOUNT_TYPE, AUTHTOKEN_TYPE, null, null, act, null, null)
                    .getResult();
        }
    } catch (OperationCanceledException e) {
        Log.d(SUB_TAG, "Excepting retrieving account", e);
        act.finish();
        throw e;
    } catch (AccountsException e) {
        Log.d(SUB_TAG, "Excepting retrieving account", e);
        throw e;
    } catch (AuthenticatorConflictException e) {
        act.runOnUiThread(new Runnable() {

            public void run() {
                showConflictMessage(act);
            }
        });
        throw e;
    } catch (IOException e) {
        Log.d(SUB_TAG, "Excepting retrieving account", e);
        throw e;
    }

    // if (loggable)
    Log.d(SUB_TAG, "Returning account " + accounts[0].name);

    return accounts[0];
}

From source file:org.kontalk.sync.Syncer.java

/**
 * The actual sync procedure.//from  w w  w. jav  a  2 s  . c om
 * This one uses the slowest method ever: it first checks for every phone
 * number in all contacts and it sends them to the server. Once a response
 * is received, it deletes all the raw contacts created by us and then
 * recreates only the ones the server has found a match for.
 */
public void performSync(Context context, Account account, String authority, ContentProviderClient provider,
        ContentProviderClient usersProvider, SyncResult syncResult) throws OperationCanceledException {

    final Map<String, RawPhoneNumberEntry> lookupNumbers = new HashMap<>();
    final List<String> jidList = new ArrayList<>();

    // resync users database
    Log.v(TAG, "resyncing users database");
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    // update users database
    Uri uri = Users.CONTENT_URI.buildUpon().appendQueryParameter(Users.RESYNC, "true").build();
    try {
        int count = usersProvider.update(uri, new ContentValues(), null, null);
        Log.d(TAG, "users database resynced (" + count + ")");
    } catch (Exception e) {
        Log.e(TAG, "error resyncing users database - aborting sync", e);
        syncResult.databaseError = true;
        return;
    }

    // query all contacts
    Cursor cursor;
    try {
        cursor = usersProvider.query(Users.CONTENT_URI_OFFLINE,
                new String[] { Users.JID, Users.NUMBER, Users.LOOKUP_KEY }, null, null, null);
    } catch (Exception e) {
        Log.e(TAG, "error querying users database - aborting sync", e);
        syncResult.databaseError = true;
        return;
    }

    while (cursor.moveToNext()) {
        if (mCanceled) {
            cursor.close();
            throw new OperationCanceledException();
        }

        String jid = cursor.getString(0);
        String number = cursor.getString(1);
        String lookupKey = cursor.getString(2);

        // avoid to send duplicates to the server
        if (lookupNumbers.put(XmppStringUtils.parseLocalpart(jid),
                new RawPhoneNumberEntry(lookupKey, number, jid)) == null)
            jidList.add(jid);
    }
    cursor.close();

    if (mCanceled)
        throw new OperationCanceledException();

    // empty contacts :-|
    if (jidList.size() == 0) {
        // delete all Kontalk raw contacts
        try {
            syncResult.stats.numDeletes += deleteAll(account, provider);
        } catch (Exception e) {
            Log.e(TAG, "contact delete error", e);
            syncResult.databaseError = true;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            try {
                syncResult.stats.numDeletes += deleteProfile(account, provider);
            } catch (Exception e) {
                Log.e(TAG, "profile delete error", e);
                syncResult.databaseError = true;
            }
        }

        commit(usersProvider, syncResult);
    }

    else {
        final LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(mContext);

        // register presence broadcast receiver
        PresenceBroadcastReceiver receiver = new PresenceBroadcastReceiver(jidList, this);
        IntentFilter f = new IntentFilter();
        f.addAction(MessageCenterService.ACTION_PRESENCE);
        f.addAction(MessageCenterService.ACTION_ROSTER_MATCH);
        f.addAction(MessageCenterService.ACTION_PUBLICKEY);
        f.addAction(MessageCenterService.ACTION_BLOCKLIST);
        f.addAction(MessageCenterService.ACTION_LAST_ACTIVITY);
        f.addAction(MessageCenterService.ACTION_CONNECTED);
        lbm.registerReceiver(receiver, f);

        // request current connection status
        MessageCenterService.requestConnectionStatus(mContext);

        // wait for the service to complete its job
        synchronized (this) {
            // wait for connection
            try {
                wait(MAX_WAIT_TIME);
            } catch (InterruptedException e) {
                // simulate canceled operation
                mCanceled = true;
            }
        }

        lbm.unregisterReceiver(receiver);

        // last chance to quit
        if (mCanceled)
            throw new OperationCanceledException();

        List<PresenceItem> res = receiver.getResponse();
        if (res != null) {
            ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
            // TODO operations.size() could be used instead (?)
            int op = 0;

            // this is the time - delete all Kontalk raw contacts
            try {
                syncResult.stats.numDeletes += deleteAll(account, provider);
            } catch (Exception e) {
                Log.e(TAG, "contact delete error", e);
                syncResult.databaseError = true;
                return;
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                try {
                    syncResult.stats.numDeletes += deleteProfile(account, provider);
                } catch (Exception e) {
                    Log.e(TAG, "profile delete error", e);
                    syncResult.databaseError = true;
                }
            }

            ContentValues registeredValues = new ContentValues();
            registeredValues.put(Users.REGISTERED, 1);
            for (int i = 0; i < res.size(); i++) {
                PresenceItem entry = res.get(i);
                if (entry.discarded)
                    continue;

                final RawPhoneNumberEntry data = lookupNumbers.get(XmppStringUtils.parseLocalpart(entry.from));
                if (data != null && data.lookupKey != null) {
                    // add contact
                    addContact(account, getDisplayName(provider, data.lookupKey, data.number), data.number,
                            data.jid, operations, op++);
                } else {
                    syncResult.stats.numSkippedEntries++;
                }

                // update fields
                try {
                    String status = entry.status;

                    if (!TextUtils.isEmpty(status))
                        registeredValues.put(Users.STATUS, status);
                    else
                        registeredValues.putNull(Users.STATUS);

                    if (entry.timestamp >= 0)
                        registeredValues.put(Users.LAST_SEEN, entry.timestamp);
                    else
                        registeredValues.putNull(Users.LAST_SEEN);

                    if (entry.publicKey != null) {
                        try {
                            PGPPublicKey pubKey = PGP.getMasterKey(entry.publicKey);
                            // trust our own key blindly
                            int trustLevel = Authenticator.isSelfJID(mContext, entry.from)
                                    ? MyUsers.Keys.TRUST_VERIFIED
                                    : -1;
                            // update keys table immediately
                            Keyring.setKey(mContext, entry.from, entry.publicKey, trustLevel);

                            // no data from system contacts, use name from public key
                            if (data == null) {
                                PGPUserID uid = PGP.parseUserId(pubKey,
                                        XmppStringUtils.parseDomain(entry.from));
                                if (uid != null) {
                                    registeredValues.put(Users.DISPLAY_NAME, uid.getName());
                                }
                            }
                        } catch (Exception e) {
                            Log.w(TAG, "unable to parse public key", e);
                        }
                    } else {
                        // use roster name if no contact data available
                        if (data == null && entry.rosterName != null) {
                            registeredValues.put(Users.DISPLAY_NAME, entry.rosterName);
                        }
                    }

                    // blocked status
                    registeredValues.put(Users.BLOCKED, entry.blocked);
                    // user JID as reported by the server
                    registeredValues.put(Users.JID, entry.from);

                    /*
                     * Since UsersProvider.resync inserted the user row
                     * using our server name, it might have changed because
                     * of what the server reported. We already put into the
                     * values the new JID, but we need to use the old one
                     * in the where condition so we will have a match.
                     */
                    String origJid;
                    if (data != null)
                        origJid = XMPPUtils.createLocalJID(mContext,
                                XmppStringUtils.parseLocalpart(entry.from));
                    else
                        origJid = entry.from;
                    usersProvider.update(Users.CONTENT_URI_OFFLINE, registeredValues, Users.JID + " = ?",
                            new String[] { origJid });

                    // clear data
                    registeredValues.remove(Users.DISPLAY_NAME);

                    // if this is our own contact, trust our own key later
                    if (Authenticator.isSelfJID(mContext, entry.from)) {
                        // register our profile while we're at it
                        if (data != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                            // add contact
                            addProfile(account, Authenticator.getDefaultDisplayName(mContext), data.number,
                                    data.jid, operations, op++);
                        }
                    }
                } catch (Exception e) {
                    Log.e(TAG, "error updating users database", e);
                    // we shall continue here...
                }
            }

            try {
                if (operations.size() > 0)
                    provider.applyBatch(operations);
                syncResult.stats.numInserts += op;
                syncResult.stats.numEntries += op;
            } catch (Exception e) {
                Log.w(TAG, "contact write error", e);
                syncResult.stats.numSkippedEntries += op;
                /*
                 * We do not consider system contacts failure a fatal error.
                 * This is actually a workaround for systems with disabled permissions or
                 * exotic firmwares. It can also protect against security 3rd party apps or
                 * non-Android platforms, such as Jolla/Alien Dalvik.
                 */
            }

            commit(usersProvider, syncResult);
        }

        // timeout or error
        else {
            Log.w(TAG, "connection timeout - aborting sync");

            syncResult.stats.numIoExceptions++;
        }
    }
}