Example usage for android.text.util Rfc822Tokenizer tokenize

List of usage examples for android.text.util Rfc822Tokenizer tokenize

Introduction

In this page you can find the example usage for android.text.util Rfc822Tokenizer tokenize.

Prototype

public static Rfc822Token[] tokenize(CharSequence text) 

Source Link

Document

This method will try to take a string like "Foo Bar (something) <foo\@google.com>, blah\@google.com (something)" and convert it into one or more Rfc822Tokens.

Usage

From source file:com.DGSD.Teexter.UI.Recipient.RecipientAlternatesAdapter.java

/**
 * Get a HashMap of address to RecipientEntry that contains all contact
 * information for a contact with the provided address, if one exists. This
 * may block the UI, so run it in an async task.
 * /*from ww w .  j  a  v a  2  s  .  c  o m*/
 * @param context
 *            Context.
 * @param inAddresses
 *            Array of addresses on which to perform the lookup.
 * @return HashMap<String,RecipientEntry>
 */
public static HashMap<String, RecipientEntry> getMatchingRecipients(Context context, String[] inAddresses) {
    int addressesSize = Math.min(MAX_LOOKUPS, inAddresses.length);
    String[] addresses = new String[addressesSize];
    StringBuilder bindString = new StringBuilder();
    // Create the "?" string and set up arguments.
    for (int i = 0; i < addressesSize; i++) {
        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(inAddresses[i].toLowerCase());
        addresses[i] = (tokens.length > 0 ? tokens[0].getAddress() : inAddresses[i]);
        bindString.append("?");
        if (i < addressesSize - 1) {
            bindString.append(",");
        }
    }

    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Doing reverse lookup for " + addresses.toString());
    }

    HashMap<String, RecipientEntry> recipientEntries = new HashMap<String, RecipientEntry>();
    Cursor c = context.getContentResolver().query(Phone.CONTENT_URI, EmailQuery.PROJECTION,
            Email.ADDRESS + " IN (" + bindString.toString() + ")", addresses, null);
    if (c != null) {
        try {
            if (c.moveToFirst()) {
                do {
                    String address = c.getString(EmailQuery.ADDRESS);
                    recipientEntries.put(address,
                            RecipientEntry.constructTopLevelEntry(c.getString(EmailQuery.NAME),
                                    c.getString(EmailQuery.ADDRESS), c.getInt(EmailQuery.ADDRESS_TYPE),
                                    c.getString(EmailQuery.ADDRESS_LABEL), c.getLong(EmailQuery.CONTACT_ID),
                                    c.getLong(EmailQuery.DATA_ID),
                                    c.getString(EmailQuery.PHOTO_THUMBNAIL_URI)));
                    if (Log.isLoggable(TAG, Log.DEBUG)) {
                        Log.d(TAG,
                                "Received reverse look up information for " + address + " RESULTS: "
                                        + " NAME : " + c.getString(EmailQuery.NAME) + " CONTACT ID : "
                                        + c.getLong(EmailQuery.CONTACT_ID) + " ADDRESS :"
                                        + c.getString(EmailQuery.ADDRESS));
                    }
                } while (c.moveToNext());
            }
        } finally {
            c.close();
        }
    }
    return recipientEntries;
}

From source file:com.android.ex.chips.RecipientAlternatesAdapter.java

/**
 * Get a HashMap of address to RecipientEntry that contains all contact
 * information for a contact with the provided address, if one exists. This
 * may block the UI, so run it in an async task.
 * @param context//from   ww  w  .java2 s.c o  m
 *            Context.
 * @param inAddresses
 *            Array of addresses on which to perform the lookup.
 * @return HashMap<String,RecipientEntry>
 */
