RawContactModifier.java revision 428f008513d1591cc08fcfe2cf0c9237fb313241
1/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.contacts.model;
18
19import android.content.ContentValues;
20import android.content.Context;
21import android.database.Cursor;
22import android.net.Uri;
23import android.os.Bundle;
24import android.provider.ContactsContract;
25import android.provider.ContactsContract.CommonDataKinds.BaseTypes;
26import android.provider.ContactsContract.CommonDataKinds.Email;
27import android.provider.ContactsContract.CommonDataKinds.Event;
28import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
29import android.provider.ContactsContract.CommonDataKinds.Im;
30import android.provider.ContactsContract.CommonDataKinds.Nickname;
31import android.provider.ContactsContract.CommonDataKinds.Note;
32import android.provider.ContactsContract.CommonDataKinds.Organization;
33import android.provider.ContactsContract.CommonDataKinds.Phone;
34import android.provider.ContactsContract.CommonDataKinds.Photo;
35import android.provider.ContactsContract.CommonDataKinds.Relation;
36import android.provider.ContactsContract.CommonDataKinds.SipAddress;
37import android.provider.ContactsContract.CommonDataKinds.StructuredName;
38import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
39import android.provider.ContactsContract.CommonDataKinds.Website;
40import android.provider.ContactsContract.Data;
41import android.provider.ContactsContract.Intents;
42import android.provider.ContactsContract.Intents.Insert;
43import android.provider.ContactsContract.RawContacts;
44import android.text.TextUtils;
45import android.util.Log;
46import android.util.SparseArray;
47import android.util.SparseIntArray;
48
49import com.android.contacts.ContactsUtils;
50import com.android.contacts.common.util.CommonDateUtils;
51import com.android.contacts.editor.EventFieldEditorView;
52import com.android.contacts.editor.PhoneticNameEditorView;
53import com.android.contacts.model.RawContactDelta.ValuesDelta;
54import com.android.contacts.common.model.account.AccountType;
55import com.android.contacts.common.model.account.AccountType.EditField;
56import com.android.contacts.common.model.account.AccountType.EditType;
57import com.android.contacts.common.model.account.AccountType.EventEditType;
58import com.android.contacts.common.model.account.GoogleAccountType;
59import com.android.contacts.common.model.dataitem.DataKind;
60import com.android.contacts.model.dataitem.StructuredNameDataItem;
61import com.android.contacts.util.DateUtils;
62import com.android.contacts.util.NameConverter;
63
64import java.text.ParsePosition;
65import java.util.ArrayList;
66import java.util.Arrays;
67import java.util.Calendar;
68import java.util.Date;
69import java.util.HashSet;
70import java.util.Iterator;
71import java.util.List;
72import java.util.Locale;
73import java.util.Set;
74
75/**
76 * Helper methods for modifying an {@link RawContactDelta}, such as inserting
77 * new rows, or enforcing {@link AccountType}.
78 */
79public class RawContactModifier {
80    private static final String TAG = RawContactModifier.class.getSimpleName();
81
82    /** Set to true in order to view logs on entity operations */
83    private static final boolean DEBUG = false;
84
85    /**
86     * For the given {@link RawContactDelta}, determine if the given
87     * {@link DataKind} could be inserted under specific
88     * {@link AccountType}.
89     */
90    public static boolean canInsert(RawContactDelta state, DataKind kind) {
91        // Insert possible when have valid types and under overall maximum
92        final int visibleCount = state.getMimeEntriesCount(kind.mimeType, true);
93        final boolean validTypes = hasValidTypes(state, kind);
94        final boolean validOverall = (kind.typeOverallMax == -1)
95                || (visibleCount < kind.typeOverallMax);
96        return (validTypes && validOverall);
97    }
98
99    public static boolean hasValidTypes(RawContactDelta state, DataKind kind) {
100        if (RawContactModifier.hasEditTypes(kind)) {
101            return (getValidTypes(state, kind).size() > 0);
102        } else {
103            return true;
104        }
105    }
106
107    /**
108     * Ensure that at least one of the given {@link DataKind} exists in the
109     * given {@link RawContactDelta} state, and try creating one if none exist.
110     * @return The child (either newly created or the first existing one), or null if the
111     *     account doesn't support this {@link DataKind}.
112     */
113    public static ValuesDelta ensureKindExists(
114            RawContactDelta state, AccountType accountType, String mimeType) {
115        final DataKind kind = accountType.getKindForMimetype(mimeType);
116        final boolean hasChild = state.getMimeEntriesCount(mimeType, true) > 0;
117
118        if (kind != null) {
119            if (hasChild) {
120                // Return the first entry.
121                return state.getMimeEntries(mimeType).get(0);
122            } else {
123                // Create child when none exists and valid kind
124                final ValuesDelta child = insertChild(state, kind);
125                if (kind.mimeType.equals(Photo.CONTENT_ITEM_TYPE)) {
126                    child.setFromTemplate(true);
127                }
128                return child;
129            }
130        }
131        return null;
132    }
133
134    /**
135     * For the given {@link RawContactDelta} and {@link DataKind}, return the
136     * list possible {@link EditType} options available based on
137     * {@link AccountType}.
138     */
139    public static ArrayList<EditType> getValidTypes(RawContactDelta state, DataKind kind) {
140        return getValidTypes(state, kind, null, true, null);
141    }
142
143    /**
144     * For the given {@link RawContactDelta} and {@link DataKind}, return the
145     * list possible {@link EditType} options available based on
146     * {@link AccountType}.
147     *
148     * @param forceInclude Always include this {@link EditType} in the returned
149     *            list, even when an otherwise-invalid choice. This is useful
150     *            when showing a dialog that includes the current type.
151     */
152    public static ArrayList<EditType> getValidTypes(RawContactDelta state, DataKind kind,
153            EditType forceInclude) {
154        return getValidTypes(state, kind, forceInclude, true, null);
155    }
156
157    /**
158     * For the given {@link RawContactDelta} and {@link DataKind}, return the
159     * list possible {@link EditType} options available based on
160     * {@link AccountType}.
161     *
162     * @param forceInclude Always include this {@link EditType} in the returned
163     *            list, even when an otherwise-invalid choice. This is useful
164     *            when showing a dialog that includes the current type.
165     * @param includeSecondary If true, include any valid types marked as
166     *            {@link EditType#secondary}.
167     * @param typeCount When provided, will be used for the frequency count of
168     *            each {@link EditType}, otherwise built using
169     *            {@link #getTypeFrequencies(RawContactDelta, DataKind)}.
170     */
171    private static ArrayList<EditType> getValidTypes(RawContactDelta state, DataKind kind,
172            EditType forceInclude, boolean includeSecondary, SparseIntArray typeCount) {
173        final ArrayList<EditType> validTypes = new ArrayList<EditType>();
174
175        // Bail early if no types provided
176        if (!hasEditTypes(kind)) return validTypes;
177
178        if (typeCount == null) {
179            // Build frequency counts if not provided
180            typeCount = getTypeFrequencies(state, kind);
181        }
182
183        // Build list of valid types
184        final int overallCount = typeCount.get(FREQUENCY_TOTAL);
185        for (EditType type : kind.typeList) {
186            final boolean validOverall = (kind.typeOverallMax == -1 ? true
187                    : overallCount < kind.typeOverallMax);
188            final boolean validSpecific = (type.specificMax == -1 ? true : typeCount
189                    .get(type.rawValue) < type.specificMax);
190            final boolean validSecondary = (includeSecondary ? true : !type.secondary);
191            final boolean forcedInclude = type.equals(forceInclude);
192            if (forcedInclude || (validOverall && validSpecific && validSecondary)) {
193                // Type is valid when no limit, under limit, or forced include
194                validTypes.add(type);
195            }
196        }
197
198        return validTypes;
199    }
200
201    private static final int FREQUENCY_TOTAL = Integer.MIN_VALUE;
202
203    /**
204     * Count up the frequency that each {@link EditType} appears in the given
205     * {@link RawContactDelta}. The returned {@link SparseIntArray} maps from
206     * {@link EditType#rawValue} to counts, with the total overall count stored
207     * as {@link #FREQUENCY_TOTAL}.
208     */
209    private static SparseIntArray getTypeFrequencies(RawContactDelta state, DataKind kind) {
210        final SparseIntArray typeCount = new SparseIntArray();
211
212        // Find all entries for this kind, bailing early if none found
213        final List<ValuesDelta> mimeEntries = state.getMimeEntries(kind.mimeType);
214        if (mimeEntries == null) return typeCount;
215
216        int totalCount = 0;
217        for (ValuesDelta entry : mimeEntries) {
218            // Only count visible entries
219            if (!entry.isVisible()) continue;
220            totalCount++;
221
222            final EditType type = getCurrentType(entry, kind);
223            if (type != null) {
224                final int count = typeCount.get(type.rawValue);
225                typeCount.put(type.rawValue, count + 1);
226            }
227        }
228        typeCount.put(FREQUENCY_TOTAL, totalCount);
229        return typeCount;
230    }
231
232    /**
233     * Check if the given {@link DataKind} has multiple types that should be
234     * displayed for users to pick.
235     */
236    public static boolean hasEditTypes(DataKind kind) {
237        return kind.typeList != null && kind.typeList.size() > 0;
238    }
239
240    /**
241     * Find the {@link EditType} that describes the given
242     * {@link ValuesDelta} row, assuming the given {@link DataKind} dictates
243     * the possible types.
244     */
245    public static EditType getCurrentType(ValuesDelta entry, DataKind kind) {
246        final Long rawValue = entry.getAsLong(kind.typeColumn);
247        if (rawValue == null) return null;
248        return getType(kind, rawValue.intValue());
249    }
250
251    /**
252     * Find the {@link EditType} that describes the given {@link ContentValues} row,
253     * assuming the given {@link DataKind} dictates the possible types.
254     */
255    public static EditType getCurrentType(ContentValues entry, DataKind kind) {
256        if (kind.typeColumn == null) return null;
257        final Integer rawValue = entry.getAsInteger(kind.typeColumn);
258        if (rawValue == null) return null;
259        return getType(kind, rawValue);
260    }
261
262    /**
263     * Find the {@link EditType} that describes the given {@link Cursor} row,
264     * assuming the given {@link DataKind} dictates the possible types.
265     */
266    public static EditType getCurrentType(Cursor cursor, DataKind kind) {
267        if (kind.typeColumn == null) return null;
268        final int index = cursor.getColumnIndex(kind.typeColumn);
269        if (index == -1) return null;
270        final int rawValue = cursor.getInt(index);
271        return getType(kind, rawValue);
272    }
273
274    /**
275     * Find the {@link EditType} with the given {@link EditType#rawValue}.
276     */
277    public static EditType getType(DataKind kind, int rawValue) {
278        for (EditType type : kind.typeList) {
279            if (type.rawValue == rawValue) {
280                return type;
281            }
282        }
283        return null;
284    }
285
286    /**
287     * Return the precedence for the the given {@link EditType#rawValue}, where
288     * lower numbers are higher precedence.
289     */
290    public static int getTypePrecedence(DataKind kind, int rawValue) {
291        for (int i = 0; i < kind.typeList.size(); i++) {
292            final EditType type = kind.typeList.get(i);
293            if (type.rawValue == rawValue) {
294                return i;
295            }
296        }
297        return Integer.MAX_VALUE;
298    }
299
300    /**
301     * Find the best {@link EditType} for a potential insert. The "best" is the
302     * first primary type that doesn't already exist. When all valid types
303     * exist, we pick the last valid option.
304     */
305    public static EditType getBestValidType(RawContactDelta state, DataKind kind,
306            boolean includeSecondary, int exactValue) {
307        // Shortcut when no types
308        if (kind.typeColumn == null) return null;
309
310        // Find type counts and valid primary types, bail if none
311        final SparseIntArray typeCount = getTypeFrequencies(state, kind);
312        final ArrayList<EditType> validTypes = getValidTypes(state, kind, null, includeSecondary,
313                typeCount);
314        if (validTypes.size() == 0) return null;
315
316        // Keep track of the last valid type
317        final EditType lastType = validTypes.get(validTypes.size() - 1);
318
319        // Remove any types that already exist
320        Iterator<EditType> iterator = validTypes.iterator();
321        while (iterator.hasNext()) {
322            final EditType type = iterator.next();
323            final int count = typeCount.get(type.rawValue);
324
325            if (exactValue == type.rawValue) {
326                // Found exact value match
327                return type;
328            }
329
330            if (count > 0) {
331                // Type already appears, so don't consider
332                iterator.remove();
333            }
334        }
335
336        // Use the best remaining, otherwise the last valid
337        if (validTypes.size() > 0) {
338            return validTypes.get(0);
339        } else {
340            return lastType;
341        }
342    }
343
344    /**
345     * Insert a new child of kind {@link DataKind} into the given
346     * {@link RawContactDelta}. Tries using the best {@link EditType} found using
347     * {@link #getBestValidType(RawContactDelta, DataKind, boolean, int)}.
348     */
349    public static ValuesDelta insertChild(RawContactDelta state, DataKind kind) {
350        // First try finding a valid primary
351        EditType bestType = getBestValidType(state, kind, false, Integer.MIN_VALUE);
352        if (bestType == null) {
353            // No valid primary found, so expand search to secondary
354            bestType = getBestValidType(state, kind, true, Integer.MIN_VALUE);
355        }
356        return insertChild(state, kind, bestType);
357    }
358
359    /**
360     * Insert a new child of kind {@link DataKind} into the given
361     * {@link RawContactDelta}, marked with the given {@link EditType}.
362     */
363    public static ValuesDelta insertChild(RawContactDelta state, DataKind kind, EditType type) {
364        // Bail early if invalid kind
365        if (kind == null) return null;
366        final ContentValues after = new ContentValues();
367
368        // Our parent CONTACT_ID is provided later
369        after.put(Data.MIMETYPE, kind.mimeType);
370
371        // Fill-in with any requested default values
372        if (kind.defaultValues != null) {
373            after.putAll(kind.defaultValues);
374        }
375
376        if (kind.typeColumn != null && type != null) {
377            // Set type, if provided
378            after.put(kind.typeColumn, type.rawValue);
379        }
380
381        final ValuesDelta child = ValuesDelta.fromAfter(after);
382        state.addEntry(child);
383        return child;
384    }
385
386    /**
387     * Processing to trim any empty {@link ValuesDelta} and {@link RawContactDelta}
388     * from the given {@link RawContactDeltaList}, assuming the given {@link AccountTypeManager}
389     * dictates the structure for various fields. This method ignores rows not
390     * described by the {@link AccountType}.
391     */
392    public static void trimEmpty(RawContactDeltaList set, AccountTypeManager accountTypes) {
393        for (RawContactDelta state : set) {
394            ValuesDelta values = state.getValues();
395            final String accountType = values.getAsString(RawContacts.ACCOUNT_TYPE);
396            final String dataSet = values.getAsString(RawContacts.DATA_SET);
397            final AccountType type = accountTypes.getAccountType(accountType, dataSet);
398            trimEmpty(state, type);
399        }
400    }
401
402    public static boolean hasChanges(RawContactDeltaList set, AccountTypeManager accountTypes) {
403        if (set.isMarkedForSplitting() || set.isMarkedForJoining()) {
404            return true;
405        }
406
407        for (RawContactDelta state : set) {
408            ValuesDelta values = state.getValues();
409            final String accountType = values.getAsString(RawContacts.ACCOUNT_TYPE);
410            final String dataSet = values.getAsString(RawContacts.DATA_SET);
411            final AccountType type = accountTypes.getAccountType(accountType, dataSet);
412            if (hasChanges(state, type)) {
413                return true;
414            }
415        }
416        return false;
417    }
418
419    /**
420     * Processing to trim any empty {@link ValuesDelta} rows from the given
421     * {@link RawContactDelta}, assuming the given {@link AccountType} dictates
422     * the structure for various fields. This method ignores rows not described
423     * by the {@link AccountType}.
424     */
425    public static void trimEmpty(RawContactDelta state, AccountType accountType) {
426        boolean hasValues = false;
427
428        // Walk through entries for each well-known kind
429        for (DataKind kind : accountType.getSortedDataKinds()) {
430            final String mimeType = kind.mimeType;
431            final ArrayList<ValuesDelta> entries = state.getMimeEntries(mimeType);
432            if (entries == null) continue;
433
434            for (ValuesDelta entry : entries) {
435                // Skip any values that haven't been touched
436                final boolean touched = entry.isInsert() || entry.isUpdate();
437                if (!touched) {
438                    hasValues = true;
439                    continue;
440                }
441
442                // Test and remove this row if empty and it isn't a photo from google
443                final boolean isGoogleAccount = TextUtils.equals(GoogleAccountType.ACCOUNT_TYPE,
444                        state.getValues().getAsString(RawContacts.ACCOUNT_TYPE));
445                final boolean isPhoto = TextUtils.equals(Photo.CONTENT_ITEM_TYPE, kind.mimeType);
446                final boolean isGooglePhoto = isPhoto && isGoogleAccount;
447
448                if (RawContactModifier.isEmpty(entry, kind) && !isGooglePhoto) {
449                    if (DEBUG) {
450                        Log.v(TAG, "Trimming: " + entry.toString());
451                    }
452                    entry.markDeleted();
453                } else if (!entry.isFromTemplate()) {
454                    hasValues = true;
455                }
456            }
457        }
458        if (!hasValues) {
459            // Trim overall entity if no children exist
460            state.markDeleted();
461        }
462    }
463
464    private static boolean hasChanges(RawContactDelta state, AccountType accountType) {
465        for (DataKind kind : accountType.getSortedDataKinds()) {
466            final String mimeType = kind.mimeType;
467            final ArrayList<ValuesDelta> entries = state.getMimeEntries(mimeType);
468            if (entries == null) continue;
469
470            for (ValuesDelta entry : entries) {
471                // An empty Insert must be ignored, because it won't save anything (an example
472                // is an empty name that stays empty)
473                final boolean isRealInsert = entry.isInsert() && !isEmpty(entry, kind);
474                if (isRealInsert || entry.isUpdate() || entry.isDelete()) {
475                    return true;
476                }
477            }
478        }
479        return false;
480    }
481
482    /**
483     * Test if the given {@link ValuesDelta} would be considered "empty" in
484     * terms of {@link DataKind#fieldList}.
485     */
486    public static boolean isEmpty(ValuesDelta values, DataKind kind) {
487        if (Photo.CONTENT_ITEM_TYPE.equals(kind.mimeType)) {
488            return values.isInsert() && values.getAsByteArray(Photo.PHOTO) == null;
489        }
490
491        // No defined fields mean this row is always empty
492        if (kind.fieldList == null) return true;
493
494        for (EditField field : kind.fieldList) {
495            // If any field has values, we're not empty
496            final String value = values.getAsString(field.column);
497            if (ContactsUtils.isGraphic(value)) {
498                return false;
499            }
500        }
501
502        return true;
503    }
504
505    /**
506     * Compares corresponding fields in values1 and values2. Only the fields
507     * declared by the DataKind are taken into consideration.
508     */
509    protected static boolean areEqual(ValuesDelta values1, ContentValues values2, DataKind kind) {
510        if (kind.fieldList == null) return false;
511
512        for (EditField field : kind.fieldList) {
513            final String value1 = values1.getAsString(field.column);
514            final String value2 = values2.getAsString(field.column);
515            if (!TextUtils.equals(value1, value2)) {
516                return false;
517            }
518        }
519
520        return true;
521    }
522
523    /**
524     * Parse the given {@link Bundle} into the given {@link RawContactDelta} state,
525     * assuming the extras defined through {@link Intents}.
526     */
527    public static void parseExtras(Context context, AccountType accountType, RawContactDelta state,
528            Bundle extras) {
529        if (extras == null || extras.size() == 0) {
530            // Bail early if no useful data
531            return;
532        }
533
534        parseStructuredNameExtra(context, accountType, state, extras);
535        parseStructuredPostalExtra(accountType, state, extras);
536
537        {
538            // Phone
539            final DataKind kind = accountType.getKindForMimetype(Phone.CONTENT_ITEM_TYPE);
540            parseExtras(state, kind, extras, Insert.PHONE_TYPE, Insert.PHONE, Phone.NUMBER);
541            parseExtras(state, kind, extras, Insert.SECONDARY_PHONE_TYPE, Insert.SECONDARY_PHONE,
542                    Phone.NUMBER);
543            parseExtras(state, kind, extras, Insert.TERTIARY_PHONE_TYPE, Insert.TERTIARY_PHONE,
544                    Phone.NUMBER);
545        }
546
547        {
548            // Email
549            final DataKind kind = accountType.getKindForMimetype(Email.CONTENT_ITEM_TYPE);
550            parseExtras(state, kind, extras, Insert.EMAIL_TYPE, Insert.EMAIL, Email.DATA);
551            parseExtras(state, kind, extras, Insert.SECONDARY_EMAIL_TYPE, Insert.SECONDARY_EMAIL,
552                    Email.DATA);
553            parseExtras(state, kind, extras, Insert.TERTIARY_EMAIL_TYPE, Insert.TERTIARY_EMAIL,
554                    Email.DATA);
555        }
556
557        {
558            // Im
559            final DataKind kind = accountType.getKindForMimetype(Im.CONTENT_ITEM_TYPE);
560            fixupLegacyImType(extras);
561            parseExtras(state, kind, extras, Insert.IM_PROTOCOL, Insert.IM_HANDLE, Im.DATA);
562        }
563
564        // Organization
565        final boolean hasOrg = extras.containsKey(Insert.COMPANY)
566                || extras.containsKey(Insert.JOB_TITLE);
567        final DataKind kindOrg = accountType.getKindForMimetype(Organization.CONTENT_ITEM_TYPE);
568        if (hasOrg && RawContactModifier.canInsert(state, kindOrg)) {
569            final ValuesDelta child = RawContactModifier.insertChild(state, kindOrg);
570
571            final String company = extras.getString(Insert.COMPANY);
572            if (ContactsUtils.isGraphic(company)) {
573                child.put(Organization.COMPANY, company);
574            }
575
576            final String title = extras.getString(Insert.JOB_TITLE);
577            if (ContactsUtils.isGraphic(title)) {
578                child.put(Organization.TITLE, title);
579            }
580        }
581
582        // Notes
583        final boolean hasNotes = extras.containsKey(Insert.NOTES);
584        final DataKind kindNotes = accountType.getKindForMimetype(Note.CONTENT_ITEM_TYPE);
585        if (hasNotes && RawContactModifier.canInsert(state, kindNotes)) {
586            final ValuesDelta child = RawContactModifier.insertChild(state, kindNotes);
587
588            final String notes = extras.getString(Insert.NOTES);
589            if (ContactsUtils.isGraphic(notes)) {
590                child.put(Note.NOTE, notes);
591            }
592        }
593
594        // Arbitrary additional data
595        ArrayList<ContentValues> values = extras.getParcelableArrayList(Insert.DATA);
596        if (values != null) {
597            parseValues(state, accountType, values);
598        }
599    }
600
601    private static void parseStructuredNameExtra(
602            Context context, AccountType accountType, RawContactDelta state, Bundle extras) {
603        // StructuredName
604        RawContactModifier.ensureKindExists(state, accountType, StructuredName.CONTENT_ITEM_TYPE);
605        final ValuesDelta child = state.getPrimaryEntry(StructuredName.CONTENT_ITEM_TYPE);
606
607        final String name = extras.getString(Insert.NAME);
608        if (ContactsUtils.isGraphic(name)) {
609            final DataKind kind = accountType.getKindForMimetype(StructuredName.CONTENT_ITEM_TYPE);
610            boolean supportsDisplayName = false;
611            if (kind.fieldList != null) {
612                for (EditField field : kind.fieldList) {
613                    if (StructuredName.DISPLAY_NAME.equals(field.column)) {
614                        supportsDisplayName = true;
615                        break;
616                    }
617                }
618            }
619
620            if (supportsDisplayName) {
621                child.put(StructuredName.DISPLAY_NAME, name);
622            } else {
623                Uri uri = ContactsContract.AUTHORITY_URI.buildUpon()
624                        .appendPath("complete_name")
625                        .appendQueryParameter(StructuredName.DISPLAY_NAME, name)
626                        .build();
627                Cursor cursor = context.getContentResolver().query(uri,
628                        new String[]{
629                                StructuredName.PREFIX,
630                                StructuredName.GIVEN_NAME,
631                                StructuredName.MIDDLE_NAME,
632                                StructuredName.FAMILY_NAME,
633                                StructuredName.SUFFIX,
634                        }, null, null, null);
635
636                try {
637                    if (cursor.moveToFirst()) {
638                        child.put(StructuredName.PREFIX, cursor.getString(0));
639                        child.put(StructuredName.GIVEN_NAME, cursor.getString(1));
640                        child.put(StructuredName.MIDDLE_NAME, cursor.getString(2));
641                        child.put(StructuredName.FAMILY_NAME, cursor.getString(3));
642                        child.put(StructuredName.SUFFIX, cursor.getString(4));
643                    }
644                } finally {
645                    cursor.close();
646                }
647            }
648        }
649
650        final String phoneticName = extras.getString(Insert.PHONETIC_NAME);
651        if (ContactsUtils.isGraphic(phoneticName)) {
652            child.put(StructuredName.PHONETIC_GIVEN_NAME, phoneticName);
653        }
654    }
655
656    private static void parseStructuredPostalExtra(
657            AccountType accountType, RawContactDelta state, Bundle extras) {
658        // StructuredPostal
659        final DataKind kind = accountType.getKindForMimetype(StructuredPostal.CONTENT_ITEM_TYPE);
660        final ValuesDelta child = parseExtras(state, kind, extras, Insert.POSTAL_TYPE,
661                Insert.POSTAL, StructuredPostal.FORMATTED_ADDRESS);
662        String address = child == null ? null
663                : child.getAsString(StructuredPostal.FORMATTED_ADDRESS);
664        if (!TextUtils.isEmpty(address)) {
665            boolean supportsFormatted = false;
666            if (kind.fieldList != null) {
667                for (EditField field : kind.fieldList) {
668                    if (StructuredPostal.FORMATTED_ADDRESS.equals(field.column)) {
669                        supportsFormatted = true;
670                        break;
671                    }
672                }
673            }
674
675            if (!supportsFormatted) {
676                child.put(StructuredPostal.STREET, address);
677                child.putNull(StructuredPostal.FORMATTED_ADDRESS);
678            }
679        }
680    }
681
682    private static void parseValues(
683            RawContactDelta state, AccountType accountType,
684            ArrayList<ContentValues> dataValueList) {
685        for (ContentValues values : dataValueList) {
686            String mimeType = values.getAsString(Data.MIMETYPE);
687            if (TextUtils.isEmpty(mimeType)) {
688                Log.e(TAG, "Mimetype is required. Ignoring: " + values);
689                continue;
690            }
691
692            // Won't override the contact name
693            if (StructuredName.CONTENT_ITEM_TYPE.equals(mimeType)) {
694                continue;
695            }
696
697            DataKind kind = accountType.getKindForMimetype(mimeType);
698            if (kind == null) {
699                Log.e(TAG, "Mimetype not supported for account type "
700                        + accountType.getAccountTypeAndDataSet() + ". Ignoring: " + values);
701                continue;
702            }
703
704            ValuesDelta entry = ValuesDelta.fromAfter(values);
705            if (isEmpty(entry, kind)) {
706                continue;
707            }
708
709            ArrayList<ValuesDelta> entries = state.getMimeEntries(mimeType);
710
711            if ((kind.typeOverallMax != 1) || GroupMembership.CONTENT_ITEM_TYPE.equals(mimeType)) {
712                // Check for duplicates
713                boolean addEntry = true;
714                int count = 0;
715                if (entries != null && entries.size() > 0) {
716                    for (ValuesDelta delta : entries) {
717                        if (!delta.isDelete()) {
718                            if (areEqual(delta, values, kind)) {
719                                addEntry = false;
720                                break;
721                            }
722                            count++;
723                        }
724                    }
725                }
726
727                if (kind.typeOverallMax != -1 && count >= kind.typeOverallMax) {
728                    Log.e(TAG, "Mimetype allows at most " + kind.typeOverallMax
729                            + " entries. Ignoring: " + values);
730                    addEntry = false;
731                }
732
733                if (addEntry) {
734                    addEntry = adjustType(entry, entries, kind);
735                }
736
737                if (addEntry) {
738                    state.addEntry(entry);
739                }
740            } else {
741                // Non-list entries should not be overridden
742                boolean addEntry = true;
743                if (entries != null && entries.size() > 0) {
744                    for (ValuesDelta delta : entries) {
745                        if (!delta.isDelete() && !isEmpty(delta, kind)) {
746                            addEntry = false;
747                            break;
748                        }
749                    }
750                    if (addEntry) {
751                        for (ValuesDelta delta : entries) {
752                            delta.markDeleted();
753                        }
754                    }
755                }
756
757                if (addEntry) {
758                    addEntry = adjustType(entry, entries, kind);
759                }
760
761                if (addEntry) {
762                    state.addEntry(entry);
763                } else if (Note.CONTENT_ITEM_TYPE.equals(mimeType)){
764                    // Note is most likely to contain large amounts of text
765                    // that we don't want to drop on the ground.
766                    for (ValuesDelta delta : entries) {
767                        if (!isEmpty(delta, kind)) {
768                            delta.put(Note.NOTE, delta.getAsString(Note.NOTE) + "\n"
769                                    + values.getAsString(Note.NOTE));
770                            break;
771                        }
772                    }
773                } else {
774                    Log.e(TAG, "Will not override mimetype " + mimeType + ". Ignoring: "
775                            + values);
776                }
777            }
778        }
779    }
780
781    /**
782     * Checks if the data kind allows addition of another entry (e.g. Exchange only
783     * supports two "work" phone numbers).  If not, tries to switch to one of the
784     * unused types.  If successful, returns true.
785     */
786    private static boolean adjustType(
787            ValuesDelta entry, ArrayList<ValuesDelta> entries, DataKind kind) {
788        if (kind.typeColumn == null || kind.typeList == null || kind.typeList.size() == 0) {
789            return true;
790        }
791
792        Integer typeInteger = entry.getAsInteger(kind.typeColumn);
793        int type = typeInteger != null ? typeInteger : kind.typeList.get(0).rawValue;
794
795        if (isTypeAllowed(type, entries, kind)) {
796            entry.put(kind.typeColumn, type);
797            return true;
798        }
799
800        // Specified type is not allowed - choose the first available type that is allowed
801        int size = kind.typeList.size();
802        for (int i = 0; i < size; i++) {
803            EditType editType = kind.typeList.get(i);
804            if (isTypeAllowed(editType.rawValue, entries, kind)) {
805                entry.put(kind.typeColumn, editType.rawValue);
806                return true;
807            }
808        }
809
810        return false;
811    }
812
813    /**
814     * Checks if a new entry of the specified type can be added to the raw
815     * contact. For example, Exchange only supports two "work" phone numbers, so
816     * addition of a third would not be allowed.
817     */
818    private static boolean isTypeAllowed(int type, ArrayList<ValuesDelta> entries, DataKind kind) {
819        int max = 0;
820        int size = kind.typeList.size();
821        for (int i = 0; i < size; i++) {
822            EditType editType = kind.typeList.get(i);
823            if (editType.rawValue == type) {
824                max = editType.specificMax;
825                break;
826            }
827        }
828
829        if (max == 0) {
830            // This type is not allowed at all
831            return false;
832        }
833
834        if (max == -1) {
835            // Unlimited instances of this type are allowed
836            return true;
837        }
838
839        return getEntryCountByType(entries, kind.typeColumn, type) < max;
840    }
841
842    /**
843     * Counts occurrences of the specified type in the supplied entry list.
844     *
845     * @return The count of occurrences of the type in the entry list. 0 if entries is
846     * {@literal null}
847     */
848    private static int getEntryCountByType(ArrayList<ValuesDelta> entries, String typeColumn,
849            int type) {
850        int count = 0;
851        if (entries != null) {
852            for (ValuesDelta entry : entries) {
853                Integer typeInteger = entry.getAsInteger(typeColumn);
854                if (typeInteger != null && typeInteger == type) {
855                    count++;
856                }
857            }
858        }
859        return count;
860    }
861
862    /**
863     * Attempt to parse legacy {@link Insert#IM_PROTOCOL} values, replacing them
864     * with updated values.
865     */
866    @SuppressWarnings("deprecation")
867    private static void fixupLegacyImType(Bundle bundle) {
868        final String encodedString = bundle.getString(Insert.IM_PROTOCOL);
869        if (encodedString == null) return;
870
871        try {
872            final Object protocol = android.provider.Contacts.ContactMethods
873                    .decodeImProtocol(encodedString);
874            if (protocol instanceof Integer) {
875                bundle.putInt(Insert.IM_PROTOCOL, (Integer)protocol);
876            } else {
877                bundle.putString(Insert.IM_PROTOCOL, (String)protocol);
878            }
879        } catch (IllegalArgumentException e) {
880            // Ignore exception when legacy parser fails
881        }
882    }
883
884    /**
885     * Parse a specific entry from the given {@link Bundle} and insert into the
886     * given {@link RawContactDelta}. Silently skips the insert when missing value
887     * or no valid {@link EditType} found.
888     *
889     * @param typeExtra {@link Bundle} key that holds the incoming
890     *            {@link EditType#rawValue} value.
891     * @param valueExtra {@link Bundle} key that holds the incoming value.
892     * @param valueColumn Column to write value into {@link ValuesDelta}.
893     */
894    public static ValuesDelta parseExtras(RawContactDelta state, DataKind kind, Bundle extras,
895            String typeExtra, String valueExtra, String valueColumn) {
896        final CharSequence value = extras.getCharSequence(valueExtra);
897
898        // Bail early if account type doesn't handle this MIME type
899        if (kind == null) return null;
900
901        // Bail when can't insert type, or value missing
902        final boolean canInsert = RawContactModifier.canInsert(state, kind);
903        final boolean validValue = (value != null && TextUtils.isGraphic(value));
904        if (!validValue || !canInsert) return null;
905
906        // Find exact type when requested, otherwise best available type
907        final boolean hasType = extras.containsKey(typeExtra);
908        final int typeValue = extras.getInt(typeExtra, hasType ? BaseTypes.TYPE_CUSTOM
909                : Integer.MIN_VALUE);
910        final EditType editType = RawContactModifier.getBestValidType(state, kind, true, typeValue);
911
912        // Create data row and fill with value
913        final ValuesDelta child = RawContactModifier.insertChild(state, kind, editType);
914        child.put(valueColumn, value.toString());
915
916        if (editType != null && editType.customColumn != null) {
917            // Write down label when custom type picked
918            final String customType = extras.getString(typeExtra);
919            child.put(editType.customColumn, customType);
920        }
921
922        return child;
923    }
924
925    /**
926     * Generic mime types with type support (e.g. TYPE_HOME).
927     * Here, "type support" means if the data kind has CommonColumns#TYPE or not. Data kinds which
928     * have their own migrate methods aren't listed here.
929     */
930    private static final Set<String> sGenericMimeTypesWithTypeSupport = new HashSet<String>(
931            Arrays.asList(Phone.CONTENT_ITEM_TYPE,
932                    Email.CONTENT_ITEM_TYPE,
933                    Im.CONTENT_ITEM_TYPE,
934                    Nickname.CONTENT_ITEM_TYPE,
935                    Website.CONTENT_ITEM_TYPE,
936                    Relation.CONTENT_ITEM_TYPE,
937                    SipAddress.CONTENT_ITEM_TYPE));
938    private static final Set<String> sGenericMimeTypesWithoutTypeSupport = new HashSet<String>(
939            Arrays.asList(Organization.CONTENT_ITEM_TYPE,
940                    Note.CONTENT_ITEM_TYPE,
941                    Photo.CONTENT_ITEM_TYPE,
942                    GroupMembership.CONTENT_ITEM_TYPE));
943    // CommonColumns.TYPE cannot be accessed as it is protected interface, so use
944    // Phone.TYPE instead.
945    private static final String COLUMN_FOR_TYPE  = Phone.TYPE;
946    private static final String COLUMN_FOR_LABEL  = Phone.LABEL;
947    private static final int TYPE_CUSTOM = Phone.TYPE_CUSTOM;
948
949    /**
950     * Migrates old RawContactDelta to newly created one with a new restriction supplied from
951     * newAccountType.
952     *
953     * This is only for account switch during account creation (which must be insert operation).
954     */
955    public static void migrateStateForNewContact(Context context,
956            RawContactDelta oldState, RawContactDelta newState,
957            AccountType oldAccountType, AccountType newAccountType) {
958        if (newAccountType == oldAccountType) {
959            // Just copying all data in oldState isn't enough, but we can still rely on a lot of
960            // shortcuts.
961            for (DataKind kind : newAccountType.getSortedDataKinds()) {
962                final String mimeType = kind.mimeType;
963                // The fields with short/long form capability must be treated properly.
964                if (StructuredName.CONTENT_ITEM_TYPE.equals(mimeType)) {
965                    migrateStructuredName(context, oldState, newState, kind);
966                } else {
967                    List<ValuesDelta> entryList = oldState.getMimeEntries(mimeType);
968                    if (entryList != null && !entryList.isEmpty()) {
969                        for (ValuesDelta entry : entryList) {
970                            ContentValues values = entry.getAfter();
971                            if (values != null) {
972                                newState.addEntry(ValuesDelta.fromAfter(values));
973                            }
974                        }
975                    }
976                }
977            }
978        } else {
979            // Migrate data supported by the new account type.
980            // All the other data inside oldState are silently dropped.
981            for (DataKind kind : newAccountType.getSortedDataKinds()) {
982                if (!kind.editable) continue;
983                final String mimeType = kind.mimeType;
984                if (DataKind.PSEUDO_MIME_TYPE_DISPLAY_NAME.equals(mimeType)
985                        || DataKind.PSEUDO_MIME_TYPE_PHONETIC_NAME.equals(mimeType)) {
986                    // Ignore pseudo data.
987                    continue;
988                } else if (StructuredName.CONTENT_ITEM_TYPE.equals(mimeType)) {
989                    migrateStructuredName(context, oldState, newState, kind);
990                } else if (StructuredPostal.CONTENT_ITEM_TYPE.equals(mimeType)) {
991                    migratePostal(oldState, newState, kind);
992                } else if (Event.CONTENT_ITEM_TYPE.equals(mimeType)) {
993                    migrateEvent(oldState, newState, kind, null /* default Year */);
994                } else if (sGenericMimeTypesWithoutTypeSupport.contains(mimeType)) {
995                    migrateGenericWithoutTypeColumn(oldState, newState, kind);
996                } else if (sGenericMimeTypesWithTypeSupport.contains(mimeType)) {
997                    migrateGenericWithTypeColumn(oldState, newState, kind);
998                } else {
999                    throw new IllegalStateException("Unexpected editable mime-type: " + mimeType);
1000                }
1001            }
1002        }
1003    }
1004
1005    /**
1006     * Checks {@link DataKind#isList} and {@link DataKind#typeOverallMax}, and restricts
1007     * the number of entries (ValuesDelta) inside newState.
1008     */
1009    private static ArrayList<ValuesDelta> ensureEntryMaxSize(RawContactDelta newState,
1010            DataKind kind, ArrayList<ValuesDelta> mimeEntries) {
1011        if (mimeEntries == null) {
1012            return null;
1013        }
1014
1015        final int typeOverallMax = kind.typeOverallMax;
1016        if (typeOverallMax >= 0 && (mimeEntries.size() > typeOverallMax)) {
1017            ArrayList<ValuesDelta> newMimeEntries = new ArrayList<ValuesDelta>(typeOverallMax);
1018            for (int i = 0; i < typeOverallMax; i++) {
1019                newMimeEntries.add(mimeEntries.get(i));
1020            }
1021            mimeEntries = newMimeEntries;
1022        }
1023        return mimeEntries;
1024    }
1025
1026    /** @hide Public only for testing. */
1027    public static void migrateStructuredName(
1028            Context context, RawContactDelta oldState, RawContactDelta newState,
1029            DataKind newDataKind) {
1030        final ContentValues values =
1031                oldState.getPrimaryEntry(StructuredName.CONTENT_ITEM_TYPE).getAfter();
1032        if (values == null) {
1033            return;
1034        }
1035
1036        boolean supportDisplayName = false;
1037        boolean supportPhoneticFullName = false;
1038        boolean supportPhoneticFamilyName = false;
1039        boolean supportPhoneticMiddleName = false;
1040        boolean supportPhoneticGivenName = false;
1041        for (EditField editField : newDataKind.fieldList) {
1042            if (StructuredName.DISPLAY_NAME.equals(editField.column)) {
1043                supportDisplayName = true;
1044            }
1045            if (DataKind.PSEUDO_COLUMN_PHONETIC_NAME.equals(editField.column)) {
1046                supportPhoneticFullName = true;
1047            }
1048            if (StructuredName.PHONETIC_FAMILY_NAME.equals(editField.column)) {
1049                supportPhoneticFamilyName = true;
1050            }
1051            if (StructuredName.PHONETIC_MIDDLE_NAME.equals(editField.column)) {
1052                supportPhoneticMiddleName = true;
1053            }
1054            if (StructuredName.PHONETIC_GIVEN_NAME.equals(editField.column)) {
1055                supportPhoneticGivenName = true;
1056            }
1057        }
1058
1059        // DISPLAY_NAME <-> PREFIX, GIVEN_NAME, MIDDLE_NAME, FAMILY_NAME, SUFFIX
1060        final String displayName = values.getAsString(StructuredName.DISPLAY_NAME);
1061        if (!TextUtils.isEmpty(displayName)) {
1062            if (!supportDisplayName) {
1063                // Old data has a display name, while the new account doesn't allow it.
1064                NameConverter.displayNameToStructuredName(context, displayName, values);
1065
1066                // We don't want to migrate unseen data which may confuse users after the creation.
1067                values.remove(StructuredName.DISPLAY_NAME);
1068            }
1069        } else {
1070            if (supportDisplayName) {
1071                // Old data does not have display name, while the new account requires it.
1072                values.put(StructuredName.DISPLAY_NAME,
1073                        NameConverter.structuredNameToDisplayName(context, values));
1074                for (String field : NameConverter.STRUCTURED_NAME_FIELDS) {
1075                    values.remove(field);
1076                }
1077            }
1078        }
1079
1080        // Phonetic (full) name <-> PHONETIC_FAMILY_NAME, PHONETIC_MIDDLE_NAME, PHONETIC_GIVEN_NAME
1081        final String phoneticFullName = values.getAsString(DataKind.PSEUDO_COLUMN_PHONETIC_NAME);
1082        if (!TextUtils.isEmpty(phoneticFullName)) {
1083            if (!supportPhoneticFullName) {
1084                // Old data has a phonetic (full) name, while the new account doesn't allow it.
1085                final StructuredNameDataItem tmpItem =
1086                        PhoneticNameEditorView.parsePhoneticName(phoneticFullName, null);
1087                values.remove(DataKind.PSEUDO_COLUMN_PHONETIC_NAME);
1088                if (supportPhoneticFamilyName) {
1089                    values.put(StructuredName.PHONETIC_FAMILY_NAME,
1090                            tmpItem.getPhoneticFamilyName());
1091                } else {
1092                    values.remove(StructuredName.PHONETIC_FAMILY_NAME);
1093                }
1094                if (supportPhoneticMiddleName) {
1095                    values.put(StructuredName.PHONETIC_MIDDLE_NAME,
1096                            tmpItem.getPhoneticMiddleName());
1097                } else {
1098                    values.remove(StructuredName.PHONETIC_MIDDLE_NAME);
1099                }
1100                if (supportPhoneticGivenName) {
1101                    values.put(StructuredName.PHONETIC_GIVEN_NAME,
1102                            tmpItem.getPhoneticGivenName());
1103                } else {
1104                    values.remove(StructuredName.PHONETIC_GIVEN_NAME);
1105                }
1106            }
1107        } else {
1108            if (supportPhoneticFullName) {
1109                // Old data does not have a phonetic (full) name, while the new account requires it.
1110                values.put(DataKind.PSEUDO_COLUMN_PHONETIC_NAME,
1111                        PhoneticNameEditorView.buildPhoneticName(
1112                                values.getAsString(StructuredName.PHONETIC_FAMILY_NAME),
1113                                values.getAsString(StructuredName.PHONETIC_MIDDLE_NAME),
1114                                values.getAsString(StructuredName.PHONETIC_GIVEN_NAME)));
1115            }
1116            if (!supportPhoneticFamilyName) {
1117                values.remove(StructuredName.PHONETIC_FAMILY_NAME);
1118            }
1119            if (!supportPhoneticMiddleName) {
1120                values.remove(StructuredName.PHONETIC_MIDDLE_NAME);
1121            }
1122            if (!supportPhoneticGivenName) {
1123                values.remove(StructuredName.PHONETIC_GIVEN_NAME);
1124            }
1125        }
1126
1127        newState.addEntry(ValuesDelta.fromAfter(values));
1128    }
1129
1130    /** @hide Public only for testing. */
1131    public static void migratePostal(RawContactDelta oldState, RawContactDelta newState,
1132            DataKind newDataKind) {
1133        final ArrayList<ValuesDelta> mimeEntries = ensureEntryMaxSize(newState, newDataKind,
1134                oldState.getMimeEntries(StructuredPostal.CONTENT_ITEM_TYPE));
1135        if (mimeEntries == null || mimeEntries.isEmpty()) {
1136            return;
1137        }
1138
1139        boolean supportFormattedAddress = false;
1140        boolean supportStreet = false;
1141        final String firstColumn = newDataKind.fieldList.get(0).column;
1142        for (EditField editField : newDataKind.fieldList) {
1143            if (StructuredPostal.FORMATTED_ADDRESS.equals(editField.column)) {
1144                supportFormattedAddress = true;
1145            }
1146            if (StructuredPostal.STREET.equals(editField.column)) {
1147                supportStreet = true;
1148            }
1149        }
1150
1151        final Set<Integer> supportedTypes = new HashSet<Integer>();
1152        if (newDataKind.typeList != null && !newDataKind.typeList.isEmpty()) {
1153            for (EditType editType : newDataKind.typeList) {
1154                supportedTypes.add(editType.rawValue);
1155            }
1156        }
1157
1158        for (ValuesDelta entry : mimeEntries) {
1159            final ContentValues values = entry.getAfter();
1160            if (values == null) {
1161                continue;
1162            }
1163            final Integer oldType = values.getAsInteger(StructuredPostal.TYPE);
1164            if (!supportedTypes.contains(oldType)) {
1165                int defaultType;
1166                if (newDataKind.defaultValues != null) {
1167                    defaultType = newDataKind.defaultValues.getAsInteger(StructuredPostal.TYPE);
1168                } else {
1169                    defaultType = newDataKind.typeList.get(0).rawValue;
1170                }
1171                values.put(StructuredPostal.TYPE, defaultType);
1172                if (oldType != null && oldType == StructuredPostal.TYPE_CUSTOM) {
1173                    values.remove(StructuredPostal.LABEL);
1174                }
1175            }
1176
1177            final String formattedAddress = values.getAsString(StructuredPostal.FORMATTED_ADDRESS);
1178            if (!TextUtils.isEmpty(formattedAddress)) {
1179                if (!supportFormattedAddress) {
1180                    // Old data has a formatted address, while the new account doesn't allow it.
1181                    values.remove(StructuredPostal.FORMATTED_ADDRESS);
1182
1183                    // Unlike StructuredName we don't have logic to split it, so first
1184                    // try to use street field and. If the new account doesn't have one,
1185                    // then select first one anyway.
1186                    if (supportStreet) {
1187                        values.put(StructuredPostal.STREET, formattedAddress);
1188                    } else {
1189                        values.put(firstColumn, formattedAddress);
1190                    }
1191                }
1192            } else {
1193                if (supportFormattedAddress) {
1194                    // Old data does not have formatted address, while the new account requires it.
1195                    // Unlike StructuredName we don't have logic to join multiple address values.
1196                    // Use poor join heuristics for now.
1197                    String[] structuredData;
1198                    final boolean useJapaneseOrder =
1199                            Locale.JAPANESE.getLanguage().equals(Locale.getDefault().getLanguage());
1200                    if (useJapaneseOrder) {
1201                        structuredData = new String[] {
1202                                values.getAsString(StructuredPostal.COUNTRY),
1203                                values.getAsString(StructuredPostal.POSTCODE),
1204                                values.getAsString(StructuredPostal.REGION),
1205                                values.getAsString(StructuredPostal.CITY),
1206                                values.getAsString(StructuredPostal.NEIGHBORHOOD),
1207                                values.getAsString(StructuredPostal.STREET),
1208                                values.getAsString(StructuredPostal.POBOX) };
1209                    } else {
1210                        structuredData = new String[] {
1211                                values.getAsString(StructuredPostal.POBOX),
1212                                values.getAsString(StructuredPostal.STREET),
1213                                values.getAsString(StructuredPostal.NEIGHBORHOOD),
1214                                values.getAsString(StructuredPostal.CITY),
1215                                values.getAsString(StructuredPostal.REGION),
1216                                values.getAsString(StructuredPostal.POSTCODE),
1217                                values.getAsString(StructuredPostal.COUNTRY) };
1218                    }
1219                    final StringBuilder builder = new StringBuilder();
1220                    for (String elem : structuredData) {
1221                        if (!TextUtils.isEmpty(elem)) {
1222                            builder.append(elem + "\n");
1223                        }
1224                    }
1225                    values.put(StructuredPostal.FORMATTED_ADDRESS, builder.toString());
1226
1227                    values.remove(StructuredPostal.POBOX);
1228                    values.remove(StructuredPostal.STREET);
1229                    values.remove(StructuredPostal.NEIGHBORHOOD);
1230                    values.remove(StructuredPostal.CITY);
1231                    values.remove(StructuredPostal.REGION);
1232                    values.remove(StructuredPostal.POSTCODE);
1233                    values.remove(StructuredPostal.COUNTRY);
1234                }
1235            }
1236
1237            newState.addEntry(ValuesDelta.fromAfter(values));
1238        }
1239    }
1240
1241    /** @hide Public only for testing. */
1242    public static void migrateEvent(RawContactDelta oldState, RawContactDelta newState,
1243            DataKind newDataKind, Integer defaultYear) {
1244        final ArrayList<ValuesDelta> mimeEntries = ensureEntryMaxSize(newState, newDataKind,
1245                oldState.getMimeEntries(Event.CONTENT_ITEM_TYPE));
1246        if (mimeEntries == null || mimeEntries.isEmpty()) {
1247            return;
1248        }
1249
1250        final SparseArray<EventEditType> allowedTypes = new SparseArray<EventEditType>();
1251        for (EditType editType : newDataKind.typeList) {
1252            allowedTypes.put(editType.rawValue, (EventEditType) editType);
1253        }
1254        for (ValuesDelta entry : mimeEntries) {
1255            final ContentValues values = entry.getAfter();
1256            if (values == null) {
1257                continue;
1258            }
1259            final String dateString = values.getAsString(Event.START_DATE);
1260            final Integer type = values.getAsInteger(Event.TYPE);
1261            if (type != null && (allowedTypes.indexOfKey(type) >= 0)
1262                    && !TextUtils.isEmpty(dateString)) {
1263                EventEditType suitableType = allowedTypes.get(type);
1264
1265                final ParsePosition position = new ParsePosition(0);
1266                boolean yearOptional = false;
1267                Date date = CommonDateUtils.DATE_AND_TIME_FORMAT.parse(dateString, position);
1268                if (date == null) {
1269                    yearOptional = true;
1270                    date = CommonDateUtils.NO_YEAR_DATE_FORMAT.parse(dateString, position);
1271                }
1272                if (date != null) {
1273                    if (yearOptional && !suitableType.isYearOptional()) {
1274                        // The new EditType doesn't allow optional year. Supply default.
1275                        final Calendar calendar = Calendar.getInstance(DateUtils.UTC_TIMEZONE,
1276                                Locale.US);
1277                        if (defaultYear == null) {
1278                            defaultYear = calendar.get(Calendar.YEAR);
1279                        }
1280                        calendar.setTime(date);
1281                        final int month = calendar.get(Calendar.MONTH);
1282                        final int day = calendar.get(Calendar.DAY_OF_MONTH);
1283                        // Exchange requires 8:00 for birthdays
1284                        calendar.set(defaultYear, month, day,
1285                                EventFieldEditorView.getDefaultHourForBirthday(), 0, 0);
1286                        values.put(Event.START_DATE,
1287                                CommonDateUtils.FULL_DATE_FORMAT.format(calendar.getTime()));
1288                    }
1289                }
1290                newState.addEntry(ValuesDelta.fromAfter(values));
1291            } else {
1292                // Just drop it.
1293            }
1294        }
1295    }
1296
1297    /** @hide Public only for testing. */
1298    public static void migrateGenericWithoutTypeColumn(
1299            RawContactDelta oldState, RawContactDelta newState, DataKind newDataKind) {
1300        final ArrayList<ValuesDelta> mimeEntries = ensureEntryMaxSize(newState, newDataKind,
1301                oldState.getMimeEntries(newDataKind.mimeType));
1302        if (mimeEntries == null || mimeEntries.isEmpty()) {
1303            return;
1304        }
1305
1306        for (ValuesDelta entry : mimeEntries) {
1307            ContentValues values = entry.getAfter();
1308            if (values != null) {
1309                newState.addEntry(ValuesDelta.fromAfter(values));
1310            }
1311        }
1312    }
1313
1314    /** @hide Public only for testing. */
1315    public static void migrateGenericWithTypeColumn(
1316            RawContactDelta oldState, RawContactDelta newState, DataKind newDataKind) {
1317        final ArrayList<ValuesDelta> mimeEntries = oldState.getMimeEntries(newDataKind.mimeType);
1318        if (mimeEntries == null || mimeEntries.isEmpty()) {
1319            return;
1320        }
1321
1322        // Note that type specified with the old account may be invalid with the new account, while
1323        // we want to preserve its data as much as possible. e.g. if a user typed a phone number
1324        // with a type which is valid with an old account but not with a new account, the user
1325        // probably wants to have the number with default type, rather than seeing complete data
1326        // loss.
1327        //
1328        // Specifically, this method works as follows:
1329        // 1. detect defaultType
1330        // 2. prepare constants & variables for iteration
1331        // 3. iterate over mimeEntries:
1332        // 3.1 stop iteration if total number of mimeEntries reached typeOverallMax specified in
1333        //     DataKind
1334        // 3.2 replace unallowed types with defaultType
1335        // 3.3 check if the number of entries is below specificMax specified in AccountType
1336
1337        // Here, defaultType can be supplied in two ways
1338        // - via kind.defaultValues
1339        // - via kind.typeList.get(0).rawValue
1340        Integer defaultType = null;
1341        if (newDataKind.defaultValues != null) {
1342            defaultType = newDataKind.defaultValues.getAsInteger(COLUMN_FOR_TYPE);
1343        }
1344        final Set<Integer> allowedTypes = new HashSet<Integer>();
1345        // key: type, value: the number of entries allowed for the type (specificMax)
1346        final SparseIntArray typeSpecificMaxMap = new SparseIntArray();
1347        if (defaultType != null) {
1348            allowedTypes.add(defaultType);
1349            typeSpecificMaxMap.put(defaultType, -1);
1350        }
1351        // Note: typeList may be used in different purposes when defaultValues are specified.
1352        // Especially in IM, typeList contains available protocols (e.g. PROTOCOL_GOOGLE_TALK)
1353        // instead of "types" which we want to treate here (e.g. TYPE_HOME). So we don't add
1354        // anything other than defaultType into allowedTypes and typeSpecificMapMax.
1355        if (!Im.CONTENT_ITEM_TYPE.equals(newDataKind.mimeType) &&
1356                newDataKind.typeList != null && !newDataKind.typeList.isEmpty()) {
1357            for (EditType editType : newDataKind.typeList) {
1358                allowedTypes.add(editType.rawValue);
1359                typeSpecificMaxMap.put(editType.rawValue, editType.specificMax);
1360            }
1361            if (defaultType == null) {
1362                defaultType = newDataKind.typeList.get(0).rawValue;
1363            }
1364        }
1365
1366        if (defaultType == null) {
1367            Log.w(TAG, "Default type isn't available for mimetype " + newDataKind.mimeType);
1368        }
1369
1370        final int typeOverallMax = newDataKind.typeOverallMax;
1371
1372        // key: type, value: the number of current entries.
1373        final SparseIntArray currentEntryCount = new SparseIntArray();
1374        int totalCount = 0;
1375
1376        for (ValuesDelta entry : mimeEntries) {
1377            if (typeOverallMax != -1 && totalCount >= typeOverallMax) {
1378                break;
1379            }
1380
1381            final ContentValues values = entry.getAfter();
1382            if (values == null) {
1383                continue;
1384            }
1385
1386            final Integer oldType = entry.getAsInteger(COLUMN_FOR_TYPE);
1387            final Integer typeForNewAccount;
1388            if (!allowedTypes.contains(oldType)) {
1389                // The new account doesn't support the type.
1390                if (defaultType != null) {
1391                    typeForNewAccount = defaultType.intValue();
1392                    values.put(COLUMN_FOR_TYPE, defaultType.intValue());
1393                    if (oldType != null && oldType == TYPE_CUSTOM) {
1394                        values.remove(COLUMN_FOR_LABEL);
1395                    }
1396                } else {
1397                    typeForNewAccount = null;
1398                    values.remove(COLUMN_FOR_TYPE);
1399                }
1400            } else {
1401                typeForNewAccount = oldType;
1402            }
1403            if (typeForNewAccount != null) {
1404                final int specificMax = typeSpecificMaxMap.get(typeForNewAccount, 0);
1405                if (specificMax >= 0) {
1406                    final int currentCount = currentEntryCount.get(typeForNewAccount, 0);
1407                    if (currentCount >= specificMax) {
1408                        continue;
1409                    }
1410                    currentEntryCount.put(typeForNewAccount, currentCount + 1);
1411                }
1412            }
1413            newState.addEntry(ValuesDelta.fromAfter(values));
1414            totalCount++;
1415        }
1416    }
1417}
1418