Home | History | Annotate | Download | only in managedprofile
      1 /*
      2  * Copyright (C) 2015 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 
     17 package com.android.cts.managedprofile;
     18 
     19 import android.accounts.Account;
     20 import android.accounts.AccountManager;
     21 import android.annotation.TargetApi;
     22 import android.app.admin.DevicePolicyManager;
     23 import android.content.ContentProviderOperation;
     24 import android.content.ContentResolver;
     25 import android.content.Context;
     26 import android.content.OperationApplicationException;
     27 import android.content.res.Resources;
     28 import android.content.res.Resources.NotFoundException;
     29 import android.database.Cursor;
     30 import android.database.DatabaseUtils;
     31 import android.graphics.Rect;
     32 import android.net.Uri;
     33 import android.os.Build;
     34 import android.os.RemoteException;
     35 import android.provider.ContactsContract;
     36 import android.provider.ContactsContract.CommonDataKinds.Callable;
     37 import android.provider.ContactsContract.CommonDataKinds.Email;
     38 import android.provider.ContactsContract.CommonDataKinds.Phone;
     39 import android.provider.ContactsContract.CommonDataKinds.Photo;
     40 import android.provider.ContactsContract.Contacts;
     41 import android.provider.ContactsContract.Directory;
     42 import android.provider.ContactsContract.PhoneLookup;
     43 import android.provider.ContactsContract.RawContacts;
     44 import android.test.AndroidTestCase;
     45 import android.util.Log;
     46 
     47 import java.io.ByteArrayOutputStream;
     48 import java.io.FileNotFoundException;
     49 import java.io.IOException;
     50 import java.io.InputStream;
     51 import java.util.ArrayList;
     52 import java.util.Arrays;
     53 
     54 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
     55 public class ContactsTest extends AndroidTestCase {
     56 
     57     private static final String TAG = "ContactsTest";
     58 
     59     private static final String TEST_ACCOUNT_NAME = AccountAuthenticator.ACCOUNT_NAME;
     60     private static final String TEST_ACCOUNT_TYPE = AccountAuthenticator.ACCOUNT_TYPE;
     61     // details of a sample primary contact
     62     private static final String PRIMARY_CONTACT_DISPLAY_NAME = "Primary";
     63     private static final String PRIMARY_CONTACT_PHONE = "00000001";
     64     private static final String PRIMARY_CONTACT_EMAIL = "one (at) primary.com";
     65     private static final String PRIMARY_CONTACT_SIP = "foo@sip";
     66 
     67     // details of a sample managed contact
     68     private static final String MANAGED_CONTACT_DISPLAY_NAME = "Managed";
     69     private static final String MANAGED_CONTACT_PHONE = "6891999";
     70     private static final String MANAGED_CONTACT_EMAIL = "one (at) managed.com";
     71     private static final String MANAGED_CONTACT_SIP = "bar@sip";
     72 
     73     // details of a sample primary and a sample managed contact, with the same phone & email
     74     private static final String PRIMARY_CONTACT_DISPLAY_NAME_2 = "PrimaryShared";
     75     private static final String MANAGED_CONTACT_DISPLAY_NAME_2 = "ManagedShared";
     76     private static final String SHARED_CONTACT_PHONE = "00000002";
     77     private static final String SHARED_CONTACT_EMAIL = "shared (at) shared.com";
     78     private static final String SHARED_CONTACT_SIP = "baz@sip";
     79 
     80     // Directory display name
     81     private static final String PRIMARY_DIRECTORY_NAME = "PrimaryDirectory";
     82     private static final String MANAGED_DIRECTORY_NAME = "ManagedDirectory";
     83     private static final String PRIMARY_DIRECTORY_CONTACT_NAME = "PrimaryDirectoryContact";
     84     private static final String MANAGED_DIRECTORY_CONTACT_NAME = "ManagedDirectoryContact";
     85 
     86     // Directory Authority
     87     private static final String DIRECTORY_PROVIDER_AUTHORITY = "com.android.cts.contact.directory.provider";
     88 
     89 
     90     // Retry directory query so we can make sure directory info in cp2 is updated
     91     private static final int MAX_RETRY_DIRECTORY_QUERY = 10;
     92     private static final int RETRY_DIRECTORY_QUERY_INTERVAL = 1000; // 1s
     93 
     94     private DevicePolicyManager mDevicePolicyManager;
     95     private ContentResolver mResolver;
     96 
     97     private class ContactInfo { // Not static to access outer world.
     98 
     99         String contactId;
    100         String displayName;
    101         String photoUri;
    102         String photoThumbnailUri;
    103         String photoId;
    104 
    105         public ContactInfo(String contactId, String displayName, String photoUri,
    106                 String photoThumbnailUri, String photoId) {
    107             this.contactId = contactId;
    108             this.displayName = displayName;
    109             this.photoUri = photoUri;
    110             this.photoThumbnailUri = photoThumbnailUri;
    111             this.photoId = photoId;
    112         }
    113 
    114         private void assertNoPhotoUri() {
    115             assertNull(photoUri);
    116             assertNull(photoThumbnailUri);
    117         }
    118 
    119         private void assertPhotoUrisReadable() {
    120             assertPhotoUriReadable(photoUri);
    121             assertPhotoUriReadable(photoThumbnailUri);
    122         }
    123 
    124         private void assertThumbnailUri(int resId) {
    125             Resources resources = mContext.getResources();
    126             assertNotNull(this.photoThumbnailUri);
    127             byte[] actualPhotoThumbnail = getByteFromStreamForTest(
    128                     getInputStreamFromUriForTest(this.photoThumbnailUri));
    129             byte[] expectedPhotoThumbnail = getByteFromStreamForTest(
    130                     resources.openRawResource(resId));
    131             assertTrue(Arrays.equals(expectedPhotoThumbnail, actualPhotoThumbnail));
    132         }
    133 
    134         private void assertPhotoUri(int resId) {
    135             Resources resources = mContext.getResources();
    136             assertNotNull(this.photoUri);
    137             byte[] actualPhoto = getByteFromStreamForTest(
    138                     getInputStreamFromUriForTest(this.photoUri));
    139             byte[] expectedPhoto = getByteFromStreamForTest(
    140                     resources.openRawResource(resId));
    141             assertTrue(Arrays.equals(expectedPhoto, actualPhoto));
    142         }
    143 
    144         private boolean hasPhotoId() {
    145             return photoId != null && Long.parseLong(photoId) > 0;
    146         }
    147     }
    148 
    149     @Override
    150     protected void setUp() throws Exception {
    151         super.setUp();
    152         mResolver = getContext().getContentResolver();
    153         mDevicePolicyManager = (DevicePolicyManager) mContext
    154                 .getSystemService(Context.DEVICE_POLICY_SERVICE);
    155     }
    156 
    157     public void testAddTestAccount() {
    158         Account account = new Account(TEST_ACCOUNT_NAME, TEST_ACCOUNT_TYPE);
    159         AccountManager.get(getContext()).addAccountExplicitly(account, null, null);
    160     }
    161 
    162     public void testPrimaryProfilePhoneAndEmailLookup_insertedAndfound() throws RemoteException,
    163             OperationApplicationException, NotFoundException, IOException {
    164         assertFalse(isManagedProfile());
    165         // Do not insert to primary contact
    166         insertContact(PRIMARY_CONTACT_DISPLAY_NAME, PRIMARY_CONTACT_PHONE,
    167                 PRIMARY_CONTACT_EMAIL, PRIMARY_CONTACT_SIP, 0);
    168 
    169         ContactInfo contactInfo = getContactInfoFromPhoneLookupUri(false /*isEnterprise*/,
    170                 PRIMARY_CONTACT_PHONE);
    171         assertNotNull(contactInfo);
    172         assertEquals(PRIMARY_CONTACT_DISPLAY_NAME, contactInfo.displayName);
    173         contactInfo.assertNoPhotoUri();
    174         assertFalse(contactInfo.hasPhotoId());
    175         assertFalse(isEnterpriseContactId(contactInfo.contactId));
    176 
    177         contactInfo = getContactInfoFromEmailLookupUri(false /*isEnterprise*/,
    178                 PRIMARY_CONTACT_EMAIL);
    179         assertNotNull(contactInfo);
    180         assertEquals(PRIMARY_CONTACT_DISPLAY_NAME, contactInfo.displayName);
    181         contactInfo.assertNoPhotoUri();
    182         assertFalse(contactInfo.hasPhotoId());
    183         assertFalse(isEnterpriseContactId(contactInfo.contactId));
    184 
    185     }
    186 
    187     public void testManagedProfilePhoneAndEmailLookup_insertedAndfound() throws RemoteException,
    188             OperationApplicationException, NotFoundException, IOException {
    189         assertTrue(isManagedProfile());
    190         // Insert ic_contact_picture as photo in managed contact
    191         insertContact(MANAGED_CONTACT_DISPLAY_NAME,
    192                 MANAGED_CONTACT_PHONE,
    193                 MANAGED_CONTACT_EMAIL,
    194                 MANAGED_CONTACT_SIP,
    195                 com.android.cts.managedprofile.R.raw.ic_contact_picture);
    196 
    197         ContactInfo contactInfo = getContactInfoFromPhoneLookupUri(false /*isEnterprise*/,
    198                 MANAGED_CONTACT_PHONE);
    199         assertNotNull(contactInfo);
    200         assertEquals(MANAGED_CONTACT_DISPLAY_NAME, contactInfo.displayName);
    201         contactInfo.assertPhotoUrisReadable();
    202         assertTrue(contactInfo.hasPhotoId());
    203         assertFalse(isEnterpriseContactId(contactInfo.contactId));
    204 
    205         contactInfo = getContactInfoFromEmailLookupUri(false /*isEnterprise*/,
    206                 MANAGED_CONTACT_EMAIL);
    207         assertNotNull(contactInfo);
    208         assertEquals(MANAGED_CONTACT_DISPLAY_NAME, contactInfo.displayName);
    209         contactInfo.assertPhotoUrisReadable();
    210         assertTrue(contactInfo.hasPhotoId());
    211         assertFalse(isEnterpriseContactId(contactInfo.contactId));
    212     }
    213 
    214     public void testPrimaryProfileDuplicatedPhoneEmailContact_insertedAndfound() throws
    215             RemoteException, OperationApplicationException, NotFoundException, IOException {
    216         assertFalse(isManagedProfile());
    217         insertContact(PRIMARY_CONTACT_DISPLAY_NAME_2,
    218                 SHARED_CONTACT_PHONE,
    219                 SHARED_CONTACT_EMAIL,
    220                 SHARED_CONTACT_SIP,
    221                 com.android.cts.managedprofile.R.raw.ic_contact_picture);
    222 
    223         ContactInfo contactInfo = getContactInfoFromPhoneLookupUri(false /*isEnterprise*/,
    224                 SHARED_CONTACT_PHONE);
    225         assertNotNull(contactInfo);
    226         assertEquals(PRIMARY_CONTACT_DISPLAY_NAME_2, contactInfo.displayName);
    227         contactInfo.assertPhotoUrisReadable();
    228         assertTrue(contactInfo.hasPhotoId());
    229         assertFalse(isEnterpriseContactId(contactInfo.contactId));
    230 
    231         contactInfo = getContactInfoFromEmailLookupUri(false /*isEnterprise*/, SHARED_CONTACT_EMAIL);
    232         assertNotNull(contactInfo);
    233         assertEquals(PRIMARY_CONTACT_DISPLAY_NAME_2, contactInfo.displayName);
    234         contactInfo.assertPhotoUrisReadable();
    235         assertTrue(contactInfo.hasPhotoId());
    236         assertFalse(isEnterpriseContactId(contactInfo.contactId));
    237     }
    238 
    239     public void testManagedProfileDuplicatedPhoneEmailContact_insertedAndfound() throws
    240             RemoteException, OperationApplicationException, NotFoundException, IOException {
    241         assertTrue(isManagedProfile());
    242         insertContact(MANAGED_CONTACT_DISPLAY_NAME_2, SHARED_CONTACT_PHONE,
    243                 SHARED_CONTACT_EMAIL, SHARED_CONTACT_SIP , 0);
    244 
    245         ContactInfo contactInfo = getContactInfoFromPhoneLookupUri(false /*isEnterprise*/,
    246                 SHARED_CONTACT_PHONE);
    247         assertNotNull(contactInfo);
    248         assertEquals(MANAGED_CONTACT_DISPLAY_NAME_2, contactInfo.displayName);
    249         contactInfo.assertNoPhotoUri();
    250         assertFalse(contactInfo.hasPhotoId());
    251         assertFalse(isEnterpriseContactId(contactInfo.contactId));
    252 
    253         contactInfo = getContactInfoFromEmailLookupUri(false /*isEnterprise*/, SHARED_CONTACT_EMAIL);
    254         assertNotNull(contactInfo);
    255         assertEquals(MANAGED_CONTACT_DISPLAY_NAME_2, contactInfo.displayName);
    256         contactInfo.assertNoPhotoUri();
    257         assertFalse(contactInfo.hasPhotoId());
    258         assertFalse(isEnterpriseContactId(contactInfo.contactId));
    259     }
    260 
    261     public void testPrimaryProfileEnterprisePhoneLookup_canAccessEnterpriseContact()
    262             throws IOException {
    263         assertFalse(isManagedProfile());
    264         ContactInfo contactInfo = getContactInfoFromPhoneLookupUri(true /*isEnterprise*/,
    265                 MANAGED_CONTACT_PHONE);
    266         assertManagedLocalContact(contactInfo);
    267         contactInfo.assertPhotoUrisReadable();
    268         // Cannot get photo id in ENTERPRISE_CONTENT_FILTER_URI
    269         assertFalse(contactInfo.hasPhotoId());
    270         assertTrue(isEnterpriseContactId(contactInfo.contactId));
    271     }
    272 
    273     public void testPrimaryProfileEnterpriseSipLookup_canAccessEnterpriseContact()
    274             throws IOException {
    275         assertFalse(isManagedProfile());
    276         ContactInfo contactInfo = getContactInfoFromEnterprisePhoneLookupUriWithSipAddress(
    277                 true /*isEnterprise*/, MANAGED_CONTACT_SIP);
    278         assertManagedLocalContact(contactInfo);
    279         contactInfo.assertPhotoUrisReadable();
    280         assertFalse(contactInfo.hasPhotoId());
    281         assertTrue(isEnterpriseContactId(contactInfo.contactId));
    282     }
    283 
    284     public void testPrimaryProfileEnterpriseEmailLookup_canAccessEnterpriseContact()
    285             throws IOException {
    286         assertFalse(isManagedProfile());
    287         ContactInfo contactInfo = getContactInfoFromEmailLookupUri(true /*isEnterprise*/,
    288                 MANAGED_CONTACT_EMAIL);
    289         assertManagedLocalContact(contactInfo);
    290         contactInfo.assertPhotoUrisReadable();
    291         // Cannot get photo id in ENTERPRISE_CONTENT_FILTER_URI
    292         assertFalse(contactInfo.hasPhotoId());
    293         assertTrue(isEnterpriseContactId(contactInfo.contactId));
    294     }
    295 
    296     public void testPrimaryProfileEnterprisePhoneLookupDuplicated_canAccessPrimaryContact()
    297             throws IOException {
    298         assertFalse(isManagedProfile());
    299         ContactInfo contactInfo = getContactInfoFromPhoneLookupUri(true /*isEnterprise*/,
    300                 SHARED_CONTACT_PHONE);
    301         assertEquals(PRIMARY_CONTACT_DISPLAY_NAME_2, contactInfo.displayName);
    302         contactInfo.assertPhotoUrisReadable();
    303         assertTrue(contactInfo.hasPhotoId());
    304         assertFalse(isEnterpriseContactId(contactInfo.contactId));
    305     }
    306 
    307     public void testPrimaryProfileEnterpriseEmailLookupDuplicated_canAccessPrimaryContact()
    308             throws IOException {
    309         assertFalse(isManagedProfile());
    310         ContactInfo contactInfo = getContactInfoFromEmailLookupUri(true /*isEnterprise*/,
    311                 SHARED_CONTACT_EMAIL);
    312         assertEquals(PRIMARY_CONTACT_DISPLAY_NAME_2, contactInfo.displayName);
    313         contactInfo.assertPhotoUrisReadable();
    314         assertTrue(contactInfo.hasPhotoId());
    315         assertFalse(isEnterpriseContactId(contactInfo.contactId));
    316     }
    317 
    318     public void testManagedProfileEnterprisePhoneLookupDuplicated_canAccessEnterpriseContact() {
    319         assertTrue(isManagedProfile());
    320         ContactInfo contactInfo = getContactInfoFromPhoneLookupUri(true /*isEnterprise*/,
    321                 SHARED_CONTACT_PHONE);
    322         assertEquals(MANAGED_CONTACT_DISPLAY_NAME_2, contactInfo.displayName);
    323         contactInfo.assertNoPhotoUri();
    324         assertFalse(contactInfo.hasPhotoId());
    325         assertFalse(isEnterpriseContactId(contactInfo.contactId));
    326     }
    327 
    328     public void testManagedProfileEnterpriseEmailLookupDuplicated_canAccessEnterpriseContact() {
    329         assertTrue(isManagedProfile());
    330         ContactInfo contactInfo = getContactInfoFromEmailLookupUri(true /*isEnterprise*/,
    331                 SHARED_CONTACT_EMAIL);
    332         assertEquals(MANAGED_CONTACT_DISPLAY_NAME_2, contactInfo.displayName);
    333         contactInfo.assertNoPhotoUri();
    334         assertFalse(contactInfo.hasPhotoId());
    335         assertFalse(isEnterpriseContactId(contactInfo.contactId));
    336     }
    337 
    338     public void testPrimaryProfilePhoneLookup_canNotAccessEnterpriseContact() {
    339         assertFalse(isManagedProfile());
    340         ContactInfo contactInfo = getContactInfoFromPhoneLookupUri(false /*isEnterprise*/,
    341                 MANAGED_CONTACT_PHONE);
    342         assertNull(contactInfo);
    343     }
    344 
    345     public void testPrimaryProfileEmailLookup_canNotAccessEnterpriseContact() {
    346         assertFalse(isManagedProfile());
    347         ContactInfo contactInfo = getContactInfoFromEmailLookupUri(false /*isEnterprise*/,
    348                 MANAGED_CONTACT_EMAIL);
    349         assertNull(contactInfo);
    350     }
    351 
    352     public void testPrimaryProfileEnterprisePhoneLookup_canAccessPrimaryContact() {
    353         assertFalse(isManagedProfile());
    354         ContactInfo contactInfo = getContactInfoFromPhoneLookupUri(true /*isEnterprise*/,
    355                 PRIMARY_CONTACT_PHONE);
    356         assertEquals(PRIMARY_CONTACT_DISPLAY_NAME, contactInfo.displayName);
    357         contactInfo.assertNoPhotoUri();
    358         assertFalse(contactInfo.hasPhotoId());
    359         assertFalse(isEnterpriseContactId(contactInfo.contactId));
    360     }
    361 
    362     public void testPrimaryProfileEnterpriseEmailLookup_canAccessPrimaryContact() {
    363         assertFalse(isManagedProfile());
    364         ContactInfo contactInfo = getContactInfoFromEmailLookupUri(true /*isEnterprise*/,
    365                 PRIMARY_CONTACT_EMAIL);
    366         assertEquals(PRIMARY_CONTACT_DISPLAY_NAME, contactInfo.displayName);
    367         contactInfo.assertNoPhotoUri();
    368         assertFalse(contactInfo.hasPhotoId());
    369         assertFalse(isEnterpriseContactId(contactInfo.contactId));
    370     }
    371 
    372     public void testManagedProfileEnterprisePhoneLookup_canAccessEnterpriseContact() {
    373         assertTrue(isManagedProfile());
    374         ContactInfo contactInfo = getContactInfoFromPhoneLookupUri(true /*isEnterprise*/,
    375                 MANAGED_CONTACT_PHONE);
    376         assertManagedLocalContact(contactInfo);
    377         contactInfo.assertPhotoUrisReadable();
    378         assertTrue(contactInfo.hasPhotoId());
    379         assertFalse(isEnterpriseContactId(contactInfo.contactId));
    380     }
    381 
    382     public void testManagedProfileEnterpriseEmailLookup_canAccessEnterpriseContact() {
    383         assertTrue(isManagedProfile());
    384         ContactInfo contactInfo = getContactInfoFromEmailLookupUri(true /*isEnterprise*/,
    385                 MANAGED_CONTACT_EMAIL);
    386         assertManagedLocalContact(contactInfo);
    387         contactInfo.assertPhotoUrisReadable();
    388         assertTrue(contactInfo.hasPhotoId());
    389         assertFalse(isEnterpriseContactId(contactInfo.contactId));
    390     }
    391 
    392     public void testManagedProfileEnterprisePhoneLookup_canNotAccessPrimaryContact() {
    393         assertTrue(isManagedProfile());
    394         ContactInfo contactInfo = getContactInfoFromPhoneLookupUri(true /*isEnterprise*/,
    395                 PRIMARY_CONTACT_PHONE);
    396         assertNull(contactInfo);
    397     }
    398 
    399     public void testManagedProfileEnterpriseEmailLookup_canNotAccessPrimaryContact() {
    400         assertTrue(isManagedProfile());
    401         ContactInfo contactInfo = getContactInfoFromEmailLookupUri(true /*isEnterprise*/,
    402                 PRIMARY_CONTACT_EMAIL);
    403         assertNull(contactInfo);
    404     }
    405 
    406     public void testManagedProfilePhoneLookup_canNotAccessPrimaryContact() {
    407         assertTrue(isManagedProfile());
    408         ContactInfo contactInfo = getContactInfoFromPhoneLookupUri(false /*isEnterprise*/,
    409                 PRIMARY_CONTACT_PHONE);
    410         assertNull(contactInfo);
    411     }
    412 
    413     public void testManagedProfileEmailLookup_canNotAccessPrimaryContact() {
    414         assertTrue(isManagedProfile());
    415         ContactInfo contactInfo = getContactInfoFromEmailLookupUri(false /*isEnterprise */,
    416                 PRIMARY_CONTACT_EMAIL);
    417         assertNull(contactInfo);
    418     }
    419 
    420     public void testPrimaryProfileEnterpriseEmailLookup_canNotAccessEnterpriseContact() {
    421         assertFalse(isManagedProfile());
    422         ContactInfo contactInfo = getContactInfoFromEmailLookupUri(true /*isEnterprise*/,
    423                 MANAGED_CONTACT_EMAIL);
    424         assertNull(contactInfo);
    425     }
    426 
    427     public void testPrimaryProfileEnterprisePhoneLookup_canNotAccessEnterpriseContact() {
    428         assertFalse(isManagedProfile());
    429         ContactInfo contactInfo = getContactInfoFromPhoneLookupUri(true /*isEnterprise*/,
    430                 MANAGED_CONTACT_PHONE);
    431         assertNull(contactInfo);
    432     }
    433 
    434     public void testPrimaryProfileEnterprisePhoneLookup_canNotAccessManagedDirectories() {
    435         assertFalse(isManagedProfile());
    436 
    437         // local directory
    438         final ContactInfo defaultContactInfo =
    439                 getContactInfoFromEnterprisePhoneLookupUriInDirectory(MANAGED_CONTACT_PHONE,
    440                         Directory.ENTERPRISE_DEFAULT);
    441         assertNull(defaultContactInfo);
    442 
    443         // remote directory
    444         final long directoryId = getEnterpriseRemoteDirectoryIdSliently();
    445         if (directoryId != 0) { // if directoryId == 0, it means it can't access managed directory
    446             final ContactInfo directoryContactInfo =
    447                     getContactInfoFromEnterprisePhoneLookupUriInDirectory(MANAGED_CONTACT_PHONE,
    448                             directoryId);
    449             assertNull(directoryContactInfo);
    450         }
    451     }
    452 
    453     public void testPrimaryProfileEnterpriseEmailLookup_canNotAccessManagedDirectories() {
    454         assertFalse(isManagedProfile());
    455 
    456         // local directory
    457         final ContactInfo defaultContactInfo =
    458                 getContactInfoFromEnterpriseEmailLookupUriInDirectory(MANAGED_CONTACT_EMAIL,
    459                         Directory.ENTERPRISE_DEFAULT);
    460         assertNull(defaultContactInfo);
    461 
    462         // remote directory
    463         final long directoryId = getEnterpriseRemoteDirectoryIdSliently();
    464         if (directoryId != 0) { // if directoryId == 0, it means it can't access managed directory
    465             final ContactInfo directoryContactInfo =
    466                     getContactInfoFromEnterpriseEmailLookupUriInDirectory(MANAGED_CONTACT_EMAIL,
    467                             directoryId);
    468             assertNull(directoryContactInfo);
    469         }
    470     }
    471 
    472     public void testSetCrossProfileCallerIdDisabled_true() {
    473         assertTrue(isManagedProfile());
    474         mDevicePolicyManager.setCrossProfileCallerIdDisabled(
    475                 BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT, true);
    476     }
    477 
    478     public void testSetCrossProfileCallerIdDisabled_false() {
    479         assertTrue(isManagedProfile());
    480         mDevicePolicyManager.setCrossProfileCallerIdDisabled(
    481                 BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT, false);
    482     }
    483 
    484     public void testSetCrossProfileContactsSearchDisabled_true() {
    485         assertTrue(isManagedProfile());
    486         mDevicePolicyManager.setCrossProfileContactsSearchDisabled(
    487                 BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT, true);
    488         assertTrue(mDevicePolicyManager.getCrossProfileContactsSearchDisabled(
    489                 BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT));
    490     }
    491 
    492     public void testSetCrossProfileContactsSearchDisabled_false() {
    493         assertTrue(isManagedProfile());
    494         mDevicePolicyManager.setCrossProfileContactsSearchDisabled(
    495                 BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT, false);
    496         assertFalse(mDevicePolicyManager.getCrossProfileContactsSearchDisabled(
    497                 BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT));
    498     }
    499 
    500     public void testCurrentProfileContacts_removeContacts() {
    501         removeAllTestContactsInProfile();
    502     }
    503 
    504     public void testSetBluetoothContactSharingDisabled_setterAndGetter() {
    505         mDevicePolicyManager.setBluetoothContactSharingDisabled(
    506                 BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT, false);
    507         assertFalse(mDevicePolicyManager.getBluetoothContactSharingDisabled(
    508                 BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT));
    509         mDevicePolicyManager.setBluetoothContactSharingDisabled(
    510                 BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT, true);
    511         assertTrue(mDevicePolicyManager.getBluetoothContactSharingDisabled(
    512                 BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT));
    513     }
    514 
    515     public void testGetDirectoryListInPrimaryProfile() {
    516         assertFalse(isManagedProfile());
    517         // As directory content in CP2 may not be updated, we will try 10 times to see if it's
    518         // updated
    519         for (int i = 0; i < MAX_RETRY_DIRECTORY_QUERY; i++) {
    520             final Cursor cursor = mResolver.query(Directory.ENTERPRISE_CONTENT_URI,
    521                     new String[]{
    522                             Directory._ID,
    523                             Directory.DISPLAY_NAME
    524                     }, null, null, null);
    525 
    526             boolean hasPrimaryDefault = false;
    527             boolean hasPrimaryInvisible = false;
    528             boolean hasManagedDefault = false;
    529             boolean hasManagedInvisible = false;
    530             boolean hasPrimaryDirectory = false;
    531             boolean hasManagedDirectory = false;
    532 
    533             try {
    534                 while(cursor.moveToNext()) {
    535                     final long directoryId = cursor.getLong(0);
    536                     if (directoryId == Directory.DEFAULT) {
    537                         hasPrimaryDefault = true;
    538                     } else if (directoryId == Directory.LOCAL_INVISIBLE) {
    539                         hasPrimaryInvisible = true;
    540                     } else if (directoryId == Directory.ENTERPRISE_DEFAULT) {
    541                         hasManagedDefault = true;
    542                     } else if (directoryId == Directory.ENTERPRISE_LOCAL_INVISIBLE) {
    543                         hasManagedInvisible = true;
    544                     } else {
    545                         final String displayName = cursor.getString(1);
    546                         if (Directory.isEnterpriseDirectoryId(directoryId)
    547                                 && displayName.equals(MANAGED_DIRECTORY_NAME)) {
    548                             hasManagedDirectory = true;
    549                         }
    550                         if (!Directory.isEnterpriseDirectoryId(directoryId)
    551                                 && displayName.equals(PRIMARY_DIRECTORY_NAME)) {
    552                             hasPrimaryDirectory = true;
    553                         }
    554                     }
    555                 }
    556                 if (i + 1 == MAX_RETRY_DIRECTORY_QUERY) {
    557                     DatabaseUtils.dumpCursor(cursor);
    558                     assertTrue(hasPrimaryDefault);
    559                     assertTrue(hasPrimaryInvisible);
    560                     assertTrue(hasManagedDefault);
    561                     assertTrue(hasManagedInvisible);
    562                     assertTrue(hasPrimaryDirectory);
    563                     assertTrue(hasManagedDirectory);
    564                 }
    565             } finally {
    566                 cursor.close();
    567             }
    568             if (hasPrimaryDefault && hasPrimaryInvisible && hasManagedDefault
    569                     && hasManagedInvisible && hasPrimaryDirectory && hasManagedDirectory) {
    570                 // Success
    571                 return;
    572             } else {
    573                 // Failed, sleep and retry
    574                 try {
    575                     Log.i(TAG, "Failed " + (i+1) + " times, retry");
    576                     Thread.sleep(RETRY_DIRECTORY_QUERY_INTERVAL);
    577                 } catch (InterruptedException e) {}
    578             }
    579         }
    580     }
    581 
    582     public void testPrimaryProfileEnterpriseEmailLookup_canAccessPrimaryDirectories() {
    583         assertFalse(isManagedProfile());
    584 
    585         // local directory
    586         final ContactInfo defaultContactInfo
    587                 = getContactInfoFromEnterpriseEmailLookupUriInDirectory(PRIMARY_CONTACT_EMAIL,
    588                 Directory.DEFAULT);
    589         assertPrimaryLocalContact(defaultContactInfo);
    590 
    591         // remote directory
    592         final long directoryId = getPrimaryRemoteDirectoryId();
    593         final ContactInfo directoryContactInfo
    594                 = getContactInfoFromEnterpriseEmailLookupUriInDirectory(PRIMARY_CONTACT_EMAIL,
    595                 directoryId);
    596         assertPrimaryDirectoryContact(directoryContactInfo);
    597     }
    598 
    599     public void testPrimaryProfileEnterpriseEmailLookup_canAccessManagedDirectories() {
    600         assertFalse(isManagedProfile());
    601 
    602         // local directory
    603         final ContactInfo defaultContactInfo
    604                 = getContactInfoFromEnterpriseEmailLookupUriInDirectory(MANAGED_CONTACT_EMAIL,
    605                 Directory.ENTERPRISE_DEFAULT);
    606         assertManagedLocalContact(defaultContactInfo);
    607 
    608         // remote directory
    609         final long directoryId = getEnterpriseRemoteDirectoryId();
    610         final ContactInfo directoryContactInfo
    611                 = getContactInfoFromEnterpriseEmailLookupUriInDirectory(MANAGED_CONTACT_EMAIL,
    612                 directoryId);
    613         assertManagedDirectoryContact(directoryContactInfo);
    614     }
    615 
    616     public void testPrimaryProfileEnterprisePhoneLookup_canAccessPrimaryDirectories() {
    617         assertFalse(isManagedProfile());
    618 
    619         // local directory
    620         final ContactInfo defaultContactInfo
    621                 = getContactInfoFromEnterprisePhoneLookupUriInDirectory(PRIMARY_CONTACT_PHONE,
    622                 Directory.DEFAULT);
    623         assertPrimaryLocalContact(defaultContactInfo);
    624 
    625         // remote directory
    626         final long directoryId = getPrimaryRemoteDirectoryId();
    627         final ContactInfo directoryContactInfo
    628                 = getContactInfoFromEnterprisePhoneLookupUriInDirectory(PRIMARY_CONTACT_PHONE,
    629                 directoryId);
    630         assertPrimaryDirectoryContact(directoryContactInfo);
    631     }
    632 
    633     public void testPrimaryProfileEnterprisePhoneLookup_canAccessManagedDirectories() {
    634         assertFalse(isManagedProfile());
    635 
    636         // local directory
    637         final ContactInfo defaultContactInfo
    638                 = getContactInfoFromEnterprisePhoneLookupUriInDirectory(MANAGED_CONTACT_PHONE,
    639                 Directory.ENTERPRISE_DEFAULT);
    640         assertManagedLocalContact(defaultContactInfo);
    641 
    642         // remote directory
    643         final long directoryId = getEnterpriseRemoteDirectoryId();
    644         final ContactInfo directoryContactInfo
    645                 = getContactInfoFromEnterprisePhoneLookupUriInDirectory(MANAGED_CONTACT_PHONE,
    646                 directoryId);
    647         assertManagedDirectoryContact(directoryContactInfo);
    648     }
    649 
    650     public void testPrimaryProfileEnterpriseCallableFilter_canAccessPrimaryDirectories() {
    651         assertFalse(isManagedProfile());
    652         final ContactInfo defaultContactInfo
    653                 = getContactInfoFromEnterpriseCallableFilterUriInDirectory(
    654                         PRIMARY_CONTACT_PHONE, Directory.DEFAULT);
    655         assertPrimaryLocalContact(defaultContactInfo);
    656 
    657         final ContactInfo directoryContactInfo
    658                 = getContactInfoFromEnterpriseCallableFilterUriInDirectory(
    659                         PRIMARY_CONTACT_PHONE, getPrimaryRemoteDirectoryId());
    660         assertPrimaryDirectoryContact(directoryContactInfo);
    661 
    662     }
    663 
    664     public void testManagedProfileEnterpriseCallableFilter_canAccessManagedDirectories() {
    665         assertTrue(isManagedProfile());
    666         final ContactInfo defaultContactInfo
    667                 = getContactInfoFromEnterpriseCallableFilterUriInDirectory(
    668                         MANAGED_CONTACT_PHONE, Directory.DEFAULT);
    669         assertManagedLocalContact(defaultContactInfo);
    670 
    671         final ContactInfo directoryContactInfo
    672                 = getContactInfoFromEnterpriseCallableFilterUriInDirectory(
    673                         MANAGED_CONTACT_PHONE, getEnterpriseRemoteDirectoryIdInManagedProfile());
    674         assertManagedDirectoryContact(directoryContactInfo);
    675     }
    676 
    677     public void testPrimaryProfileEnterpriseCallableFilter_canAccessManagedDirectories() {
    678         assertFalse(isManagedProfile());
    679 
    680         // local directory
    681         final ContactInfo defaultContactInfo
    682                 = getContactInfoFromEnterpriseCallableFilterUriInDirectory(
    683                         MANAGED_CONTACT_PHONE, Directory.ENTERPRISE_DEFAULT);
    684         assertManagedLocalContact(defaultContactInfo);
    685 
    686         // remote directory
    687         final long directoryId = getEnterpriseRemoteDirectoryId();
    688         final ContactInfo directoryContactInfo
    689                 = getContactInfoFromEnterpriseCallableFilterUriInDirectory(
    690                         MANAGED_CONTACT_PHONE, directoryId);
    691         assertManagedDirectoryContact(directoryContactInfo);
    692     }
    693 
    694     public void testPrimaryProfileEnterpriseCallableFilter_canNotAccessManagedDirectories() {
    695         assertFalse(isManagedProfile());
    696 
    697         // local directory
    698         final ContactInfo defaultContactInfo
    699                 = getContactInfoFromEnterpriseCallableFilterUriInDirectory(
    700                 MANAGED_CONTACT_PHONE, Directory.ENTERPRISE_DEFAULT);
    701         assertNull(defaultContactInfo);
    702 
    703         // remote directory
    704         final long directoryId = getEnterpriseRemoteDirectoryIdSliently();
    705         if (directoryId == 0L) {
    706             // if no enterprise directory id is found, the test succeeds.
    707             return;
    708         } else {
    709             final ContactInfo directoryContactInfo =
    710                     getContactInfoFromEnterpriseCallableFilterUriInDirectory(MANAGED_CONTACT_PHONE,
    711                             directoryId);
    712             assertNull(directoryContactInfo);
    713         }
    714     }
    715 
    716     public void testPrimaryProfileEnterpriseEmailFilter_canAccessPrimaryDirectories() {
    717         assertFalse(isManagedProfile());
    718         final ContactInfo defaultContactInfo
    719                 = getContactInfoFromEnterpriseEmailFilterUriInDirectory(
    720                         PRIMARY_CONTACT_EMAIL, Directory.DEFAULT);
    721         assertPrimaryLocalContact(defaultContactInfo);
    722 
    723         final ContactInfo directoryContactInfo
    724                 = getContactInfoFromEnterpriseEmailFilterUriInDirectory(
    725                         PRIMARY_CONTACT_EMAIL, getPrimaryRemoteDirectoryId());
    726         assertPrimaryDirectoryContact(directoryContactInfo);
    727     }
    728 
    729     public void testEnterpriseProfileEnterpriseEmailFilter_canAccessManagedDirectories() {
    730         assertTrue(isManagedProfile());
    731         final ContactInfo defaultContactInfo
    732                 = getContactInfoFromEnterpriseEmailFilterUriInDirectory(
    733                         MANAGED_CONTACT_EMAIL, Directory.DEFAULT);
    734         assertManagedLocalContact(defaultContactInfo);
    735 
    736         final ContactInfo directoryContactInfo
    737                 = getContactInfoFromEnterpriseEmailFilterUriInDirectory(
    738                         MANAGED_CONTACT_EMAIL, getEnterpriseRemoteDirectoryIdInManagedProfile());
    739         assertManagedDirectoryContact(directoryContactInfo);
    740     }
    741 
    742     public void testPrimaryProfileEnterpriseEmailFilter_canAccessManagedDirectories() {
    743         assertFalse(isManagedProfile());
    744 
    745         // local directory
    746         final ContactInfo defaultContactInfo
    747                 = getContactInfoFromEnterpriseEmailFilterUriInDirectory(
    748                 MANAGED_CONTACT_EMAIL, Directory.ENTERPRISE_DEFAULT);
    749         assertManagedLocalContact(defaultContactInfo);
    750 
    751         // remote directory
    752         final long directoryId = getEnterpriseRemoteDirectoryId();
    753         final ContactInfo directoryContactInfo
    754                 = getContactInfoFromEnterpriseEmailFilterUriInDirectory(
    755                 MANAGED_CONTACT_EMAIL, directoryId);
    756         assertManagedDirectoryContact(directoryContactInfo);
    757     }
    758 
    759     public void testPrimaryProfileEnterpriseEmailFilter_canNotAccessManagedDirectories() {
    760         assertFalse(isManagedProfile());
    761 
    762         // local directory
    763         final ContactInfo defaultContactInfo =
    764                 getContactInfoFromEnterpriseEmailFilterUriInDirectory(MANAGED_CONTACT_EMAIL,
    765                         Directory.ENTERPRISE_DEFAULT);
    766         assertNull(defaultContactInfo);
    767 
    768         // remote directory
    769         final long directoryId = getEnterpriseRemoteDirectoryIdSliently();
    770         if (directoryId == 0L) {
    771             // if no enterprise directory id is found, the test succeeds.
    772             return;
    773         } else {
    774             final ContactInfo directoryContactInfo =
    775                     getContactInfoFromEnterpriseEmailFilterUriInDirectory(MANAGED_CONTACT_EMAIL,
    776                             directoryId);
    777             assertNull(directoryContactInfo);
    778         }
    779     }
    780 
    781     public void testPrimaryProfileEnterpriseContactFilter_canAccessPrimaryDirectories() {
    782         assertFalse(isManagedProfile());
    783         final ContactInfo defaultContactInfo
    784                 = getContactInfoFromEnterpriseContactFilterUriInDirectory(
    785                         PRIMARY_CONTACT_DISPLAY_NAME, Directory.DEFAULT);
    786         assertPrimaryLocalContact(defaultContactInfo);
    787 
    788         final ContactInfo directoryContactInfo
    789                 = getContactInfoFromEnterpriseContactFilterUriInDirectory(
    790                         PRIMARY_DIRECTORY_CONTACT_NAME, getPrimaryRemoteDirectoryId());
    791         assertPrimaryDirectoryContact(directoryContactInfo);
    792     }
    793 
    794     public void testManagedProfileEnterpriseContactFilter_canAccessManagedDirectories() {
    795         assertTrue(isManagedProfile());
    796         final ContactInfo defaultContactInfo
    797                 = getContactInfoFromEnterpriseContactFilterUriInDirectory(
    798                         MANAGED_CONTACT_DISPLAY_NAME, Directory.DEFAULT);
    799         assertManagedLocalContact(defaultContactInfo);
    800 
    801         final ContactInfo directoryContactInfo
    802                 = getContactInfoFromEnterpriseContactFilterUriInDirectory(
    803                         MANAGED_DIRECTORY_CONTACT_NAME, getEnterpriseRemoteDirectoryIdInManagedProfile());
    804         assertManagedDirectoryContact(directoryContactInfo);
    805     }
    806 
    807     public void testPrimaryProfileEnterpriseContactFilter_canAccessManagedDirectories() {
    808         assertFalse(isManagedProfile());
    809 
    810         // local directory
    811         final ContactInfo defaultContactInfo
    812                 = getContactInfoFromEnterpriseContactFilterUriInDirectory(
    813                         MANAGED_CONTACT_DISPLAY_NAME, Directory.ENTERPRISE_DEFAULT);
    814         assertManagedLocalContact(defaultContactInfo);
    815 
    816         // remote directory
    817         final long directoryId = getEnterpriseRemoteDirectoryId();
    818         final ContactInfo directoryContactInfo
    819                 = getContactInfoFromEnterpriseEmailFilterUriInDirectory(
    820                         MANAGED_CONTACT_DISPLAY_NAME, directoryId);
    821         assertManagedDirectoryContact(directoryContactInfo);
    822     }
    823 
    824     public void testPrimaryProfileEnterpriseContactFilter_canNotAccessManagedDirectories() {
    825         assertFalse(isManagedProfile());
    826 
    827         // local directory
    828         final ContactInfo defaultContactInfo
    829                 = getContactInfoFromEnterpriseContactFilterUriInDirectory(
    830                         MANAGED_CONTACT_DISPLAY_NAME, Directory.ENTERPRISE_DEFAULT);
    831         assertNull(defaultContactInfo);
    832 
    833         // remote directory
    834         final long directoryId = getEnterpriseRemoteDirectoryIdSliently();
    835         if (directoryId == 0L) {
    836             // if no enterprise directory id is found, the test succeeds.
    837             return;
    838         } else {
    839             final ContactInfo directoryContactInfo =
    840                     getContactInfoFromEnterpriseEmailFilterUriInDirectory(
    841                             MANAGED_CONTACT_DISPLAY_NAME, directoryId);
    842             assertNull(directoryContactInfo);
    843         }
    844     }
    845 
    846     public void testPrimaryProfileEnterprisePhoneFilter_canAccessPrimaryDirectories() {
    847         assertFalse(isManagedProfile());
    848         final ContactInfo defaultContactInfo
    849                 = getContactInfoFromEnterprisePhoneFilterUriInDirectory(
    850                         PRIMARY_CONTACT_PHONE, Directory.DEFAULT);
    851         assertPrimaryLocalContact(defaultContactInfo);
    852 
    853         final ContactInfo directoryContactInfo
    854                 = getContactInfoFromEnterprisePhoneFilterUriInDirectory(
    855                         PRIMARY_CONTACT_PHONE, getPrimaryRemoteDirectoryId());
    856         assertPrimaryDirectoryContact(directoryContactInfo);
    857     }
    858 
    859     public void testManagedProfileEnterprisePhoneFilter_canAccessManagedDirectories() {
    860         assertTrue(isManagedProfile());
    861         final ContactInfo defaultContactInfo
    862                 = getContactInfoFromEnterprisePhoneFilterUriInDirectory(
    863                         MANAGED_CONTACT_PHONE, Directory.DEFAULT);
    864         assertManagedLocalContact(defaultContactInfo);
    865 
    866         final ContactInfo directoryContactInfo
    867                 = getContactInfoFromEnterprisePhoneFilterUriInDirectory(
    868                         MANAGED_CONTACT_PHONE, getEnterpriseRemoteDirectoryIdInManagedProfile());
    869         assertManagedDirectoryContact(directoryContactInfo);
    870     }
    871 
    872     public void testPrimaryProfileEnterprisePhoneFilter_canAccessManagedDirectories() {
    873         assertFalse(isManagedProfile());
    874 
    875         // local directory
    876         final ContactInfo defaultContactInfo
    877                 = getContactInfoFromEnterprisePhoneFilterUriInDirectory(
    878                 MANAGED_CONTACT_PHONE, Directory.ENTERPRISE_DEFAULT);
    879         assertManagedLocalContact(defaultContactInfo);
    880 
    881         // remote directory
    882         final long directoryId = getEnterpriseRemoteDirectoryId();
    883         final ContactInfo directoryContactInfo
    884                 = getContactInfoFromEnterprisePhoneFilterUriInDirectory(
    885                 MANAGED_CONTACT_PHONE, directoryId);
    886         assertManagedDirectoryContact(directoryContactInfo);
    887     }
    888 
    889     public void testPrimaryProfileEnterprisePhoneFilter_canNotAccessManagedDirectories() {
    890         assertFalse(isManagedProfile());
    891 
    892         // local directory
    893         final ContactInfo defaultContactInfo
    894                 = getContactInfoFromEnterprisePhoneFilterUriInDirectory(
    895                 MANAGED_CONTACT_PHONE, Directory.ENTERPRISE_DEFAULT);
    896         assertNull(defaultContactInfo);
    897 
    898         // remote directory
    899         final long directoryId = getEnterpriseRemoteDirectoryIdSliently();
    900         if (directoryId == 0L) {
    901             // if no enterprise directory id is found, the test succeeds.
    902             return;
    903         } else {
    904             final ContactInfo directoryContactInfo =
    905                     getContactInfoFromEnterprisePhoneFilterUriInDirectory(
    906                             MANAGED_CONTACT_PHONE, directoryId);
    907             assertNull(directoryContactInfo);
    908         }
    909     }
    910 
    911     public void testPrimaryProfileEnterpriseDirectories_canNotAccessManagedDirectories() {
    912         assertFalse(isManagedProfile());
    913 
    914         final Cursor cursor = mResolver.query(Directory.ENTERPRISE_CONTENT_URI,
    915                 new String[]{Directory._ID}, null, null, null);
    916         try {
    917             while (cursor.moveToNext()) {
    918                 final long directoryId = cursor.getLong(0);
    919                 if (Directory.isEnterpriseDirectoryId(directoryId)) {
    920                     fail("found enterprise directories");
    921                 }
    922             }
    923         } finally {
    924             cursor.close();
    925         }
    926     }
    927 
    928 
    929     public void testFilterUriWhenDirectoryParamMissing() {
    930         assertFailWhenDirectoryParamMissing(Phone.ENTERPRISE_CONTENT_FILTER_URI);
    931         assertFailWhenDirectoryParamMissing(Email.ENTERPRISE_CONTENT_FILTER_URI);
    932         assertFailWhenDirectoryParamMissing(Contacts.ENTERPRISE_CONTENT_FILTER_URI);
    933         assertFailWhenDirectoryParamMissing(Callable.ENTERPRISE_CONTENT_FILTER_URI);
    934     }
    935 
    936     public void testQuickContact() throws Exception {
    937         showQuickContactInternal(null);
    938         showQuickContactInternal(Directory.ENTERPRISE_DEFAULT);
    939         showQuickContactInternal(getEnterpriseRemoteDirectoryId());
    940     }
    941 
    942     private void showQuickContactInternal(Long directoryId) throws Exception {
    943         final Uri phoneLookupUri =
    944                 Uri.withAppendedPath(
    945                         PhoneLookup.ENTERPRISE_CONTENT_FILTER_URI, MANAGED_CONTACT_PHONE);
    946         if (directoryId != null) {
    947             phoneLookupUri.buildUpon().appendQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY,
    948                     String.valueOf(directoryId)).build();
    949         }
    950         final Cursor cursor =
    951                 getContext().getContentResolver().query(phoneLookupUri, null, null, null, null);
    952         try {
    953             assertTrue(cursor.moveToFirst());
    954             final long contactId =
    955                     cursor.getLong(cursor.getColumnIndex(ContactsContract.PhoneLookup._ID));
    956             final String lookupKey =
    957                     cursor.getString(
    958                             cursor.getColumnIndex(ContactsContract.PhoneLookup.LOOKUP_KEY));
    959             final Uri lookupUri = Contacts.getLookupUri(contactId, lookupKey);
    960             // TODO: It is better to verify the uri received by quick contacts, but it is difficult
    961             // to verify it as the quick contacts in managed profile is started. We now just make
    962             // sure no exception is thrown due to invalid uri (eg: directory id is missing).
    963             // Also, consider using UiAutomator to verify the activtiy is started.
    964             ContactsContract.QuickContact.showQuickContact(getContext(), (Rect) null, lookupUri,
    965                     ContactsContract.QuickContact.MODE_LARGE, null);
    966         } finally {
    967             if (cursor != null) {
    968                 cursor.close();
    969             }
    970         }
    971     }
    972 
    973     private long getPrimaryRemoteDirectoryId() {
    974         assertFalse(isManagedProfile());
    975         return getRemoteDirectoryIdInternal();
    976     }
    977 
    978     private long getEnterpriseRemoteDirectoryIdInManagedProfile() {
    979         assertTrue(isManagedProfile());
    980         return getRemoteDirectoryIdInternal();
    981     }
    982 
    983     private long getRemoteDirectoryIdInternal() {
    984         final Cursor cursor = mResolver.query(Directory.ENTERPRISE_CONTENT_URI,
    985                 new String[]{
    986                         Directory._ID, Directory.DIRECTORY_AUTHORITY
    987                 }, null, null, null);
    988         try {
    989             while (cursor.moveToNext()) {
    990                 final long directoryId = cursor.getLong(0);
    991                 final String directoryAuthority = cursor.getString(1);
    992                 if (!Directory.isEnterpriseDirectoryId(directoryId)
    993                         && Directory.isRemoteDirectoryId(directoryId)
    994                         && DIRECTORY_PROVIDER_AUTHORITY.equals(directoryAuthority)) {
    995                     return directoryId;
    996                 }
    997             }
    998         } finally {
    999             cursor.close();
   1000         }
   1001         fail("Cannot find primary directory id");
   1002         return 0;
   1003     }
   1004 
   1005     private long getEnterpriseRemoteDirectoryId() {
   1006         final long enterpriseDirectoryId = getEnterpriseRemoteDirectoryIdSliently();
   1007         assertNotSame("Cannot find enterprise directory id", 0L, enterpriseDirectoryId);
   1008         return enterpriseDirectoryId;
   1009     }
   1010 
   1011     private long getEnterpriseRemoteDirectoryIdSliently() {
   1012         assertFalse(isManagedProfile());
   1013         final Cursor cursor = mResolver.query(Directory.ENTERPRISE_CONTENT_URI,
   1014                 new String[] {
   1015                     Directory._ID, Directory.DIRECTORY_AUTHORITY
   1016                 }, null, null, null);
   1017         try {
   1018             while (cursor.moveToNext()) {
   1019                 final long directoryId = cursor.getLong(0);
   1020                 final String directoryAuthority = cursor.getString(1);
   1021                 if (Directory.isEnterpriseDirectoryId(directoryId)
   1022                         && Directory.isRemoteDirectoryId(directoryId)
   1023                         && DIRECTORY_PROVIDER_AUTHORITY.equals(directoryAuthority)) {
   1024                     return directoryId;
   1025                 }
   1026             }
   1027         } finally {
   1028             cursor.close();
   1029         }
   1030         return 0;
   1031     }
   1032 
   1033     private boolean isManagedProfile() {
   1034         String adminPackage = BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT.getPackageName();
   1035         return mDevicePolicyManager.isProfileOwnerApp(adminPackage);
   1036     }
   1037 
   1038     private void insertContact(String displayName, String phoneNumber, String email,
   1039             String sipAddress, int photoResId)
   1040             throws RemoteException, OperationApplicationException, NotFoundException, IOException {
   1041         ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
   1042         ops.add(ContentProviderOperation
   1043                 .newInsert(ContactsContract.RawContacts.CONTENT_URI)
   1044                 .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, TEST_ACCOUNT_TYPE)
   1045                 .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, TEST_ACCOUNT_NAME)
   1046                 .build());
   1047         ops.add(ContentProviderOperation
   1048                 .newInsert(ContactsContract.Data.CONTENT_URI)
   1049                 .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
   1050                 .withValue(
   1051                         ContactsContract.Data.MIMETYPE,
   1052                         ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
   1053                 .withValue(
   1054                         ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
   1055                         displayName)
   1056                 .build());
   1057         ops.add(ContentProviderOperation
   1058                 .newInsert(ContactsContract.Data.CONTENT_URI)
   1059                 .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
   1060                 .withValue(
   1061                         ContactsContract.Data.MIMETYPE,
   1062                         ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
   1063                 .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER,
   1064                         phoneNumber)
   1065                 .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
   1066                         Phone.TYPE_MOBILE)
   1067                 .build());
   1068         ops.add(ContentProviderOperation
   1069                 .newInsert(ContactsContract.Data.CONTENT_URI)
   1070                 .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
   1071                 .withValue(
   1072                         ContactsContract.Data.MIMETYPE,
   1073                         ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
   1074                 .withValue(ContactsContract.CommonDataKinds.Email.ADDRESS,
   1075                         email)
   1076                 .withValue(ContactsContract.CommonDataKinds.Email.TYPE,
   1077                         Email.TYPE_WORK)
   1078                 .build());
   1079         ops.add(ContentProviderOperation
   1080                 .newInsert(ContactsContract.Data.CONTENT_URI)
   1081                 .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
   1082                 .withValue(
   1083                         ContactsContract.Data.MIMETYPE,
   1084                         ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE)
   1085                 .withValue(ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS,
   1086                         sipAddress)
   1087                 .withValue(ContactsContract.CommonDataKinds.SipAddress.TYPE,
   1088                         ContactsContract.CommonDataKinds.SipAddress.TYPE_WORK)
   1089                 .build());
   1090 
   1091         if (photoResId != 0) {
   1092             InputStream phoneInputStream = mContext.getResources().openRawResource(photoResId);
   1093             try {
   1094                 byte[] rawPhoto = getByteFromStream(phoneInputStream);
   1095                 ops.add(ContentProviderOperation
   1096                         .newInsert(ContactsContract.Data.CONTENT_URI)
   1097                         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
   1098                         .withValue(
   1099                                 ContactsContract.Data.MIMETYPE,
   1100                                 ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
   1101                         .withValue(Photo.PHOTO, rawPhoto)
   1102                         .build());
   1103             } finally {
   1104                 phoneInputStream.close();
   1105             }
   1106         }
   1107 
   1108         mResolver.applyBatch(ContactsContract.AUTHORITY, ops);
   1109     }
   1110 
   1111     private void assertPrimaryLocalContact(ContactInfo contactInfo) {
   1112         assertNotNull(contactInfo);
   1113         assertEquals(PRIMARY_CONTACT_DISPLAY_NAME, contactInfo.displayName);
   1114         contactInfo.assertNoPhotoUri();
   1115         assertFalse(contactInfo.hasPhotoId());
   1116     }
   1117 
   1118     private void assertManagedLocalContact(ContactInfo contactInfo) {
   1119         assertNotNull(contactInfo);
   1120         assertEquals(MANAGED_CONTACT_DISPLAY_NAME, contactInfo.displayName);
   1121         contactInfo.assertPhotoUrisReadable();
   1122     }
   1123 
   1124     private void assertPrimaryDirectoryContact(ContactInfo contactInfo) {
   1125         assertNotNull(contactInfo);
   1126         assertEquals(PRIMARY_DIRECTORY_CONTACT_NAME, contactInfo.displayName);
   1127         contactInfo.assertThumbnailUri(R.raw.primary_thumbnail);
   1128         contactInfo.assertPhotoUri(R.raw.primary_photo);
   1129     }
   1130 
   1131     private void assertManagedDirectoryContact(ContactInfo contactInfo) {
   1132         assertNotNull(contactInfo);
   1133         assertEquals(MANAGED_DIRECTORY_CONTACT_NAME, contactInfo.displayName);
   1134         contactInfo.assertThumbnailUri(R.raw.managed_thumbnail);
   1135         contactInfo.assertPhotoUri(R.raw.managed_photo);
   1136     }
   1137 
   1138     private void assertContactInfoEquals(ContactInfo lhs, ContactInfo rhs) {
   1139         if (lhs == null) {
   1140             assertNull(rhs);
   1141         } else {
   1142             assertNotNull(rhs);
   1143             assertEquals(lhs.contactId, rhs.contactId);
   1144             assertEquals(lhs.displayName, rhs.displayName);
   1145             assertEquals(lhs.photoId, rhs.photoId);
   1146             assertEquals(lhs.photoThumbnailUri, rhs.photoThumbnailUri);
   1147             assertEquals(lhs.photoUri, rhs.photoUri);
   1148         }
   1149     }
   1150 
   1151     private ContactInfo getContactInfoFromPhoneLookupUri(boolean isEnterprise, String phoneNumber) {
   1152         Uri baseUri = (isEnterprise) ? PhoneLookup.ENTERPRISE_CONTENT_FILTER_URI
   1153                 : PhoneLookup.CONTENT_FILTER_URI;
   1154         Uri uri = baseUri.buildUpon().appendPath(phoneNumber).build();
   1155         ContactInfo contactInfo = getContactInfoFromUri(uri, PhoneLookup._ID,
   1156                 PhoneLookup.DISPLAY_NAME,
   1157                 PhoneLookup.PHOTO_URI, PhoneLookup.PHOTO_THUMBNAIL_URI, PhoneLookup.PHOTO_ID);
   1158 
   1159         ContactInfo contactInfo2 = getContactInfoFromUri(uri, PhoneLookup.CONTACT_ID,
   1160                 PhoneLookup.DISPLAY_NAME,
   1161                 PhoneLookup.PHOTO_URI, PhoneLookup.PHOTO_THUMBNAIL_URI, PhoneLookup.PHOTO_ID);
   1162         assertContactInfoEquals(contactInfo, contactInfo2);
   1163         return contactInfo;
   1164     }
   1165 
   1166     private ContactInfo getContactInfoFromEnterprisePhoneLookupUriWithSipAddress(
   1167             boolean isEnterprise, String sipAddress) {
   1168         Uri baseUri = (isEnterprise) ? PhoneLookup.ENTERPRISE_CONTENT_FILTER_URI
   1169                 : PhoneLookup.CONTENT_FILTER_URI;
   1170         Uri uri = baseUri.buildUpon().appendPath(sipAddress)
   1171                 .appendQueryParameter(PhoneLookup.QUERY_PARAMETER_SIP_ADDRESS, "1").build();
   1172         return getContactInfoFromUri(uri, PhoneLookup.CONTACT_ID, PhoneLookup.DISPLAY_NAME,
   1173                 PhoneLookup.PHOTO_URI, PhoneLookup.PHOTO_THUMBNAIL_URI, PhoneLookup.PHOTO_ID);
   1174     }
   1175 
   1176     private ContactInfo getContactInfoFromEnterprisePhoneLookupUriInDirectory(String phoneNumber,
   1177             long directoryId) {
   1178         Uri uri = PhoneLookup.ENTERPRISE_CONTENT_FILTER_URI.buildUpon().appendPath(phoneNumber)
   1179                 .appendQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY,
   1180                         String.valueOf(directoryId)).build();
   1181         return getContactInfoFromUri(uri, PhoneLookup._ID, PhoneLookup.DISPLAY_NAME,
   1182                 PhoneLookup.PHOTO_URI, PhoneLookup.PHOTO_THUMBNAIL_URI, PhoneLookup.PHOTO_ID);
   1183     }
   1184 
   1185     private ContactInfo getContactInfoFromEmailLookupUri(boolean isEnterprise, String email) {
   1186         Uri baseUri = (isEnterprise) ? Email.ENTERPRISE_CONTENT_LOOKUP_URI
   1187                 : Email.CONTENT_LOOKUP_URI;
   1188         Uri uri = Uri.withAppendedPath(baseUri, email);
   1189         return getContactInfoFromUri(uri, Email.CONTACT_ID, Email.DISPLAY_NAME_PRIMARY,
   1190                 Email.PHOTO_URI, Email.PHOTO_THUMBNAIL_URI, Email.PHOTO_ID);
   1191     }
   1192 
   1193     private ContactInfo getContactInfoFromEnterpriseEmailLookupUriInDirectory(String email,
   1194             long directoryId) {
   1195         Uri uri = Email.ENTERPRISE_CONTENT_LOOKUP_URI.buildUpon().appendPath(email)
   1196                 .appendQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY,
   1197                         String.valueOf(directoryId)).build();
   1198         return getContactInfoFromUri(uri, Email.CONTACT_ID, Email.DISPLAY_NAME_PRIMARY,
   1199                 Email.PHOTO_URI, Email.PHOTO_THUMBNAIL_URI, Email.PHOTO_ID);
   1200     }
   1201 
   1202     private ContactInfo getContactInfoFromEnterpriseCallableFilterUriInDirectory(String filter,
   1203             long directoryId) {
   1204         final Uri uri = Uri.withAppendedPath(Callable.ENTERPRISE_CONTENT_FILTER_URI, filter)
   1205                 .buildUpon().appendQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY,
   1206                         String.valueOf(directoryId)).build();
   1207         return getContactInfoFromUri(uri, Callable.CONTACT_ID, Callable.DISPLAY_NAME_PRIMARY,
   1208                 Callable.PHOTO_URI, Callable.PHOTO_THUMBNAIL_URI, Callable.PHOTO_ID);
   1209     }
   1210 
   1211     private ContactInfo getContactInfoFromEnterpriseEmailFilterUriInDirectory(String filter,
   1212             long directoryId) {
   1213         final Uri uri = Uri.withAppendedPath(Email.ENTERPRISE_CONTENT_FILTER_URI, filter)
   1214                 .buildUpon().appendQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY,
   1215                         String.valueOf(directoryId)).build();
   1216         return getContactInfoFromUri(uri, Email.CONTACT_ID, Email.DISPLAY_NAME_PRIMARY,
   1217                 Email.PHOTO_URI, Email.PHOTO_THUMBNAIL_URI, Email.PHOTO_ID);
   1218     }
   1219 
   1220     private ContactInfo getContactInfoFromEnterpriseContactFilterUriInDirectory(String filter,
   1221             long directoryId) {
   1222         final Uri uri = Uri.withAppendedPath(Contacts.ENTERPRISE_CONTENT_FILTER_URI, filter)
   1223                 .buildUpon().appendQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY,
   1224                         String.valueOf(directoryId)).build();
   1225         return getContactInfoFromUri(uri, Contacts._ID, Contacts.DISPLAY_NAME_PRIMARY,
   1226                 Contacts.PHOTO_URI, Contacts.PHOTO_THUMBNAIL_URI, Contacts.PHOTO_ID);
   1227     }
   1228 
   1229     private ContactInfo getContactInfoFromEnterprisePhoneFilterUriInDirectory(String filter,
   1230             long directoryId) {
   1231         final Uri uri = Uri.withAppendedPath(Phone.ENTERPRISE_CONTENT_FILTER_URI, filter)
   1232                 .buildUpon().appendQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY,
   1233                         String.valueOf(directoryId)).build();
   1234         return getContactInfoFromUri(uri, Phone.CONTACT_ID, Phone.DISPLAY_NAME_PRIMARY,
   1235                 Phone.PHOTO_URI, Phone.PHOTO_THUMBNAIL_URI, Phone.PHOTO_ID);
   1236     }
   1237 
   1238 
   1239     private ContactInfo getContactInfoFromUri(Uri uri, String idColumn,
   1240             String displayNameColumn, String photoUriColumn, String photoThumbnailColumn,
   1241             String photoIdColumn) {
   1242         Cursor cursor = mResolver.query(uri,
   1243                 new String[] {
   1244                         idColumn,
   1245                         displayNameColumn,
   1246                         photoUriColumn,
   1247                         photoIdColumn,
   1248                         photoThumbnailColumn,
   1249                 }, null, null, null);
   1250         if (cursor == null) {
   1251             return null;
   1252         }
   1253         try {
   1254             if (cursor.moveToFirst()) {
   1255                 return new ContactInfo(
   1256                         cursor.getString(cursor.getColumnIndexOrThrow(idColumn)),
   1257                         cursor.getString(cursor.getColumnIndexOrThrow(displayNameColumn)),
   1258                         cursor.getString(cursor.getColumnIndexOrThrow(photoUriColumn)),
   1259                         cursor.getString(cursor.getColumnIndexOrThrow(photoThumbnailColumn)),
   1260                         cursor.getString(cursor.getColumnIndexOrThrow(photoIdColumn)));
   1261             }
   1262         } finally {
   1263             cursor.close();
   1264         }
   1265         return null;
   1266     }
   1267 
   1268     private void removeAllTestContactsInProfile() {
   1269         ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
   1270         ops.add(ContentProviderOperation.newDelete(RawContacts.CONTENT_URI)
   1271                 .withSelection(RawContacts.ACCOUNT_TYPE + "=?", new String[] {TEST_ACCOUNT_TYPE})
   1272                 .build());
   1273         try {
   1274             mResolver.applyBatch(ContactsContract.AUTHORITY, ops);
   1275         } catch (Exception e) {
   1276             // Catch all exceptions to let tearDown() run smoothly
   1277             e.printStackTrace();
   1278         }
   1279 
   1280         Account account = new Account(TEST_ACCOUNT_NAME, TEST_ACCOUNT_TYPE);
   1281         AccountManager.get(getContext()).removeAccountExplicitly(account);
   1282     }
   1283 
   1284     private InputStream getInputStreamFromUriForTest(String uriString) {
   1285         try {
   1286             return mResolver.openInputStream(Uri.parse(uriString));
   1287         } catch (FileNotFoundException e) {
   1288             fail(e.getMessage());
   1289             throw new RuntimeException(e);
   1290         }
   1291     }
   1292 
   1293     private static byte[] getByteFromStreamForTest(InputStream is) {
   1294         assertNotNull(is);
   1295         try (InputStream in = is) {
   1296             return getByteFromStream(in);
   1297         } catch (IOException e) {
   1298             fail(e.getMessage());
   1299             throw new RuntimeException(e);
   1300         }
   1301     }
   1302 
   1303     private static byte[] getByteFromStream(InputStream is) throws IOException {
   1304         ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
   1305         byte[] buf = new byte[1024 * 10];
   1306         int i = 0;
   1307         while ((i = is.read(buf, 0, buf.length)) > 0) {
   1308             outputStream.write(buf, 0, i);
   1309         }
   1310         return outputStream.toByteArray();
   1311     }
   1312 
   1313     private boolean isEnterpriseContactId(String contactId) {
   1314         return ContactsContract.Contacts.isEnterpriseContactId(Long.valueOf(contactId));
   1315     }
   1316 
   1317     private void assertPhotoUriReadable(String uri) {
   1318         assertNotNull(uri);
   1319         try (InputStream is = mResolver.openInputStream(Uri.parse(uri))) {
   1320             // Make sure it's readabe.  Don't have to read all content.
   1321             is.read();
   1322         } catch (IOException e) {
   1323             fail(e.getMessage());
   1324             throw new RuntimeException(e);
   1325         }
   1326     }
   1327 
   1328     private void assertFailWhenDirectoryParamMissing(Uri uri) {
   1329         try {
   1330             mResolver.query(uri, null, null, null, null);
   1331             fail("IllegalArgumentException is not thrown");
   1332         } catch (IllegalArgumentException ex) {
   1333         }
   1334     }
   1335 }
   1336