public static HashMap<String, RecipientEntry> getMatchingRecipients(Context context,
        ArrayList<String> inAddresses, int addressType) {
    Queries.Query query;
    if (addressType == QUERY_TYPE_EMAIL) {
        query = Queries.EMAIL;
    } else {
        query = Queries.PHONE;
    }
    int addressesSize = Math.min(MAX_LOOKUPS, inAddresses.size());
    String[] addresses = new String[addressesSize];
    StringBuilder bindString = new StringBuilder();
    // Create the "?" string and set up arguments.
    for (int i = 0; i < addressesSize; i++) {
        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(inAddresses.get(i).toLowerCase());
        addresses[i] = (tokens.length > 0 ? tokens[0].getAddress() : inAddresses.get(i));
        bindString.append("?");
        if (i < addressesSize - 1) {
            bindString.append(",");
        }
    }

    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Doing reverse lookup for " + addresses.toString());
    }

    HashMap<String, RecipientEntry> recipientEntries = new HashMap<String, RecipientEntry>();
    Cursor c = context.getContentResolver().query(query.getContentUri(), query.getProjection(),
            query.getProjection()[Queries.Query.DESTINATION] + " IN (" + bindString.toString() + ")", addresses,
            null);

    if (c != null) {
        try {
            if (c.moveToFirst()) {
                do {
                    String address = c.getString(Queries.Query.DESTINATION);
                    recipientEntries.put(address, RecipientEntry.constructTopLevelEntry(
                            c.getString(Queries.Query.NAME), c.getInt(Queries.Query.DISPLAY_NAME_SOURCE),
                            c.getString(Queries.Query.DESTINATION), c.getInt(Queries.Query.DESTINATION_TYPE),
                            c.getString(Queries.Query.DESTINATION_LABEL), c.getLong(Queries.Query.CONTACT_ID),
                            c.getLong(Queries.Query.DATA_ID), c.getString(Queries.Query.PHOTO_THUMBNAIL_URI)));
                    if (Log.isLoggable(TAG, Log.DEBUG)) {
                        Log.d(TAG,
                                "Received reverse look up information for " + address + " RESULTS: "
                                        + " NAME : " + c.getString(Queries.Query.NAME) + " CONTACT ID : "
                                        + c.getLong(Queries.Query.CONTACT_ID) + " ADDRESS :"
                                        + c.getString(Queries.Query.DESTINATION));
                    }
                } while (c.moveToNext());
            }
        } finally {
            c.close();
        }
    }
    return recipientEntries;
}

From source file:cm.confide.ex.chips.RecipientAlternatesAdapter.java

/**
 * Get a HashMap of address to RecipientEntry that contains all contact
 * information for a contact with the provided address, if one exists. This
 * may block the UI, so run it in an async task.
 *
 * @param context Context.//from   w ww.ja  v  a2s.  com
 * @param inAddresses Array of addresses on which to perform the lookup.
 * @param callback RecipientMatchCallback called when a match or matches are found.
 * @return HashMap<String,RecipientEntry>
 */
public static void getMatchingRecipients(Context context, BaseRecipientAdapter adapter,
        ArrayList<String> inAddresses, int addressType, Account account, RecipientMatchCallback callback) {
    Queries.Query query;
    if (addressType == QUERY_TYPE_EMAIL) {
        query = Queries.EMAIL;
    } else {
        query = Queries.PHONE;
    }
    int addressesSize = Math.min(MAX_LOOKUPS, inAddresses.size());
    HashSet<String> addresses = new HashSet<String>();
    StringBuilder bindString = new StringBuilder();
    // Create the "?" string and set up arguments.
    for (int i = 0; i < addressesSize; i++) {
        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(inAddresses.get(i).toLowerCase());
        addresses.add(tokens.length > 0 ? tokens[0].getAddress() : inAddresses.get(i));
        bindString.append("?");
        if (i < addressesSize - 1) {
            bindString.append(",");
        }
    }

    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Doing reverse lookup for " + addresses.toString());
    }

    String[] addressArray = new String[addresses.size()];
    addresses.toArray(addressArray);
    HashMap<String, RecipientEntry> recipientEntries = null;
    Cursor c = null;

    try {
        c = context.getContentResolver().query(query.getContentUri(), query.getProjection(),
                query.getProjection()[Queries.Query.DESTINATION] + " IN (" + bindString.toString() + ")",
                addressArray, null);
        recipientEntries = processContactEntries(c);
        callback.matchesFound(recipientEntries);
    } finally {
        if (c != null) {
            c.close();
        }
    }
    // See if any entries did not resolve; if so, we need to check other
    // directories
    final Set<String> matchesNotFound = new HashSet<String>();
    if (recipientEntries.size() < addresses.size()) {
        final List<DirectorySearchParams> paramsList;
        Cursor directoryCursor = null;
        try {
            directoryCursor = context.getContentResolver().query(DirectoryListQuery.URI,
                    DirectoryListQuery.PROJECTION, null, null, null);
            if (directoryCursor == null) {
                paramsList = null;
            } else {
                paramsList = BaseRecipientAdapter.setupOtherDirectories(context, directoryCursor, account);
            }
        } finally {
            if (directoryCursor != null) {
                directoryCursor.close();
            }
        }
        // Run a directory query for each unmatched recipient.
        HashSet<String> unresolvedAddresses = new HashSet<String>();
        for (String address : addresses) {
            if (!recipientEntries.containsKey(address)) {
                unresolvedAddresses.add(address);
            }
        }

        matchesNotFound.addAll(unresolvedAddresses);

        if (paramsList != null) {
            Cursor directoryContactsCursor = null;
            for (String unresolvedAddress : unresolvedAddresses) {
                for (int i = 0; i < paramsList.size(); i++) {
                    try {
                        directoryContactsCursor = doQuery(unresolvedAddress, 1, paramsList.get(i).directoryId,
                                account, context.getContentResolver(), query);
                    } finally {
                        if (directoryContactsCursor != null && directoryContactsCursor.getCount() == 0) {
                            directoryContactsCursor.close();
                            directoryContactsCursor = null;
                        } else {
                            break;
                        }
                    }
                }
                if (directoryContactsCursor != null) {
                    try {
                        final Map<String, RecipientEntry> entries = processContactEntries(
                                directoryContactsCursor);

                        for (final String address : entries.keySet()) {
                            matchesNotFound.remove(address);
                        }

                        callback.matchesFound(entries);
                    } finally {
                        directoryContactsCursor.close();
                    }
                }
            }
        }
    }

    // If no matches found in contact provider or the directories, try the extension
    // matcher.
    // todo (aalbert): This whole method needs to be in the adapter?
    if (adapter != null) {
        final Map<String, RecipientEntry> entries = adapter.getMatchingRecipients(matchesNotFound);
        if (entries != null && entries.size() > 0) {
            callback.matchesFound(entries);
            for (final String address : entries.keySet()) {
                matchesNotFound.remove(address);
            }
        }
    }
    callback.matchesNotFound(matchesNotFound);
}

From source file:info.guardianproject.otr.app.im.app.AddContactActivity.java

void inviteBuddies() {
    Rfc822Token[] recipients = Rfc822Tokenizer.tokenize(mAddressList.getText());
    try {//ww  w. j a v a2s  .c  om
        IImConnection conn = mApp.getConnection(mProviderId);
        IContactList list = getContactList(conn);
        if (list == null) {
            // Log.e(ImApp.LOG_TAG, "<AddContactActivity> can't find given contact list:"
            //                    + getSelectedListName());
            finish();
        } else {
            boolean fail = false;
            String username = null;

            for (Rfc822Token recipient : recipients) {
                username = recipient.getAddress();
                if (username.indexOf('@') == -1) {
                    username = username + "@" + getDomain(mProviderId);
                }
                if (Log.isLoggable(ImApp.LOG_TAG, Log.DEBUG)) {
                    log("addContact:" + username);
                }

                int res = list.addContact(username);
                if (res != ImErrorInfo.NO_ERROR) {
                    fail = true;
                    mHandler.showAlert(R.string.error,
                            ErrorResUtils.getErrorRes(getResources(), res, username));
                }

            }
            // close the screen if there's no error.
            if (!fail) {

                if (username != null) {
                    Intent intent = new Intent();
                    intent.putExtra(ContactsPickerActivity.EXTRA_RESULT_USERNAME, username);
                    intent.putExtra(ContactsPickerActivity.EXTRA_RESULT_PROVIDER, mProviderId);
                    setResult(RESULT_OK, intent);
                    finish();
                }

            }
        }
    } catch (RemoteException ex) {
        Log.e(ImApp.LOG_TAG, "<AddContactActivity> inviteBuddies: caught " + ex);
    }
}

From source file:org.awesomeapp.messenger.ui.AddContactActivity.java

void inviteBuddies() {
    Rfc822Token[] recipients = Rfc822Tokenizer.tokenize(mNewAddress.getText());

    Pattern pattern = Pattern.compile(EMAIL_PATTERN);

    boolean foundOne = false;

    for (Rfc822Token recipient : recipients) {

        String address = recipient.getAddress();
        if (pattern.matcher(address).matches()) {
            new AddContactAsyncTask(mApp.getDefaultProviderId(), mApp.getDefaultAccountId(), mApp)
                    .execute(address, null, null);
            foundOne = true;/* w  w w  . j  a v  a 2s .c om*/
        }
    }

    if (foundOne) {
        Intent intent = new Intent();
        intent.putExtra(ContactsPickerActivity.EXTRA_RESULT_USERNAME, recipients[0].getAddress());
        intent.putExtra(ContactsPickerActivity.EXTRA_RESULT_PROVIDER, mApp.getDefaultProviderId());
        setResult(RESULT_OK, intent);
        finish();
    }

}

From source file:com.android.messaging.ui.contact.ContactRecipientAdapter.java

/**
 * Called when we need to substitute temporary recipient chips with better alternatives.
 * For example, if a list of comma-delimited phone numbers are pasted into the edit box,
 * we want to be able to look up in the ContactUtil for exact matches and get contact
 * details such as name and photo thumbnail for the contact to display a better chip.
 *///from ww  w.j a  v a 2  s.  co  m
@Override
public void getMatchingRecipients(final ArrayList<String> inAddresses, final RecipientMatchCallback callback) {
    final int addressesSize = Math.min(RecipientAlternatesAdapter.MAX_LOOKUPS, inAddresses.size());
    final HashSet<String> addresses = new HashSet<String>();
    for (int i = 0; i < addressesSize; i++) {
        final Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(inAddresses.get(i).toLowerCase());
        addresses.add(tokens.length > 0 ? tokens[0].getAddress() : inAddresses.get(i));
    }

    final Map<String, RecipientEntry> recipientEntries = new HashMap<String, RecipientEntry>();
    // query for each address
    for (final String address : addresses) {
        final Cursor cursor = ContactUtil.lookupDestination(getContext(), address).performSynchronousQuery();
        if (cursor != null) {
            try {
                if (cursor.moveToNext()) {
                    // There may be multiple matches to the same number, always take the
                    // first match.
                    // TODO: May need to consider if there's an existing conversation
                    // that matches this particular contact and prioritize that contact.
                    final RecipientEntry entry = ContactUtil.createRecipientEntryForPhoneQuery(cursor, true);
                    recipientEntries.put(address, entry);
                }

            } finally {
                cursor.close();
            }
        }
    }

    // report matches
    callback.matchesFound(recipientEntries);
}

From source file:com.chen.mail.browse.SendersView.java

private static void formatDefault(ConversationItemViewModel header, String sendersString, Context context,
        final CharacterStyle readStyleSpan, final boolean resourceCachingRequired) {
    try {/*w  ww  . ja  v a  2s.c  o  m*/
        getSenderResources(context, resourceCachingRequired);
        // Clear any existing sender fragments; we must re-make all of them.
        header.senderFragments.clear();
        // TODO: unify this with ConversationItemView.calculateTextsAndBitmaps's tokenization
        final Rfc822Token[] senders = Rfc822Tokenizer.tokenize(sendersString);
        final String[] namesOnly = new String[senders.length];
        String display;
        for (int i = 0; i < senders.length; i++) {
            display = Address.decodeAddressName(senders[i].getName());
            if (TextUtils.isEmpty(display)) {
                display = senders[i].getAddress();
            }
            namesOnly[i] = display;
        }
        generateSenderFragments(header, namesOnly, readStyleSpan);
    } finally {
        if (!resourceCachingRequired) {
            clearResourceCache();
        }
    }
}

From source file:com.android.ex.chips.RecipientEditTextView.java

RecipientEntry createTokenizedEntry(final String token) {
    if (TextUtils.isEmpty(token))
        return null;
    if (isPhoneQuery() && isPhoneNumber(token))
        return RecipientEntry.constructFakePhoneEntry(token, true);
    final Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(token);
    String display = null;//from  w w  w .j a  va2s. c  o  m
    boolean isValid = isValid(token);
    if (isValid && tokens != null && tokens.length > 0) {
        // If we can get a name from tokenizing, then generate an entry from
        // this.
        display = tokens[0].getName();
        if (!TextUtils.isEmpty(display))
            return RecipientEntry.constructGeneratedEntry(display, tokens[0].getAddress(), isValid);
        else {
            display = tokens[0].getAddress();
            if (!TextUtils.isEmpty(display))
                return RecipientEntry.constructFakeEntry(display, isValid);
        }
    }
    // Unable to validate the token or to create a valid token from it.
    // Just create a chip the user can edit.
    String validatedToken = null;
    if (mValidator != null && !isValid) {
        // Try fixing up the entry using the validator.
        validatedToken = mValidator.fixText(token).toString();
        if (!TextUtils.isEmpty(validatedToken))
            if (validatedToken.contains(token)) {
                // protect against the case of a validator with a null
                // domain,
                // which doesn't add a domain to the token
                final Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(validatedToken);
                if (tokenized.length > 0) {
                    validatedToken = tokenized[0].getAddress();
                    isValid = true;
                }
            } else {
                // We ran into a case where the token was invalid and
                // removed
                // by the validator. In this case, just use the original
                // token
                // and let the user sort out the error chip.
                validatedToken = null;
                isValid = false;
            }
    }
    // Otherwise, fallback to just creating an editable email address chip.
    return RecipientEntry.constructFakeEntry(!TextUtils.isEmpty(validatedToken) ? validatedToken : token,
            isValid);
}

From source file:com.android.ex.chips.RecipientEditTextView.java

private static String tokenizeAddress(final String destination) {
    final Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(destination);
    if (tokens != null && tokens.length > 0)
        return tokens[0].getAddress();
    return destination;
}

From source file:com.android.mail.compose.ComposeActivity.java

/**
 * Compare all the recipients of an email to the current account and all
 * custom addresses associated with that account. Return the match if there
 * is one, or the default account if there isn't.
 *//*from w  ww  .ja  va 2 s  .  co  m*/
protected ReplyFromAccount getMatchingRecipient(Account account, List<String> sentTo) {
    // Tokenize the list and place in a hashmap.
    ReplyFromAccount matchingReplyFrom = null;
    Rfc822Token[] tokens;
    HashSet<String> recipientsMap = new HashSet<String>();
    for (String address : sentTo) {
        tokens = Rfc822Tokenizer.tokenize(address);
        for (final Rfc822Token token : tokens) {
            recipientsMap.add(token.getAddress());
        }
    }

    int matchingAddressCount = 0;
    List<ReplyFromAccount> customFroms;
    customFroms = account.getReplyFroms();
    if (customFroms != null) {
        for (ReplyFromAccount entry : customFroms) {
            if (recipientsMap.contains(entry.address)) {
                matchingReplyFrom = entry;
                matchingAddressCount++;
            }
        }
    }
    if (matchingAddressCount > 1) {
        matchingReplyFrom = getDefaultReplyFromAccount(account);
    }
    return matchingReplyFrom;
}